blob: 62af5bb8fff695c22af5d0ffa4a262e42cdb0685 [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
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000684 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000685 //
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() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000695 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
696 OldMethod->getRefQualifier() != NewMethod->getRefQualifier()))
John McCall1f82f242009-11-18 22:49:29 +0000697 return true;
698
699 // The signatures match; this is not an overload.
700 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000701}
702
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000703/// TryImplicitConversion - Attempt to perform an implicit conversion
704/// from the given expression (Expr) to the given type (ToType). This
705/// function returns an implicit conversion sequence that can be used
706/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000707///
708/// void f(float f);
709/// void g(int i) { f(i); }
710///
711/// this routine would produce an implicit conversion sequence to
712/// describe the initialization of f from i, which will be a standard
713/// conversion sequence containing an lvalue-to-rvalue conversion (C++
714/// 4.1) followed by a floating-integral conversion (C++ 4.9).
715//
716/// Note that this routine only determines how the conversion can be
717/// performed; it does not actually perform the conversion. As such,
718/// it will not produce any diagnostics if no conversion is available,
719/// but will instead return an implicit conversion sequence of kind
720/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000721///
722/// If @p SuppressUserConversions, then user-defined conversions are
723/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000724/// If @p AllowExplicit, then explicit user-defined conversions are
725/// permitted.
John McCall5c32be02010-08-24 20:38:10 +0000726static ImplicitConversionSequence
727TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
728 bool SuppressUserConversions,
729 bool AllowExplicit,
730 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000731 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000732 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
733 ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000734 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000735 return ICS;
736 }
737
John McCall5c32be02010-08-24 20:38:10 +0000738 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000739 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000740 return ICS;
741 }
742
Douglas Gregor836a7e82010-08-11 02:15:33 +0000743 // C++ [over.ics.user]p4:
744 // A conversion of an expression of class type to the same class
745 // type is given Exact Match rank, and a conversion of an
746 // expression of class type to a base class of that type is
747 // given Conversion rank, in spite of the fact that a copy/move
748 // constructor (i.e., a user-defined conversion function) is
749 // called for those cases.
750 QualType FromType = From->getType();
751 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000752 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
753 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000754 ICS.setStandard();
755 ICS.Standard.setAsIdentityConversion();
756 ICS.Standard.setFromType(FromType);
757 ICS.Standard.setAllToTypes(ToType);
758
759 // We don't actually check at this point whether there is a valid
760 // copy/move constructor, since overloading just assumes that it
761 // exists. When we actually perform initialization, we'll find the
762 // appropriate constructor to copy the returned object, if needed.
763 ICS.Standard.CopyConstructor = 0;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000764
Douglas Gregor5ab11652010-04-17 22:01:05 +0000765 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000766 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000767 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000768
769 return ICS;
770 }
771
772 if (SuppressUserConversions) {
773 // We're not in the case above, so there is no conversion that
774 // we can perform.
775 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000776 return ICS;
777 }
778
779 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000780 OverloadCandidateSet Conversions(From->getExprLoc());
781 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000782 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000783 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000784
785 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000786 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000787 // C++ [over.ics.user]p4:
788 // A conversion of an expression of class type to the same class
789 // type is given Exact Match rank, and a conversion of an
790 // expression of class type to a base class of that type is
791 // given Conversion rank, in spite of the fact that a copy
792 // constructor (i.e., a user-defined conversion function) is
793 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000794 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000795 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000796 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000797 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
798 QualType ToCanon
799 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000800 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000801 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000802 // Turn this into a "standard" conversion sequence, so that it
803 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000804 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000805 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000806 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000807 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000808 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000809 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000810 ICS.Standard.Second = ICK_Derived_To_Base;
811 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000812 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000813
814 // C++ [over.best.ics]p4:
815 // However, when considering the argument of a user-defined
816 // conversion function that is a candidate by 13.3.1.3 when
817 // invoked for the copying of the temporary in the second step
818 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
819 // 13.3.1.6 in all cases, only standard conversion sequences and
820 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000821 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000822 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000823 }
John McCalle8c8cd22010-01-13 22:30:33 +0000824 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000825 ICS.setAmbiguous();
826 ICS.Ambiguous.setFromType(From->getType());
827 ICS.Ambiguous.setToType(ToType);
828 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
829 Cand != Conversions.end(); ++Cand)
830 if (Cand->Viable)
831 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000832 } else {
John McCall65eb8792010-02-25 01:37:24 +0000833 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000834 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000835
836 return ICS;
837}
838
John McCall5c32be02010-08-24 20:38:10 +0000839bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
840 const InitializedEntity &Entity,
841 Expr *Initializer,
842 bool SuppressUserConversions,
843 bool AllowExplicitConversions,
844 bool InOverloadResolution) {
845 ImplicitConversionSequence ICS
846 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
847 SuppressUserConversions,
848 AllowExplicitConversions,
849 InOverloadResolution);
850 if (ICS.isBad()) return true;
851
852 // Perform the actual conversion.
853 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
854 return false;
855}
856
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000857/// PerformImplicitConversion - Perform an implicit conversion of the
858/// expression From to the type ToType. Returns true if there was an
859/// error, false otherwise. The expression From is replaced with the
860/// converted expression. Flavor is the kind of conversion we're
861/// performing, used in the error message. If @p AllowExplicit,
862/// explicit user-defined conversions are permitted.
863bool
864Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
865 AssignmentAction Action, bool AllowExplicit) {
866 ImplicitConversionSequence ICS;
867 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
868}
869
870bool
871Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
872 AssignmentAction Action, bool AllowExplicit,
873 ImplicitConversionSequence& ICS) {
John McCall5c32be02010-08-24 20:38:10 +0000874 ICS = clang::TryImplicitConversion(*this, From, ToType,
875 /*SuppressUserConversions=*/false,
876 AllowExplicit,
877 /*InOverloadResolution=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000878 return PerformImplicitConversion(From, ToType, ICS, Action);
879}
880
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000881/// \brief Determine whether the conversion from FromType to ToType is a valid
882/// conversion that strips "noreturn" off the nested function type.
883static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
884 QualType ToType, QualType &ResultTy) {
885 if (Context.hasSameUnqualifiedType(FromType, ToType))
886 return false;
887
John McCall991eb4b2010-12-21 00:44:39 +0000888 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
889 // where F adds one of the following at most once:
890 // - a pointer
891 // - a member pointer
892 // - a block pointer
893 CanQualType CanTo = Context.getCanonicalType(ToType);
894 CanQualType CanFrom = Context.getCanonicalType(FromType);
895 Type::TypeClass TyClass = CanTo->getTypeClass();
896 if (TyClass != CanFrom->getTypeClass()) return false;
897 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
898 if (TyClass == Type::Pointer) {
899 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
900 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
901 } else if (TyClass == Type::BlockPointer) {
902 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
903 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
904 } else if (TyClass == Type::MemberPointer) {
905 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
906 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
907 } else {
908 return false;
909 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000910
John McCall991eb4b2010-12-21 00:44:39 +0000911 TyClass = CanTo->getTypeClass();
912 if (TyClass != CanFrom->getTypeClass()) return false;
913 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
914 return false;
915 }
916
917 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
918 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
919 if (!EInfo.getNoReturn()) return false;
920
921 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
922 assert(QualType(FromFn, 0).isCanonical());
923 if (QualType(FromFn, 0) != CanTo) return false;
924
925 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000926 return true;
927}
Douglas Gregor46188682010-05-18 22:42:18 +0000928
929/// \brief Determine whether the conversion from FromType to ToType is a valid
930/// vector conversion.
931///
932/// \param ICK Will be set to the vector conversion kind, if this is a vector
933/// conversion.
934static bool IsVectorConversion(ASTContext &Context, QualType FromType,
935 QualType ToType, ImplicitConversionKind &ICK) {
936 // We need at least one of these types to be a vector type to have a vector
937 // conversion.
938 if (!ToType->isVectorType() && !FromType->isVectorType())
939 return false;
940
941 // Identical types require no conversions.
942 if (Context.hasSameUnqualifiedType(FromType, ToType))
943 return false;
944
945 // There are no conversions between extended vector types, only identity.
946 if (ToType->isExtVectorType()) {
947 // There are no conversions between extended vector types other than the
948 // identity conversion.
949 if (FromType->isExtVectorType())
950 return false;
951
952 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000953 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000954 ICK = ICK_Vector_Splat;
955 return true;
956 }
957 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000958
959 // We can perform the conversion between vector types in the following cases:
960 // 1)vector types are equivalent AltiVec and GCC vector types
961 // 2)lax vector conversions are permitted and the vector types are of the
962 // same size
963 if (ToType->isVectorType() && FromType->isVectorType()) {
964 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000965 (Context.getLangOptions().LaxVectorConversions &&
966 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000967 ICK = ICK_Vector_Conversion;
968 return true;
969 }
Douglas Gregor46188682010-05-18 22:42:18 +0000970 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000971
Douglas Gregor46188682010-05-18 22:42:18 +0000972 return false;
973}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000974
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000975/// IsStandardConversion - Determines whether there is a standard
976/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
977/// expression From to the type ToType. Standard conversion sequences
978/// only consider non-class types; for conversions that involve class
979/// types, use TryImplicitConversion. If a conversion exists, SCS will
980/// contain the standard conversion sequence required to perform this
981/// conversion and this routine will return true. Otherwise, this
982/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +0000983static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
984 bool InOverloadResolution,
985 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000986 QualType FromType = From->getType();
John McCall5c32be02010-08-24 20:38:10 +0000987
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000988 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000989 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000990 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000991 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000992 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000993 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000994
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000995 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000996 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000997 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +0000998 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000999 return false;
1000
Mike Stump11289f42009-09-09 15:08:12 +00001001 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001002 }
1003
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001004 // The first conversion can be an lvalue-to-rvalue conversion,
1005 // array-to-pointer conversion, or function-to-pointer conversion
1006 // (C++ 4p1).
1007
John McCall5c32be02010-08-24 20:38:10 +00001008 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001009 DeclAccessPair AccessPair;
1010 if (FunctionDecl *Fn
John McCall5c32be02010-08-24 20:38:10 +00001011 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1012 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001013 // We were able to resolve the address of the overloaded function,
1014 // so we can convert to the type of that function.
1015 FromType = Fn->getType();
1016 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
1017 if (!Method->isStatic()) {
John McCall424cec92011-01-19 06:33:43 +00001018 const Type *ClassType
John McCall5c32be02010-08-24 20:38:10 +00001019 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1020 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregor980fb162010-04-29 18:24:40 +00001021 }
1022 }
1023
1024 // If the "from" expression takes the address of the overloaded
1025 // function, update the type of the resulting expression accordingly.
1026 if (FromType->getAs<FunctionType>())
1027 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +00001028 if (UnOp->getOpcode() == UO_AddrOf)
John McCall5c32be02010-08-24 20:38:10 +00001029 FromType = S.Context.getPointerType(FromType);
Douglas Gregor980fb162010-04-29 18:24:40 +00001030
1031 // Check that we've computed the proper type after overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00001032 assert(S.Context.hasSameType(FromType,
1033 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001034 } else {
1035 return false;
1036 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001037 }
Mike Stump11289f42009-09-09 15:08:12 +00001038 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001039 // An lvalue (3.10) of a non-function, non-array type T can be
1040 // converted to an rvalue.
John McCall086a4642010-11-24 05:12:34 +00001041 bool argIsLValue = From->isLValue();
1042 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001043 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001044 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001045 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001046
1047 // If T is a non-class type, the type of the rvalue is the
1048 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001049 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1050 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001051 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001052 } else if (FromType->isArrayType()) {
1053 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001054 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001055
1056 // An lvalue or rvalue of type "array of N T" or "array of unknown
1057 // bound of T" can be converted to an rvalue of type "pointer to
1058 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001059 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001060
John McCall5c32be02010-08-24 20:38:10 +00001061 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001062 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001063 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001064
1065 // For the purpose of ranking in overload resolution
1066 // (13.3.3.1.1), this conversion is considered an
1067 // array-to-pointer conversion followed by a qualification
1068 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001069 SCS.Second = ICK_Identity;
1070 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001071 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001072 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001073 }
John McCall086a4642010-11-24 05:12:34 +00001074 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001075 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001076 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001077
1078 // An lvalue of function type T can be converted to an rvalue of
1079 // type "pointer to T." The result is a pointer to the
1080 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001081 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001082 } else {
1083 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001084 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001085 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001086 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001087
1088 // The second conversion can be an integral promotion, floating
1089 // point promotion, integral conversion, floating point conversion,
1090 // floating-integral conversion, pointer conversion,
1091 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001092 // For overloading in C, this can also be a "compatible-type"
1093 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001094 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001095 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001096 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001097 // The unqualified versions of the types are the same: there's no
1098 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001099 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001100 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001101 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001102 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001103 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001104 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001105 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001106 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001107 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001108 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001109 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001110 SCS.Second = ICK_Complex_Promotion;
1111 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001112 } else if (ToType->isBooleanType() &&
1113 (FromType->isArithmeticType() ||
1114 FromType->isAnyPointerType() ||
1115 FromType->isBlockPointerType() ||
1116 FromType->isMemberPointerType() ||
1117 FromType->isNullPtrType())) {
1118 // Boolean conversions (C++ 4.12).
1119 SCS.Second = ICK_Boolean_Conversion;
1120 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001121 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001122 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001123 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001124 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001125 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001126 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001127 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001128 SCS.Second = ICK_Complex_Conversion;
1129 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001130 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1131 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001132 // Complex-real conversions (C99 6.3.1.7)
1133 SCS.Second = ICK_Complex_Real;
1134 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001135 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001136 // Floating point conversions (C++ 4.8).
1137 SCS.Second = ICK_Floating_Conversion;
1138 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001139 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001140 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001141 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001142 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001143 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001144 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001145 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001146 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1147 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001148 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001149 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001150 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall5c32be02010-08-24 20:38:10 +00001151 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1152 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001153 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001154 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001155 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001156 SCS.Second = SecondICK;
1157 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001158 } else if (!S.getLangOptions().CPlusPlus &&
1159 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001160 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001161 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001162 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001163 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001164 // Treat a conversion that strips "noreturn" as an identity conversion.
1165 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001166 } else {
1167 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001168 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001169 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001170 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001171
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001172 QualType CanonFrom;
1173 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001174 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall5c32be02010-08-24 20:38:10 +00001175 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001176 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001177 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001178 CanonFrom = S.Context.getCanonicalType(FromType);
1179 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001180 } else {
1181 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001182 SCS.Third = ICK_Identity;
1183
Mike Stump11289f42009-09-09 15:08:12 +00001184 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001185 // [...] Any difference in top-level cv-qualification is
1186 // subsumed by the initialization itself and does not constitute
1187 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001188 CanonFrom = S.Context.getCanonicalType(FromType);
1189 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001190 if (CanonFrom.getLocalUnqualifiedType()
1191 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001192 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1193 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001194 FromType = ToType;
1195 CanonFrom = CanonTo;
1196 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001197 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001198 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001199
1200 // If we have not converted the argument type to the parameter type,
1201 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001202 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001203 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001204
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001205 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001206}
1207
1208/// IsIntegralPromotion - Determines whether the conversion from the
1209/// expression From (whose potentially-adjusted type is FromType) to
1210/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1211/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001212bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001213 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001214 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001215 if (!To) {
1216 return false;
1217 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001218
1219 // An rvalue of type char, signed char, unsigned char, short int, or
1220 // unsigned short int can be converted to an rvalue of type int if
1221 // int can represent all the values of the source type; otherwise,
1222 // the source rvalue can be converted to an rvalue of type unsigned
1223 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001224 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1225 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001226 if (// We can promote any signed, promotable integer type to an int
1227 (FromType->isSignedIntegerType() ||
1228 // We can promote any unsigned integer type whose size is
1229 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001230 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001231 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001232 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001233 }
1234
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001235 return To->getKind() == BuiltinType::UInt;
1236 }
1237
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001238 // C++0x [conv.prom]p3:
1239 // A prvalue of an unscoped enumeration type whose underlying type is not
1240 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1241 // following types that can represent all the values of the enumeration
1242 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1243 // unsigned int, long int, unsigned long int, long long int, or unsigned
1244 // long long int. If none of the types in that list can represent all the
1245 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1246 // type can be converted to an rvalue a prvalue of the extended integer type
1247 // with lowest integer conversion rank (4.13) greater than the rank of long
1248 // long in which all the values of the enumeration can be represented. If
1249 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001250 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1251 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1252 // provided for a scoped enumeration.
1253 if (FromEnumType->getDecl()->isScoped())
1254 return false;
1255
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001256 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001257 if (ToType->isIntegerType() &&
1258 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001259 return Context.hasSameUnqualifiedType(ToType,
1260 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001261 }
John McCall56774992009-12-09 09:09:27 +00001262
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001263 // C++0x [conv.prom]p2:
1264 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1265 // to an rvalue a prvalue of the first of the following types that can
1266 // represent all the values of its underlying type: int, unsigned int,
1267 // long int, unsigned long int, long long int, or unsigned long long int.
1268 // If none of the types in that list can represent all the values of its
1269 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1270 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1271 // type.
1272 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1273 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001274 // Determine whether the type we're converting from is signed or
1275 // unsigned.
1276 bool FromIsSigned;
1277 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001278
1279 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1280 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001281
1282 // The types we'll try to promote to, in the appropriate
1283 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001284 QualType PromoteTypes[6] = {
1285 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001286 Context.LongTy, Context.UnsignedLongTy ,
1287 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001288 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001289 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001290 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1291 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001292 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001293 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1294 // We found the type that we can promote to. If this is the
1295 // type we wanted, we have a promotion. Otherwise, no
1296 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001297 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001298 }
1299 }
1300 }
1301
1302 // An rvalue for an integral bit-field (9.6) can be converted to an
1303 // rvalue of type int if int can represent all the values of the
1304 // bit-field; otherwise, it can be converted to unsigned int if
1305 // unsigned int can represent all the values of the bit-field. If
1306 // the bit-field is larger yet, no integral promotion applies to
1307 // it. If the bit-field has an enumerated type, it is treated as any
1308 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001309 // FIXME: We should delay checking of bit-fields until we actually perform the
1310 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001311 using llvm::APSInt;
1312 if (From)
1313 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001314 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001315 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001316 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1317 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1318 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001319
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001320 // Are we promoting to an int from a bitfield that fits in an int?
1321 if (BitWidth < ToSize ||
1322 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1323 return To->getKind() == BuiltinType::Int;
1324 }
Mike Stump11289f42009-09-09 15:08:12 +00001325
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001326 // Are we promoting to an unsigned int from an unsigned bitfield
1327 // that fits into an unsigned int?
1328 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1329 return To->getKind() == BuiltinType::UInt;
1330 }
Mike Stump11289f42009-09-09 15:08:12 +00001331
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001332 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001333 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001334 }
Mike Stump11289f42009-09-09 15:08:12 +00001335
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001336 // An rvalue of type bool can be converted to an rvalue of type int,
1337 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001338 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001339 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001340 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001341
1342 return false;
1343}
1344
1345/// IsFloatingPointPromotion - Determines whether the conversion from
1346/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1347/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001348bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001349 /// An rvalue of type float can be converted to an rvalue of type
1350 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001351 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1352 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001353 if (FromBuiltin->getKind() == BuiltinType::Float &&
1354 ToBuiltin->getKind() == BuiltinType::Double)
1355 return true;
1356
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001357 // C99 6.3.1.5p1:
1358 // When a float is promoted to double or long double, or a
1359 // double is promoted to long double [...].
1360 if (!getLangOptions().CPlusPlus &&
1361 (FromBuiltin->getKind() == BuiltinType::Float ||
1362 FromBuiltin->getKind() == BuiltinType::Double) &&
1363 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1364 return true;
1365 }
1366
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001367 return false;
1368}
1369
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001370/// \brief Determine if a conversion is a complex promotion.
1371///
1372/// A complex promotion is defined as a complex -> complex conversion
1373/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001374/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001375bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001376 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001377 if (!FromComplex)
1378 return false;
1379
John McCall9dd450b2009-09-21 23:43:11 +00001380 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001381 if (!ToComplex)
1382 return false;
1383
1384 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001385 ToComplex->getElementType()) ||
1386 IsIntegralPromotion(0, FromComplex->getElementType(),
1387 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001388}
1389
Douglas Gregor237f96c2008-11-26 23:31:11 +00001390/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1391/// the pointer type FromPtr to a pointer to type ToPointee, with the
1392/// same type qualifiers as FromPtr has on its pointee type. ToType,
1393/// if non-empty, will be a pointer to ToType that may or may not have
1394/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001395static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001396BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001397 QualType ToPointee, QualType ToType,
1398 ASTContext &Context) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001399 assert((FromPtr->getTypeClass() == Type::Pointer ||
1400 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1401 "Invalid similarly-qualified pointer type");
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001402
1403 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1404 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1405 return ToType.getUnqualifiedType();
1406
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001407 QualType CanonFromPointee
1408 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001409 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001410 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001411
1412 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001413 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001414 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001415 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001416 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001417
1418 // Build a pointer to ToPointee. It has the right qualifiers
1419 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001420 if (isa<ObjCObjectPointerType>(ToType))
1421 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001422 return Context.getPointerType(ToPointee);
1423 }
1424
1425 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001426 QualType QualifiedCanonToPointee
1427 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001428
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001429 if (isa<ObjCObjectPointerType>(ToType))
1430 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1431 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001432}
1433
Mike Stump11289f42009-09-09 15:08:12 +00001434static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001435 bool InOverloadResolution,
1436 ASTContext &Context) {
1437 // Handle value-dependent integral null pointer constants correctly.
1438 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1439 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001440 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001441 return !InOverloadResolution;
1442
Douglas Gregor56751b52009-09-25 04:25:58 +00001443 return Expr->isNullPointerConstant(Context,
1444 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1445 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001446}
Mike Stump11289f42009-09-09 15:08:12 +00001447
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001448/// IsPointerConversion - Determines whether the conversion of the
1449/// expression From, which has the (possibly adjusted) type FromType,
1450/// can be converted to the type ToType via a pointer conversion (C++
1451/// 4.10). If so, returns true and places the converted type (that
1452/// might differ from ToType in its cv-qualifiers at some level) into
1453/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001454///
Douglas Gregora29dc052008-11-27 01:19:21 +00001455/// This routine also supports conversions to and from block pointers
1456/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1457/// pointers to interfaces. FIXME: Once we've determined the
1458/// appropriate overloading rules for Objective-C, we may want to
1459/// split the Objective-C checks into a different routine; however,
1460/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001461/// conversions, so for now they live here. IncompatibleObjC will be
1462/// set if the conversion is an allowed Objective-C conversion that
1463/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001464bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001465 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001466 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001467 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001468 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001469 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1470 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001471 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001472
Mike Stump11289f42009-09-09 15:08:12 +00001473 // Conversion from a null pointer constant to any Objective-C pointer type.
1474 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001475 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001476 ConvertedType = ToType;
1477 return true;
1478 }
1479
Douglas Gregor231d1c62008-11-27 00:15:41 +00001480 // Blocks: Block pointers can be converted to void*.
1481 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001482 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001483 ConvertedType = ToType;
1484 return true;
1485 }
1486 // Blocks: A null pointer constant can be converted to a block
1487 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001488 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001489 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001490 ConvertedType = ToType;
1491 return true;
1492 }
1493
Sebastian Redl576fd422009-05-10 18:38:11 +00001494 // If the left-hand-side is nullptr_t, the right side can be a null
1495 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001496 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001497 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001498 ConvertedType = ToType;
1499 return true;
1500 }
1501
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001502 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001503 if (!ToTypePtr)
1504 return false;
1505
1506 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001507 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001508 ConvertedType = ToType;
1509 return true;
1510 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001511
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001512 // Beyond this point, both types need to be pointers
1513 // , including objective-c pointers.
1514 QualType ToPointeeType = ToTypePtr->getPointeeType();
1515 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001516 ConvertedType = BuildSimilarlyQualifiedPointerType(
1517 FromType->getAs<ObjCObjectPointerType>(),
1518 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001519 ToType, Context);
1520 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001521 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001522 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001523 if (!FromTypePtr)
1524 return false;
1525
1526 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001527
Douglas Gregorfb640862010-08-18 21:25:30 +00001528 // If the unqualified pointee types are the same, this can't be a
1529 // pointer conversion, so don't do all of the work below.
1530 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1531 return false;
1532
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001533 // An rvalue of type "pointer to cv T," where T is an object type,
1534 // can be converted to an rvalue of type "pointer to cv void" (C++
1535 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001536 if (FromPointeeType->isIncompleteOrObjectType() &&
1537 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001538 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001539 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001540 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001541 return true;
1542 }
1543
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001544 // When we're overloading in C, we allow a special kind of pointer
1545 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001546 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001547 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001548 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001549 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001550 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001551 return true;
1552 }
1553
Douglas Gregor5c407d92008-10-23 00:40:37 +00001554 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001555 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001556 // An rvalue of type "pointer to cv D," where D is a class type,
1557 // can be converted to an rvalue of type "pointer to cv B," where
1558 // B is a base class (clause 10) of D. If B is an inaccessible
1559 // (clause 11) or ambiguous (10.2) base class of D, a program that
1560 // necessitates this conversion is ill-formed. The result of the
1561 // conversion is a pointer to the base class sub-object of the
1562 // derived class object. The null pointer value is converted to
1563 // the null pointer value of the destination type.
1564 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001565 // Note that we do not check for ambiguity or inaccessibility
1566 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001567 if (getLangOptions().CPlusPlus &&
1568 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001569 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001570 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001571 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001572 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001573 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001574 ToType, Context);
1575 return true;
1576 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001577
Douglas Gregora119f102008-12-19 19:13:09 +00001578 return false;
1579}
1580
1581/// isObjCPointerConversion - Determines whether this is an
1582/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1583/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001584bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001585 QualType& ConvertedType,
1586 bool &IncompatibleObjC) {
1587 if (!getLangOptions().ObjC1)
1588 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001589
Steve Naroff7cae42b2009-07-10 23:34:53 +00001590 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001591 const ObjCObjectPointerType* ToObjCPtr =
1592 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001593 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001594 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001595
Steve Naroff7cae42b2009-07-10 23:34:53 +00001596 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001597 // If the pointee types are the same (ignoring qualifications),
1598 // then this is not a pointer conversion.
1599 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1600 FromObjCPtr->getPointeeType()))
1601 return false;
1602
Steve Naroff1329fa02009-07-15 18:40:39 +00001603 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001604 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001605 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001606 ConvertedType = ToType;
1607 return true;
1608 }
1609 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001610 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001611 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001612 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001613 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001614 ConvertedType = ToType;
1615 return true;
1616 }
1617 // Objective C++: We're able to convert from a pointer to an
1618 // interface to a pointer to a different interface.
1619 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001620 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1621 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1622 if (getLangOptions().CPlusPlus && LHS && RHS &&
1623 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1624 FromObjCPtr->getPointeeType()))
1625 return false;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001626 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1627 ToObjCPtr->getPointeeType(),
1628 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001629 return true;
1630 }
1631
1632 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1633 // Okay: this is some kind of implicit downcast of Objective-C
1634 // interfaces, which is permitted. However, we're going to
1635 // complain about it.
1636 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001637 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1638 ToObjCPtr->getPointeeType(),
1639 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001640 return true;
1641 }
Mike Stump11289f42009-09-09 15:08:12 +00001642 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001643 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001644 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001645 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001646 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001647 else if (const BlockPointerType *ToBlockPtr =
1648 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001649 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001650 // to a block pointer type.
1651 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1652 ConvertedType = ToType;
1653 return true;
1654 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001655 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001656 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001657 else if (FromType->getAs<BlockPointerType>() &&
1658 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1659 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001660 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001661 ConvertedType = ToType;
1662 return true;
1663 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001664 else
Douglas Gregora119f102008-12-19 19:13:09 +00001665 return false;
1666
Douglas Gregor033f56d2008-12-23 00:53:59 +00001667 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001668 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001669 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001670 else if (const BlockPointerType *FromBlockPtr =
1671 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001672 FromPointeeType = FromBlockPtr->getPointeeType();
1673 else
Douglas Gregora119f102008-12-19 19:13:09 +00001674 return false;
1675
Douglas Gregora119f102008-12-19 19:13:09 +00001676 // If we have pointers to pointers, recursively check whether this
1677 // is an Objective-C conversion.
1678 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1679 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1680 IncompatibleObjC)) {
1681 // We always complain about this conversion.
1682 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001683 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregora119f102008-12-19 19:13:09 +00001684 return true;
1685 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001686 // Allow conversion of pointee being objective-c pointer to another one;
1687 // as in I* to id.
1688 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1689 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1690 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1691 IncompatibleObjC)) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001692 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001693 return true;
1694 }
1695
Douglas Gregor033f56d2008-12-23 00:53:59 +00001696 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001697 // differences in the argument and result types are in Objective-C
1698 // pointer conversions. If so, we permit the conversion (but
1699 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001700 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001701 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001702 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001703 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001704 if (FromFunctionType && ToFunctionType) {
1705 // If the function types are exactly the same, this isn't an
1706 // Objective-C pointer conversion.
1707 if (Context.getCanonicalType(FromPointeeType)
1708 == Context.getCanonicalType(ToPointeeType))
1709 return false;
1710
1711 // Perform the quick checks that will tell us whether these
1712 // function types are obviously different.
1713 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1714 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1715 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1716 return false;
1717
1718 bool HasObjCConversion = false;
1719 if (Context.getCanonicalType(FromFunctionType->getResultType())
1720 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1721 // Okay, the types match exactly. Nothing to do.
1722 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1723 ToFunctionType->getResultType(),
1724 ConvertedType, IncompatibleObjC)) {
1725 // Okay, we have an Objective-C pointer conversion.
1726 HasObjCConversion = true;
1727 } else {
1728 // Function types are too different. Abort.
1729 return false;
1730 }
Mike Stump11289f42009-09-09 15:08:12 +00001731
Douglas Gregora119f102008-12-19 19:13:09 +00001732 // Check argument types.
1733 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1734 ArgIdx != NumArgs; ++ArgIdx) {
1735 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1736 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1737 if (Context.getCanonicalType(FromArgType)
1738 == Context.getCanonicalType(ToArgType)) {
1739 // Okay, the types match exactly. Nothing to do.
1740 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1741 ConvertedType, IncompatibleObjC)) {
1742 // Okay, we have an Objective-C pointer conversion.
1743 HasObjCConversion = true;
1744 } else {
1745 // Argument types are too different. Abort.
1746 return false;
1747 }
1748 }
1749
1750 if (HasObjCConversion) {
1751 // We had an Objective-C conversion. Allow this pointer
1752 // conversion, but complain about it.
1753 ConvertedType = ToType;
1754 IncompatibleObjC = true;
1755 return true;
1756 }
1757 }
1758
Sebastian Redl72b597d2009-01-25 19:43:20 +00001759 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001760}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001761
1762/// FunctionArgTypesAreEqual - This routine checks two function proto types
1763/// for equlity of their argument types. Caller has already checked that
1764/// they have same number of arguments. This routine assumes that Objective-C
1765/// pointer types which only differ in their protocol qualifiers are equal.
John McCall424cec92011-01-19 06:33:43 +00001766bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
1767 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001768 if (!getLangOptions().ObjC1)
1769 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1770 NewType->arg_type_begin());
1771
1772 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1773 N = NewType->arg_type_begin(),
1774 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1775 QualType ToType = (*O);
1776 QualType FromType = (*N);
1777 if (ToType != FromType) {
1778 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1779 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001780 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1781 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1782 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1783 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001784 continue;
1785 }
John McCall8b07ec22010-05-15 11:32:37 +00001786 else if (const ObjCObjectPointerType *PTTo =
1787 ToType->getAs<ObjCObjectPointerType>()) {
1788 if (const ObjCObjectPointerType *PTFr =
1789 FromType->getAs<ObjCObjectPointerType>())
1790 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1791 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001792 }
1793 return false;
1794 }
1795 }
1796 return true;
1797}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001798
Douglas Gregor39c16d42008-10-24 04:54:22 +00001799/// CheckPointerConversion - Check the pointer conversion from the
1800/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001801/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001802/// conversions for which IsPointerConversion has already returned
1803/// true. It returns true and produces a diagnostic if there was an
1804/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001805bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001806 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001807 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001808 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001809 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001810 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001811
John McCall8cb679e2010-11-15 09:13:47 +00001812 Kind = CK_BitCast;
1813
Douglas Gregor4038cf42010-06-08 17:35:15 +00001814 if (CXXBoolLiteralExpr* LitBool
1815 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001816 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregor4038cf42010-06-08 17:35:15 +00001817 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1818 << ToType;
1819
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001820 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1821 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001822 QualType FromPointeeType = FromPtrType->getPointeeType(),
1823 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001824
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001825 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1826 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001827 // We must have a derived-to-base conversion. Check an
1828 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001829 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1830 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001831 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001832 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001833 return true;
1834
1835 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00001836 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001837 }
1838 }
Mike Stump11289f42009-09-09 15:08:12 +00001839 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00001840 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001841 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001842 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001843 // Objective-C++ conversions are always okay.
1844 // FIXME: We should have a different class of conversions for the
1845 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001846 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001847 return false;
John McCall8cb679e2010-11-15 09:13:47 +00001848 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001849 }
John McCall8cb679e2010-11-15 09:13:47 +00001850
1851 // We shouldn't fall into this case unless it's valid for other
1852 // reasons.
1853 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1854 Kind = CK_NullToPointer;
1855
Douglas Gregor39c16d42008-10-24 04:54:22 +00001856 return false;
1857}
1858
Sebastian Redl72b597d2009-01-25 19:43:20 +00001859/// IsMemberPointerConversion - Determines whether the conversion of the
1860/// expression From, which has the (possibly adjusted) type FromType, can be
1861/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1862/// If so, returns true and places the converted type (that might differ from
1863/// ToType in its cv-qualifiers at some level) into ConvertedType.
1864bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001865 QualType ToType,
1866 bool InOverloadResolution,
1867 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001868 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001869 if (!ToTypePtr)
1870 return false;
1871
1872 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001873 if (From->isNullPointerConstant(Context,
1874 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1875 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001876 ConvertedType = ToType;
1877 return true;
1878 }
1879
1880 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001881 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001882 if (!FromTypePtr)
1883 return false;
1884
1885 // A pointer to member of B can be converted to a pointer to member of D,
1886 // where D is derived from B (C++ 4.11p2).
1887 QualType FromClass(FromTypePtr->getClass(), 0);
1888 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001889
Douglas Gregor7f6ae692010-12-21 21:40:41 +00001890 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
1891 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
1892 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001893 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1894 ToClass.getTypePtr());
1895 return true;
1896 }
1897
1898 return false;
1899}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001900
Sebastian Redl72b597d2009-01-25 19:43:20 +00001901/// CheckMemberPointerConversion - Check the member pointer conversion from the
1902/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001903/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001904/// for which IsMemberPointerConversion has already returned true. It returns
1905/// true and produces a diagnostic if there was an error, or returns false
1906/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001907bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001908 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001909 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001910 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001911 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001912 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001913 if (!FromPtrType) {
1914 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001915 assert(From->isNullPointerConstant(Context,
1916 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001917 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00001918 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001919 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001920 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001921
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001922 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001923 assert(ToPtrType && "No member pointer cast has a target type "
1924 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001925
Sebastian Redled8f2002009-01-28 18:33:18 +00001926 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1927 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001928
Sebastian Redled8f2002009-01-28 18:33:18 +00001929 // FIXME: What about dependent types?
1930 assert(FromClass->isRecordType() && "Pointer into non-class.");
1931 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001932
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001933 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001934 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001935 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1936 assert(DerivationOkay &&
1937 "Should not have been called if derivation isn't OK.");
1938 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001939
Sebastian Redled8f2002009-01-28 18:33:18 +00001940 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1941 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001942 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1943 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1944 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1945 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001946 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001947
Douglas Gregor89ee6822009-02-28 01:32:25 +00001948 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001949 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1950 << FromClass << ToClass << QualType(VBase, 0)
1951 << From->getSourceRange();
1952 return true;
1953 }
1954
John McCall5b0829a2010-02-10 09:31:12 +00001955 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001956 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1957 Paths.front(),
1958 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001959
Anders Carlssond7923c62009-08-22 23:33:40 +00001960 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001961 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001962 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001963 return false;
1964}
1965
Douglas Gregor9a657932008-10-21 23:43:52 +00001966/// IsQualificationConversion - Determines whether the conversion from
1967/// an rvalue of type FromType to ToType is a qualification conversion
1968/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001969bool
1970Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001971 FromType = Context.getCanonicalType(FromType);
1972 ToType = Context.getCanonicalType(ToType);
1973
1974 // If FromType and ToType are the same type, this is not a
1975 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001976 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001977 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001978
Douglas Gregor9a657932008-10-21 23:43:52 +00001979 // (C++ 4.4p4):
1980 // A conversion can add cv-qualifiers at levels other than the first
1981 // in multi-level pointers, subject to the following rules: [...]
1982 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001983 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001984 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001985 // Within each iteration of the loop, we check the qualifiers to
1986 // determine if this still looks like a qualification
1987 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001988 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001989 // until there are no more pointers or pointers-to-members left to
1990 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001991 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001992
1993 // -- for every j > 0, if const is in cv 1,j then const is in cv
1994 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001995 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001996 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001997
Douglas Gregor9a657932008-10-21 23:43:52 +00001998 // -- if the cv 1,j and cv 2,j are different, then const is in
1999 // every cv for 0 < k < j.
2000 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002001 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002002 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002003
Douglas Gregor9a657932008-10-21 23:43:52 +00002004 // Keep track of whether all prior cv-qualifiers in the "to" type
2005 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002006 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00002007 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002008 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002009
2010 // We are left with FromType and ToType being the pointee types
2011 // after unwrapping the original FromType and ToType the same number
2012 // of types. If we unwrapped any pointers, and if FromType and
2013 // ToType have the same unqualified type (since we checked
2014 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002015 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002016}
2017
Douglas Gregor576e98c2009-01-30 23:27:23 +00002018/// Determines whether there is a user-defined conversion sequence
2019/// (C++ [over.ics.user]) that converts expression From to the type
2020/// ToType. If such a conversion exists, User will contain the
2021/// user-defined conversion sequence that performs such a conversion
2022/// and this routine will return true. Otherwise, this routine returns
2023/// false and User is unspecified.
2024///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002025/// \param AllowExplicit true if the conversion should consider C++0x
2026/// "explicit" conversion functions as well as non-explicit conversion
2027/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002028static OverloadingResult
2029IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2030 UserDefinedConversionSequence& User,
2031 OverloadCandidateSet& CandidateSet,
2032 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002033 // Whether we will only visit constructors.
2034 bool ConstructorsOnly = false;
2035
2036 // If the type we are conversion to is a class type, enumerate its
2037 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002038 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002039 // C++ [over.match.ctor]p1:
2040 // When objects of class type are direct-initialized (8.5), or
2041 // copy-initialized from an expression of the same or a
2042 // derived class type (8.5), overload resolution selects the
2043 // constructor. [...] For copy-initialization, the candidate
2044 // functions are all the converting constructors (12.3.1) of
2045 // that class. The argument list is the expression-list within
2046 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002047 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002048 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002049 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002050 ConstructorsOnly = true;
2051
John McCall5c32be02010-08-24 20:38:10 +00002052 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002053 // We're not going to find any constructors.
2054 } else if (CXXRecordDecl *ToRecordDecl
2055 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002056 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002057 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002058 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002059 NamedDecl *D = *Con;
2060 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2061
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002062 // Find the constructor (which may be a template).
2063 CXXConstructorDecl *Constructor = 0;
2064 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002065 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002066 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002067 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002068 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2069 else
John McCalla0296f72010-03-19 07:35:19 +00002070 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002071
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002072 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002073 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002074 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002075 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2076 /*ExplicitArgs*/ 0,
2077 &From, 1, CandidateSet,
2078 /*SuppressUserConversions=*/
2079 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002080 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002081 // Allow one user-defined conversion when user specifies a
2082 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002083 S.AddOverloadCandidate(Constructor, FoundDecl,
2084 &From, 1, CandidateSet,
2085 /*SuppressUserConversions=*/
2086 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002087 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002088 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002089 }
2090 }
2091
Douglas Gregor5ab11652010-04-17 22:01:05 +00002092 // Enumerate conversion functions, if we're allowed to.
2093 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002094 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2095 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002096 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002097 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002098 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002099 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002100 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2101 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002102 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002103 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002104 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002105 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002106 DeclAccessPair FoundDecl = I.getPair();
2107 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002108 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2109 if (isa<UsingShadowDecl>(D))
2110 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2111
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002112 CXXConversionDecl *Conv;
2113 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002114 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2115 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002116 else
John McCallda4458e2010-03-31 01:36:47 +00002117 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002118
2119 if (AllowExplicit || !Conv->isExplicit()) {
2120 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002121 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2122 ActingContext, From, ToType,
2123 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002124 else
John McCall5c32be02010-08-24 20:38:10 +00002125 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2126 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002127 }
2128 }
2129 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002130 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002131
2132 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002133 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002134 case OR_Success:
2135 // Record the standard conversion we used and the conversion function.
2136 if (CXXConstructorDecl *Constructor
2137 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2138 // C++ [over.ics.user]p1:
2139 // If the user-defined conversion is specified by a
2140 // constructor (12.3.1), the initial standard conversion
2141 // sequence converts the source type to the type required by
2142 // the argument of the constructor.
2143 //
2144 QualType ThisType = Constructor->getThisType(S.Context);
2145 if (Best->Conversions[0].isEllipsis())
2146 User.EllipsisConversion = true;
2147 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002148 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002149 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002150 }
John McCall5c32be02010-08-24 20:38:10 +00002151 User.ConversionFunction = Constructor;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002152 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002153 User.After.setAsIdentityConversion();
2154 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2155 User.After.setAllToTypes(ToType);
2156 return OR_Success;
2157 } else if (CXXConversionDecl *Conversion
2158 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2159 // C++ [over.ics.user]p1:
2160 //
2161 // [...] If the user-defined conversion is specified by a
2162 // conversion function (12.3.2), the initial standard
2163 // conversion sequence converts the source type to the
2164 // implicit object parameter of the conversion function.
2165 User.Before = Best->Conversions[0].Standard;
2166 User.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002167 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002168 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002169
John McCall5c32be02010-08-24 20:38:10 +00002170 // C++ [over.ics.user]p2:
2171 // The second standard conversion sequence converts the
2172 // result of the user-defined conversion to the target type
2173 // for the sequence. Since an implicit conversion sequence
2174 // is an initialization, the special rules for
2175 // initialization by user-defined conversion apply when
2176 // selecting the best user-defined conversion for a
2177 // user-defined conversion sequence (see 13.3.3 and
2178 // 13.3.3.1).
2179 User.After = Best->FinalConversion;
2180 return OR_Success;
2181 } else {
2182 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002183 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002184 }
2185
John McCall5c32be02010-08-24 20:38:10 +00002186 case OR_No_Viable_Function:
2187 return OR_No_Viable_Function;
2188 case OR_Deleted:
2189 // No conversion here! We're done.
2190 return OR_Deleted;
2191
2192 case OR_Ambiguous:
2193 return OR_Ambiguous;
2194 }
2195
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002196 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002197}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002198
2199bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002200Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002201 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002202 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002203 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002204 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002205 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002206 if (OvResult == OR_Ambiguous)
2207 Diag(From->getSourceRange().getBegin(),
2208 diag::err_typecheck_ambiguous_condition)
2209 << From->getType() << ToType << From->getSourceRange();
2210 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2211 Diag(From->getSourceRange().getBegin(),
2212 diag::err_typecheck_nonviable_condition)
2213 << From->getType() << ToType << From->getSourceRange();
2214 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002215 return false;
John McCall5c32be02010-08-24 20:38:10 +00002216 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002217 return true;
2218}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002219
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002220/// CompareImplicitConversionSequences - Compare two implicit
2221/// conversion sequences to determine whether one is better than the
2222/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002223static ImplicitConversionSequence::CompareKind
2224CompareImplicitConversionSequences(Sema &S,
2225 const ImplicitConversionSequence& ICS1,
2226 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002227{
2228 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2229 // conversion sequences (as defined in 13.3.3.1)
2230 // -- a standard conversion sequence (13.3.3.1.1) is a better
2231 // conversion sequence than a user-defined conversion sequence or
2232 // an ellipsis conversion sequence, and
2233 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2234 // conversion sequence than an ellipsis conversion sequence
2235 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002236 //
John McCall0d1da222010-01-12 00:44:57 +00002237 // C++0x [over.best.ics]p10:
2238 // For the purpose of ranking implicit conversion sequences as
2239 // described in 13.3.3.2, the ambiguous conversion sequence is
2240 // treated as a user-defined sequence that is indistinguishable
2241 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002242 if (ICS1.getKindRank() < ICS2.getKindRank())
2243 return ImplicitConversionSequence::Better;
2244 else if (ICS2.getKindRank() < ICS1.getKindRank())
2245 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002246
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002247 // The following checks require both conversion sequences to be of
2248 // the same kind.
2249 if (ICS1.getKind() != ICS2.getKind())
2250 return ImplicitConversionSequence::Indistinguishable;
2251
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002252 // Two implicit conversion sequences of the same form are
2253 // indistinguishable conversion sequences unless one of the
2254 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002255 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002256 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002257 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002258 // User-defined conversion sequence U1 is a better conversion
2259 // sequence than another user-defined conversion sequence U2 if
2260 // they contain the same user-defined conversion function or
2261 // constructor and if the second standard conversion sequence of
2262 // U1 is better than the second standard conversion sequence of
2263 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002264 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002265 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002266 return CompareStandardConversionSequences(S,
2267 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002268 ICS2.UserDefined.After);
2269 }
2270
2271 return ImplicitConversionSequence::Indistinguishable;
2272}
2273
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002274static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2275 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2276 Qualifiers Quals;
2277 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2278 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2279 }
2280
2281 return Context.hasSameUnqualifiedType(T1, T2);
2282}
2283
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002284// Per 13.3.3.2p3, compare the given standard conversion sequences to
2285// determine if one is a proper subset of the other.
2286static ImplicitConversionSequence::CompareKind
2287compareStandardConversionSubsets(ASTContext &Context,
2288 const StandardConversionSequence& SCS1,
2289 const StandardConversionSequence& SCS2) {
2290 ImplicitConversionSequence::CompareKind Result
2291 = ImplicitConversionSequence::Indistinguishable;
2292
Douglas Gregore87561a2010-05-23 22:10:15 +00002293 // the identity conversion sequence is considered to be a subsequence of
2294 // any non-identity conversion sequence
2295 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2296 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2297 return ImplicitConversionSequence::Better;
2298 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2299 return ImplicitConversionSequence::Worse;
2300 }
2301
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002302 if (SCS1.Second != SCS2.Second) {
2303 if (SCS1.Second == ICK_Identity)
2304 Result = ImplicitConversionSequence::Better;
2305 else if (SCS2.Second == ICK_Identity)
2306 Result = ImplicitConversionSequence::Worse;
2307 else
2308 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002309 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002310 return ImplicitConversionSequence::Indistinguishable;
2311
2312 if (SCS1.Third == SCS2.Third) {
2313 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2314 : ImplicitConversionSequence::Indistinguishable;
2315 }
2316
2317 if (SCS1.Third == ICK_Identity)
2318 return Result == ImplicitConversionSequence::Worse
2319 ? ImplicitConversionSequence::Indistinguishable
2320 : ImplicitConversionSequence::Better;
2321
2322 if (SCS2.Third == ICK_Identity)
2323 return Result == ImplicitConversionSequence::Better
2324 ? ImplicitConversionSequence::Indistinguishable
2325 : ImplicitConversionSequence::Worse;
2326
2327 return ImplicitConversionSequence::Indistinguishable;
2328}
2329
Douglas Gregore696ebb2011-01-26 14:52:12 +00002330/// \brief Determine whether one of the given reference bindings is better
2331/// than the other based on what kind of bindings they are.
2332static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2333 const StandardConversionSequence &SCS2) {
2334 // C++0x [over.ics.rank]p3b4:
2335 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2336 // implicit object parameter of a non-static member function declared
2337 // without a ref-qualifier, and *either* S1 binds an rvalue reference
2338 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
2339 // lvalue reference to a function lvalue and S2 binds an rvalue
2340 // reference*.
2341 //
2342 // FIXME: Rvalue references. We're going rogue with the above edits,
2343 // because the semantics in the current C++0x working paper (N3225 at the
2344 // time of this writing) break the standard definition of std::forward
2345 // and std::reference_wrapper when dealing with references to functions.
2346 // Proposed wording changes submitted to CWG for consideration.
2347 //
Douglas Gregor02824322011-01-26 19:30:28 +00002348 // Note: neither of these conditions will evalute true for the implicit
2349 // object parameter, because we don't set either BindsToRvalue or
2350 // BindsToFunctionLvalue when computing the conversion sequence for the
2351 // implicit object parameter.
Douglas Gregore696ebb2011-01-26 14:52:12 +00002352 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2353 SCS2.IsLvalueReference) ||
2354 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2355 !SCS2.IsLvalueReference);
2356}
2357
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002358/// CompareStandardConversionSequences - Compare two standard
2359/// conversion sequences to determine whether one is better than the
2360/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002361static ImplicitConversionSequence::CompareKind
2362CompareStandardConversionSequences(Sema &S,
2363 const StandardConversionSequence& SCS1,
2364 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002365{
2366 // Standard conversion sequence S1 is a better conversion sequence
2367 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2368
2369 // -- S1 is a proper subsequence of S2 (comparing the conversion
2370 // sequences in the canonical form defined by 13.3.3.1.1,
2371 // excluding any Lvalue Transformation; the identity conversion
2372 // sequence is considered to be a subsequence of any
2373 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002374 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002375 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002376 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002377
2378 // -- the rank of S1 is better than the rank of S2 (by the rules
2379 // defined below), or, if not that,
2380 ImplicitConversionRank Rank1 = SCS1.getRank();
2381 ImplicitConversionRank Rank2 = SCS2.getRank();
2382 if (Rank1 < Rank2)
2383 return ImplicitConversionSequence::Better;
2384 else if (Rank2 < Rank1)
2385 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002386
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002387 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2388 // are indistinguishable unless one of the following rules
2389 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002390
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002391 // A conversion that is not a conversion of a pointer, or
2392 // pointer to member, to bool is better than another conversion
2393 // that is such a conversion.
2394 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2395 return SCS2.isPointerConversionToBool()
2396 ? ImplicitConversionSequence::Better
2397 : ImplicitConversionSequence::Worse;
2398
Douglas Gregor5c407d92008-10-23 00:40:37 +00002399 // C++ [over.ics.rank]p4b2:
2400 //
2401 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002402 // conversion of B* to A* is better than conversion of B* to
2403 // void*, and conversion of A* to void* is better than conversion
2404 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002405 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002406 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002407 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002408 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002409 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2410 // Exactly one of the conversion sequences is a conversion to
2411 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002412 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2413 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002414 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2415 // Neither conversion sequence converts to a void pointer; compare
2416 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002417 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002418 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002419 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002420 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2421 // Both conversion sequences are conversions to void
2422 // pointers. Compare the source types to determine if there's an
2423 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002424 QualType FromType1 = SCS1.getFromType();
2425 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002426
2427 // Adjust the types we're converting from via the array-to-pointer
2428 // conversion, if we need to.
2429 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002430 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002431 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002432 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002433
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002434 QualType FromPointee1
2435 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2436 QualType FromPointee2
2437 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002438
John McCall5c32be02010-08-24 20:38:10 +00002439 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002440 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002441 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002442 return ImplicitConversionSequence::Worse;
2443
2444 // Objective-C++: If one interface is more specific than the
2445 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002446 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2447 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002448 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002449 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002450 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002451 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002452 return ImplicitConversionSequence::Worse;
2453 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002454 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002455
2456 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2457 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002458 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002459 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002460 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002461
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002462 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002463 // Check for a better reference binding based on the kind of bindings.
2464 if (isBetterReferenceBindingKind(SCS1, SCS2))
2465 return ImplicitConversionSequence::Better;
2466 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2467 return ImplicitConversionSequence::Worse;
2468
Sebastian Redlb28b4072009-03-22 23:49:27 +00002469 // C++ [over.ics.rank]p3b4:
2470 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2471 // which the references refer are the same type except for
2472 // top-level cv-qualifiers, and the type to which the reference
2473 // initialized by S2 refers is more cv-qualified than the type
2474 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002475 QualType T1 = SCS1.getToType(2);
2476 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002477 T1 = S.Context.getCanonicalType(T1);
2478 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002479 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002480 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2481 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002482 if (UnqualT1 == UnqualT2) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00002483 // If the type is an array type, promote the element qualifiers to the
2484 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002485 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002486 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002487 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002488 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002489 if (T2.isMoreQualifiedThan(T1))
2490 return ImplicitConversionSequence::Better;
2491 else if (T1.isMoreQualifiedThan(T2))
2492 return ImplicitConversionSequence::Worse;
2493 }
2494 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002495
2496 return ImplicitConversionSequence::Indistinguishable;
2497}
2498
2499/// CompareQualificationConversions - Compares two standard conversion
2500/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002501/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2502ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002503CompareQualificationConversions(Sema &S,
2504 const StandardConversionSequence& SCS1,
2505 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002506 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002507 // -- S1 and S2 differ only in their qualification conversion and
2508 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2509 // cv-qualification signature of type T1 is a proper subset of
2510 // the cv-qualification signature of type T2, and S1 is not the
2511 // deprecated string literal array-to-pointer conversion (4.2).
2512 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2513 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2514 return ImplicitConversionSequence::Indistinguishable;
2515
2516 // FIXME: the example in the standard doesn't use a qualification
2517 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002518 QualType T1 = SCS1.getToType(2);
2519 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002520 T1 = S.Context.getCanonicalType(T1);
2521 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002522 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002523 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2524 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002525
2526 // If the types are the same, we won't learn anything by unwrapped
2527 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002528 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002529 return ImplicitConversionSequence::Indistinguishable;
2530
Chandler Carruth607f38e2009-12-29 07:16:59 +00002531 // If the type is an array type, promote the element qualifiers to the type
2532 // for comparison.
2533 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002534 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002535 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002536 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002537
Mike Stump11289f42009-09-09 15:08:12 +00002538 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002539 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002540 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002541 // Within each iteration of the loop, we check the qualifiers to
2542 // determine if this still looks like a qualification
2543 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002544 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002545 // until there are no more pointers or pointers-to-members left
2546 // to unwrap. This essentially mimics what
2547 // IsQualificationConversion does, but here we're checking for a
2548 // strict subset of qualifiers.
2549 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2550 // The qualifiers are the same, so this doesn't tell us anything
2551 // about how the sequences rank.
2552 ;
2553 else if (T2.isMoreQualifiedThan(T1)) {
2554 // T1 has fewer qualifiers, so it could be the better sequence.
2555 if (Result == ImplicitConversionSequence::Worse)
2556 // Neither has qualifiers that are a subset of the other's
2557 // qualifiers.
2558 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002559
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002560 Result = ImplicitConversionSequence::Better;
2561 } else if (T1.isMoreQualifiedThan(T2)) {
2562 // T2 has fewer qualifiers, so it could be the better sequence.
2563 if (Result == ImplicitConversionSequence::Better)
2564 // Neither has qualifiers that are a subset of the other's
2565 // qualifiers.
2566 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002567
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002568 Result = ImplicitConversionSequence::Worse;
2569 } else {
2570 // Qualifiers are disjoint.
2571 return ImplicitConversionSequence::Indistinguishable;
2572 }
2573
2574 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002575 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002576 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002577 }
2578
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002579 // Check that the winning standard conversion sequence isn't using
2580 // the deprecated string literal array to pointer conversion.
2581 switch (Result) {
2582 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002583 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002584 Result = ImplicitConversionSequence::Indistinguishable;
2585 break;
2586
2587 case ImplicitConversionSequence::Indistinguishable:
2588 break;
2589
2590 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002591 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002592 Result = ImplicitConversionSequence::Indistinguishable;
2593 break;
2594 }
2595
2596 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002597}
2598
Douglas Gregor5c407d92008-10-23 00:40:37 +00002599/// CompareDerivedToBaseConversions - Compares two standard conversion
2600/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002601/// various kinds of derived-to-base conversions (C++
2602/// [over.ics.rank]p4b3). As part of these checks, we also look at
2603/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002604ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002605CompareDerivedToBaseConversions(Sema &S,
2606 const StandardConversionSequence& SCS1,
2607 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002608 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002609 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002610 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002611 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002612
2613 // Adjust the types we're converting from via the array-to-pointer
2614 // conversion, if we need to.
2615 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002616 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002617 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002618 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002619
2620 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002621 FromType1 = S.Context.getCanonicalType(FromType1);
2622 ToType1 = S.Context.getCanonicalType(ToType1);
2623 FromType2 = S.Context.getCanonicalType(FromType2);
2624 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002625
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002626 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002627 //
2628 // If class B is derived directly or indirectly from class A and
2629 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002630 //
2631 // For Objective-C, we let A, B, and C also be Objective-C
2632 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002633
2634 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002635 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002636 SCS2.Second == ICK_Pointer_Conversion &&
2637 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2638 FromType1->isPointerType() && FromType2->isPointerType() &&
2639 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002640 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002641 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002642 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002643 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002644 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002645 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002646 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002647 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002648
John McCall8b07ec22010-05-15 11:32:37 +00002649 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2650 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2651 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2652 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002653
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002654 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002655 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002656 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002657 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002658 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002659 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002660
2661 if (ToIface1 && ToIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002662 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002663 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002664 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002665 return ImplicitConversionSequence::Worse;
2666 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002667 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002668
2669 // -- conversion of B* to A* is better than conversion of C* to A*,
2670 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002671 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002672 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002673 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002674 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002675
Douglas Gregor237f96c2008-11-26 23:31:11 +00002676 if (FromIface1 && FromIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002677 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002678 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002679 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002680 return ImplicitConversionSequence::Worse;
2681 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002682 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002683 }
2684
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002685 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002686 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2687 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2688 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2689 const MemberPointerType * FromMemPointer1 =
2690 FromType1->getAs<MemberPointerType>();
2691 const MemberPointerType * ToMemPointer1 =
2692 ToType1->getAs<MemberPointerType>();
2693 const MemberPointerType * FromMemPointer2 =
2694 FromType2->getAs<MemberPointerType>();
2695 const MemberPointerType * ToMemPointer2 =
2696 ToType2->getAs<MemberPointerType>();
2697 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2698 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2699 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2700 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2701 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2702 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2703 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2704 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002705 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002706 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002707 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002708 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002709 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002710 return ImplicitConversionSequence::Better;
2711 }
2712 // conversion of B::* to C::* is better than conversion of A::* to C::*
2713 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002714 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002715 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002716 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002717 return ImplicitConversionSequence::Worse;
2718 }
2719 }
2720
Douglas Gregor5ab11652010-04-17 22:01:05 +00002721 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002722 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002723 // -- binding of an expression of type C to a reference of type
2724 // B& is better than binding an expression of type C to a
2725 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002726 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2727 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2728 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002729 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002730 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002731 return ImplicitConversionSequence::Worse;
2732 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002733
Douglas Gregor2fe98832008-11-03 19:09:14 +00002734 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002735 // -- binding of an expression of type B to a reference of type
2736 // A& is better than binding an expression of type C to a
2737 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002738 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2739 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2740 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002741 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002742 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002743 return ImplicitConversionSequence::Worse;
2744 }
2745 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002746
Douglas Gregor5c407d92008-10-23 00:40:37 +00002747 return ImplicitConversionSequence::Indistinguishable;
2748}
2749
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002750/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2751/// determine whether they are reference-related,
2752/// reference-compatible, reference-compatible with added
2753/// qualification, or incompatible, for use in C++ initialization by
2754/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2755/// type, and the first type (T1) is the pointee type of the reference
2756/// type being initialized.
2757Sema::ReferenceCompareResult
2758Sema::CompareReferenceRelationship(SourceLocation Loc,
2759 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002760 bool &DerivedToBase,
2761 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002762 assert(!OrigT1->isReferenceType() &&
2763 "T1 must be the pointee type of the reference type");
2764 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2765
2766 QualType T1 = Context.getCanonicalType(OrigT1);
2767 QualType T2 = Context.getCanonicalType(OrigT2);
2768 Qualifiers T1Quals, T2Quals;
2769 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2770 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2771
2772 // C++ [dcl.init.ref]p4:
2773 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2774 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2775 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002776 DerivedToBase = false;
2777 ObjCConversion = false;
2778 if (UnqualT1 == UnqualT2) {
2779 // Nothing to do.
2780 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002781 IsDerivedFrom(UnqualT2, UnqualT1))
2782 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002783 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2784 UnqualT2->isObjCObjectOrInterfaceType() &&
2785 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2786 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002787 else
2788 return Ref_Incompatible;
2789
2790 // At this point, we know that T1 and T2 are reference-related (at
2791 // least).
2792
2793 // If the type is an array type, promote the element qualifiers to the type
2794 // for comparison.
2795 if (isa<ArrayType>(T1) && T1Quals)
2796 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2797 if (isa<ArrayType>(T2) && T2Quals)
2798 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2799
2800 // C++ [dcl.init.ref]p4:
2801 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2802 // reference-related to T2 and cv1 is the same cv-qualification
2803 // as, or greater cv-qualification than, cv2. For purposes of
2804 // overload resolution, cases for which cv1 is greater
2805 // cv-qualification than cv2 are identified as
2806 // reference-compatible with added qualification (see 13.3.3.2).
2807 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2808 return Ref_Compatible;
2809 else if (T1.isMoreQualifiedThan(T2))
2810 return Ref_Compatible_With_Added_Qualification;
2811 else
2812 return Ref_Related;
2813}
2814
Douglas Gregor836a7e82010-08-11 02:15:33 +00002815/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002816/// with DeclType. Return true if something definite is found.
2817static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002818FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2819 QualType DeclType, SourceLocation DeclLoc,
2820 Expr *Init, QualType T2, bool AllowRvalues,
2821 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002822 assert(T2->isRecordType() && "Can only find conversions of record types.");
2823 CXXRecordDecl *T2RecordDecl
2824 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2825
2826 OverloadCandidateSet CandidateSet(DeclLoc);
2827 const UnresolvedSetImpl *Conversions
2828 = T2RecordDecl->getVisibleConversionFunctions();
2829 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2830 E = Conversions->end(); I != E; ++I) {
2831 NamedDecl *D = *I;
2832 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2833 if (isa<UsingShadowDecl>(D))
2834 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2835
2836 FunctionTemplateDecl *ConvTemplate
2837 = dyn_cast<FunctionTemplateDecl>(D);
2838 CXXConversionDecl *Conv;
2839 if (ConvTemplate)
2840 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2841 else
2842 Conv = cast<CXXConversionDecl>(D);
2843
Douglas Gregor836a7e82010-08-11 02:15:33 +00002844 // If this is an explicit conversion, and we're not allowed to consider
2845 // explicit conversions, skip it.
2846 if (!AllowExplicit && Conv->isExplicit())
2847 continue;
2848
2849 if (AllowRvalues) {
2850 bool DerivedToBase = false;
2851 bool ObjCConversion = false;
2852 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00002853 S.CompareReferenceRelationship(
2854 DeclLoc,
2855 Conv->getConversionType().getNonReferenceType()
2856 .getUnqualifiedType(),
2857 DeclType.getNonReferenceType().getUnqualifiedType(),
2858 DerivedToBase, ObjCConversion) ==
2859 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00002860 continue;
2861 } else {
2862 // If the conversion function doesn't return a reference type,
2863 // it can't be considered for this conversion. An rvalue reference
2864 // is only acceptable if its referencee is a function type.
2865
2866 const ReferenceType *RefType =
2867 Conv->getConversionType()->getAs<ReferenceType>();
2868 if (!RefType ||
2869 (!RefType->isLValueReferenceType() &&
2870 !RefType->getPointeeType()->isFunctionType()))
2871 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002872 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002873
2874 if (ConvTemplate)
2875 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00002876 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00002877 else
2878 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00002879 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002880 }
2881
2882 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002883 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002884 case OR_Success:
2885 // C++ [over.ics.ref]p1:
2886 //
2887 // [...] If the parameter binds directly to the result of
2888 // applying a conversion function to the argument
2889 // expression, the implicit conversion sequence is a
2890 // user-defined conversion sequence (13.3.3.1.2), with the
2891 // second standard conversion sequence either an identity
2892 // conversion or, if the conversion function returns an
2893 // entity of a type that is a derived class of the parameter
2894 // type, a derived-to-base Conversion.
2895 if (!Best->FinalConversion.DirectBinding)
2896 return false;
2897
2898 ICS.setUserDefined();
2899 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2900 ICS.UserDefined.After = Best->FinalConversion;
2901 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002902 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redld92badf2010-06-30 18:13:39 +00002903 ICS.UserDefined.EllipsisConversion = false;
2904 assert(ICS.UserDefined.After.ReferenceBinding &&
2905 ICS.UserDefined.After.DirectBinding &&
2906 "Expected a direct reference binding!");
2907 return true;
2908
2909 case OR_Ambiguous:
2910 ICS.setAmbiguous();
2911 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2912 Cand != CandidateSet.end(); ++Cand)
2913 if (Cand->Viable)
2914 ICS.Ambiguous.addConversion(Cand->Function);
2915 return true;
2916
2917 case OR_No_Viable_Function:
2918 case OR_Deleted:
2919 // There was no suitable conversion, or we found a deleted
2920 // conversion; continue with other checks.
2921 return false;
2922 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002923
2924 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002925}
2926
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002927/// \brief Compute an implicit conversion sequence for reference
2928/// initialization.
2929static ImplicitConversionSequence
2930TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2931 SourceLocation DeclLoc,
2932 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002933 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002934 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2935
2936 // Most paths end in a failed conversion.
2937 ImplicitConversionSequence ICS;
2938 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2939
2940 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2941 QualType T2 = Init->getType();
2942
2943 // If the initializer is the address of an overloaded function, try
2944 // to resolve the overloaded function. If all goes well, T2 is the
2945 // type of the resulting function.
2946 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2947 DeclAccessPair Found;
2948 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2949 false, Found))
2950 T2 = Fn->getType();
2951 }
2952
2953 // Compute some basic properties of the types and the initializer.
2954 bool isRValRef = DeclType->isRValueReferenceType();
2955 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002956 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002957 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002958 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002959 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2960 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002961
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002962
Sebastian Redld92badf2010-06-30 18:13:39 +00002963 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002964 // A reference to type "cv1 T1" is initialized by an expression
2965 // of type "cv2 T2" as follows:
2966
Sebastian Redld92badf2010-06-30 18:13:39 +00002967 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00002968 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002969 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2970 // reference-compatible with "cv2 T2," or
2971 //
2972 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2973 if (InitCategory.isLValue() &&
2974 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002975 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002976 // When a parameter of reference type binds directly (8.5.3)
2977 // to an argument expression, the implicit conversion sequence
2978 // is the identity conversion, unless the argument expression
2979 // has a type that is a derived class of the parameter type,
2980 // in which case the implicit conversion sequence is a
2981 // derived-to-base Conversion (13.3.3.1).
2982 ICS.setStandard();
2983 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002984 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2985 : ObjCConversion? ICK_Compatible_Conversion
2986 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002987 ICS.Standard.Third = ICK_Identity;
2988 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2989 ICS.Standard.setToType(0, T2);
2990 ICS.Standard.setToType(1, T1);
2991 ICS.Standard.setToType(2, T1);
2992 ICS.Standard.ReferenceBinding = true;
2993 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00002994 ICS.Standard.IsLvalueReference = !isRValRef;
2995 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
2996 ICS.Standard.BindsToRvalue = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002997 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002998
Sebastian Redld92badf2010-06-30 18:13:39 +00002999 // Nothing more to do: the inaccessibility/ambiguity check for
3000 // derived-to-base conversions is suppressed when we're
3001 // computing the implicit conversion sequence (C++
3002 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003003 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003004 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003005
Sebastian Redld92badf2010-06-30 18:13:39 +00003006 // -- has a class type (i.e., T2 is a class type), where T1 is
3007 // not reference-related to T2, and can be implicitly
3008 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3009 // is reference-compatible with "cv3 T3" 92) (this
3010 // conversion is selected by enumerating the applicable
3011 // conversion functions (13.3.1.6) and choosing the best
3012 // one through overload resolution (13.3)),
3013 if (!SuppressUserConversions && T2->isRecordType() &&
3014 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3015 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003016 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3017 Init, T2, /*AllowRvalues=*/false,
3018 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003019 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003020 }
3021 }
3022
Sebastian Redld92badf2010-06-30 18:13:39 +00003023 // -- Otherwise, the reference shall be an lvalue reference to a
3024 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003025 // shall be an rvalue reference.
Douglas Gregor870f3742010-04-18 09:22:00 +00003026 //
3027 // We actually handle one oddity of C++ [over.ics.ref] at this
3028 // point, which is that, due to p2 (which short-circuits reference
3029 // binding by only attempting a simple conversion for non-direct
3030 // bindings) and p3's strange wording, we allow a const volatile
3031 // reference to bind to an rvalue. Hence the check for the presence
3032 // of "const" rather than checking for "const" being the only
3033 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003034 // This is also the point where rvalue references and lvalue inits no longer
3035 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003036 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003037 return ICS;
3038
Douglas Gregorf143cd52011-01-24 16:14:37 +00003039 // -- If the initializer expression
3040 //
3041 // -- is an xvalue, class prvalue, array prvalue or function
3042 // lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3043 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3044 (InitCategory.isXValue() ||
3045 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3046 (InitCategory.isLValue() && T2->isFunctionType()))) {
3047 ICS.setStandard();
3048 ICS.Standard.First = ICK_Identity;
3049 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3050 : ObjCConversion? ICK_Compatible_Conversion
3051 : ICK_Identity;
3052 ICS.Standard.Third = ICK_Identity;
3053 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3054 ICS.Standard.setToType(0, T2);
3055 ICS.Standard.setToType(1, T1);
3056 ICS.Standard.setToType(2, T1);
3057 ICS.Standard.ReferenceBinding = true;
3058 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3059 // binding unless we're binding to a class prvalue.
3060 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3061 // allow the use of rvalue references in C++98/03 for the benefit of
3062 // standard library implementors; therefore, we need the xvalue check here.
3063 ICS.Standard.DirectBinding =
3064 S.getLangOptions().CPlusPlus0x ||
3065 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003066 ICS.Standard.IsLvalueReference = !isRValRef;
3067 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3068 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003069 ICS.Standard.CopyConstructor = 0;
3070 return ICS;
3071 }
3072
3073 // -- has a class type (i.e., T2 is a class type), where T1 is not
3074 // reference-related to T2, and can be implicitly converted to
3075 // an xvalue, class prvalue, or function lvalue of type
3076 // "cv3 T3", where "cv1 T1" is reference-compatible with
3077 // "cv3 T3",
3078 //
3079 // then the reference is bound to the value of the initializer
3080 // expression in the first case and to the result of the conversion
3081 // in the second case (or, in either case, to an appropriate base
3082 // class subobject).
3083 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3084 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
3085 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3086 Init, T2, /*AllowRvalues=*/true,
3087 AllowExplicit)) {
3088 // In the second case, if the reference is an rvalue reference
3089 // and the second standard conversion sequence of the
3090 // user-defined conversion sequence includes an lvalue-to-rvalue
3091 // conversion, the program is ill-formed.
3092 if (ICS.isUserDefined() && isRValRef &&
3093 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3094 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3095
Douglas Gregor95273c32011-01-21 16:36:05 +00003096 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003097 }
Douglas Gregor95273c32011-01-21 16:36:05 +00003098
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003099 // -- Otherwise, a temporary of type "cv1 T1" is created and
3100 // initialized from the initializer expression using the
3101 // rules for a non-reference copy initialization (8.5). The
3102 // reference is then bound to the temporary. If T1 is
3103 // reference-related to T2, cv1 must be the same
3104 // cv-qualification as, or greater cv-qualification than,
3105 // cv2; otherwise, the program is ill-formed.
3106 if (RefRelationship == Sema::Ref_Related) {
3107 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3108 // we would be reference-compatible or reference-compatible with
3109 // added qualification. But that wasn't the case, so the reference
3110 // initialization fails.
3111 return ICS;
3112 }
3113
3114 // If at least one of the types is a class type, the types are not
3115 // related, and we aren't allowed any user conversions, the
3116 // reference binding fails. This case is important for breaking
3117 // recursion, since TryImplicitConversion below will attempt to
3118 // create a temporary through the use of a copy constructor.
3119 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3120 (T1->isRecordType() || T2->isRecordType()))
3121 return ICS;
3122
Douglas Gregorcba72b12011-01-21 05:18:22 +00003123 // If T1 is reference-related to T2 and the reference is an rvalue
3124 // reference, the initializer expression shall not be an lvalue.
3125 if (RefRelationship >= Sema::Ref_Related &&
3126 isRValRef && Init->Classify(S.Context).isLValue())
3127 return ICS;
3128
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003129 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003130 // When a parameter of reference type is not bound directly to
3131 // an argument expression, the conversion sequence is the one
3132 // required to convert the argument expression to the
3133 // underlying type of the reference according to
3134 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3135 // to copy-initializing a temporary of the underlying type with
3136 // the argument expression. Any difference in top-level
3137 // cv-qualification is subsumed by the initialization itself
3138 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003139 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3140 /*AllowExplicit=*/false,
3141 /*InOverloadResolution=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003142
3143 // Of course, that's still a reference binding.
3144 if (ICS.isStandard()) {
3145 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003146 ICS.Standard.IsLvalueReference = !isRValRef;
3147 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3148 ICS.Standard.BindsToRvalue = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003149 } else if (ICS.isUserDefined()) {
3150 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003151 ICS.Standard.IsLvalueReference = !isRValRef;
3152 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3153 ICS.Standard.BindsToRvalue = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003154 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003155
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003156 return ICS;
3157}
3158
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003159/// TryCopyInitialization - Try to copy-initialize a value of type
3160/// ToType from the expression From. Return the implicit conversion
3161/// sequence required to pass this argument, which may be a bad
3162/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003163/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003164/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003165static ImplicitConversionSequence
3166TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00003167 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003168 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003169 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003170 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003171 /*FIXME:*/From->getLocStart(),
3172 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003173 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003174
John McCall5c32be02010-08-24 20:38:10 +00003175 return TryImplicitConversion(S, From, ToType,
3176 SuppressUserConversions,
3177 /*AllowExplicit=*/false,
3178 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003179}
3180
Douglas Gregor436424c2008-11-18 23:14:02 +00003181/// TryObjectArgumentInitialization - Try to initialize the object
3182/// parameter of the given member function (@c Method) from the
3183/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003184static ImplicitConversionSequence
3185TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003186 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003187 CXXMethodDecl *Method,
3188 CXXRecordDecl *ActingContext) {
3189 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003190 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3191 // const volatile object.
3192 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3193 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003194 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003195
3196 // Set up the conversion sequence as a "bad" conversion, to allow us
3197 // to exit early.
3198 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003199
3200 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003201 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003202 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003203 FromType = PT->getPointeeType();
3204
Douglas Gregor02824322011-01-26 19:30:28 +00003205 // When we had a pointer, it's implicitly dereferenced, so we
3206 // better have an lvalue.
3207 assert(FromClassification.isLValue());
3208 }
3209
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003210 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003211
Douglas Gregor02824322011-01-26 19:30:28 +00003212 // C++0x [over.match.funcs]p4:
3213 // For non-static member functions, the type of the implicit object
3214 // parameter is
3215 //
3216 // — "lvalue reference to cv X" for functions declared without a
3217 // ref-qualifier or with the & ref-qualifier
3218 // — "rvalue reference to cv X" for functions declared with the &&
3219 // ref-qualifier
3220 //
3221 // where X is the class of which the function is a member and cv is the
3222 // cv-qualification on the member function declaration.
3223 //
3224 // However, when finding an implicit conversion sequence for the argument, we
3225 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003226 // (C++ [over.match.funcs]p5). We perform a simplified version of
3227 // reference binding here, that allows class rvalues to bind to
3228 // non-constant references.
3229
Douglas Gregor02824322011-01-26 19:30:28 +00003230 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003231 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003232 if (ImplicitParamType.getCVRQualifiers()
3233 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003234 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003235 ICS.setBad(BadConversionSequence::bad_qualifiers,
3236 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003237 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003238 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003239
3240 // Check that we have either the same type or a derived type. It
3241 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003242 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003243 ImplicitConversionKind SecondKind;
3244 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3245 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003246 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003247 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003248 else {
John McCall65eb8792010-02-25 01:37:24 +00003249 ICS.setBad(BadConversionSequence::unrelated_class,
3250 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003251 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003252 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003253
Douglas Gregor02824322011-01-26 19:30:28 +00003254 // Check the ref-qualifier.
3255 switch (Method->getRefQualifier()) {
3256 case RQ_None:
3257 // Do nothing; we don't care about lvalueness or rvalueness.
3258 break;
3259
3260 case RQ_LValue:
3261 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3262 // non-const lvalue reference cannot bind to an rvalue
3263 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
3264 ImplicitParamType);
3265 return ICS;
3266 }
3267 break;
3268
3269 case RQ_RValue:
3270 if (!FromClassification.isRValue()) {
3271 // rvalue reference cannot bind to an lvalue
3272 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
3273 ImplicitParamType);
3274 return ICS;
3275 }
3276 break;
3277 }
3278
Douglas Gregor436424c2008-11-18 23:14:02 +00003279 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003280 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003281 ICS.Standard.setAsIdentityConversion();
3282 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003283 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003284 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003285 ICS.Standard.ReferenceBinding = true;
3286 ICS.Standard.DirectBinding = true;
Douglas Gregor02824322011-01-26 19:30:28 +00003287 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003288 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregor02824322011-01-26 19:30:28 +00003289
3290 // Note: we intentionally don't set this; see isBetterReferenceBindingKind().
Douglas Gregore696ebb2011-01-26 14:52:12 +00003291 ICS.Standard.BindsToRvalue = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003292 return ICS;
3293}
3294
3295/// PerformObjectArgumentInitialization - Perform initialization of
3296/// the implicit object parameter for the given Method with the given
3297/// expression.
3298bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003299Sema::PerformObjectArgumentInitialization(Expr *&From,
3300 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003301 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003302 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003303 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003304 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003305 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003306
Douglas Gregor02824322011-01-26 19:30:28 +00003307 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003308 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003309 FromRecordType = PT->getPointeeType();
3310 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003311 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003312 } else {
3313 FromRecordType = From->getType();
3314 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003315 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003316 }
3317
John McCall6e9f8f62009-12-03 04:06:58 +00003318 // Note that we always use the true parent context when performing
3319 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003320 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003321 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3322 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003323 if (ICS.isBad()) {
3324 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3325 Qualifiers FromQs = FromRecordType.getQualifiers();
3326 Qualifiers ToQs = DestType.getQualifiers();
3327 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3328 if (CVR) {
3329 Diag(From->getSourceRange().getBegin(),
3330 diag::err_member_function_call_bad_cvr)
3331 << Method->getDeclName() << FromRecordType << (CVR - 1)
3332 << From->getSourceRange();
3333 Diag(Method->getLocation(), diag::note_previous_decl)
3334 << Method->getDeclName();
3335 return true;
3336 }
3337 }
3338
Douglas Gregor436424c2008-11-18 23:14:02 +00003339 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003340 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003341 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003342 }
Mike Stump11289f42009-09-09 15:08:12 +00003343
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003344 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003345 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003346
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003347 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003348 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003349 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003350 return false;
3351}
3352
Douglas Gregor5fb53972009-01-14 15:45:31 +00003353/// TryContextuallyConvertToBool - Attempt to contextually convert the
3354/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003355static ImplicitConversionSequence
3356TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003357 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003358 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003359 // FIXME: Are these flags correct?
3360 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003361 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003362 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003363}
3364
3365/// PerformContextuallyConvertToBool - Perform a contextual conversion
3366/// of the expression From to bool (C++0x [conv]p3).
3367bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003368 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003369 if (!ICS.isBad())
3370 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003371
Fariborz Jahanian76197412009-11-18 18:26:29 +00003372 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003373 return Diag(From->getSourceRange().getBegin(),
3374 diag::err_typecheck_bool_condition)
3375 << From->getType() << From->getSourceRange();
3376 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003377}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003378
3379/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3380/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003381static ImplicitConversionSequence
3382TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3383 QualType Ty = S.Context.getObjCIdType();
3384 return TryImplicitConversion(S, From, Ty,
3385 // FIXME: Are these flags correct?
3386 /*SuppressUserConversions=*/false,
3387 /*AllowExplicit=*/true,
3388 /*InOverloadResolution=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003389}
John McCall5c32be02010-08-24 20:38:10 +00003390
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003391/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3392/// of the expression From to 'id'.
3393bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003394 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003395 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003396 if (!ICS.isBad())
3397 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3398 return true;
3399}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003400
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003401/// \brief Attempt to convert the given expression to an integral or
3402/// enumeration type.
3403///
3404/// This routine will attempt to convert an expression of class type to an
3405/// integral or enumeration type, if that class type only has a single
3406/// conversion to an integral or enumeration type.
3407///
Douglas Gregor4799d032010-06-30 00:20:43 +00003408/// \param Loc The source location of the construct that requires the
3409/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003410///
Douglas Gregor4799d032010-06-30 00:20:43 +00003411/// \param FromE The expression we're converting from.
3412///
3413/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3414/// have integral or enumeration type.
3415///
3416/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3417/// incomplete class type.
3418///
3419/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3420/// explicit conversion function (because no implicit conversion functions
3421/// were available). This is a recovery mode.
3422///
3423/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3424/// showing which conversion was picked.
3425///
3426/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3427/// conversion function that could convert to integral or enumeration type.
3428///
3429/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3430/// usable conversion function.
3431///
3432/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3433/// function, which may be an extension in this case.
3434///
3435/// \returns The expression, converted to an integral or enumeration type if
3436/// successful.
John McCalldadc5752010-08-24 06:29:42 +00003437ExprResult
John McCallb268a282010-08-23 23:25:46 +00003438Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003439 const PartialDiagnostic &NotIntDiag,
3440 const PartialDiagnostic &IncompleteDiag,
3441 const PartialDiagnostic &ExplicitConvDiag,
3442 const PartialDiagnostic &ExplicitConvNote,
3443 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003444 const PartialDiagnostic &AmbigNote,
3445 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003446 // We can't perform any more checking for type-dependent expressions.
3447 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003448 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003449
3450 // If the expression already has integral or enumeration type, we're golden.
3451 QualType T = From->getType();
3452 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003453 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003454
3455 // FIXME: Check for missing '()' if T is a function type?
3456
3457 // If we don't have a class type in C++, there's no way we can get an
3458 // expression of integral or enumeration type.
3459 const RecordType *RecordTy = T->getAs<RecordType>();
3460 if (!RecordTy || !getLangOptions().CPlusPlus) {
3461 Diag(Loc, NotIntDiag)
3462 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003463 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003464 }
3465
3466 // We must have a complete class type.
3467 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003468 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003469
3470 // Look for a conversion to an integral or enumeration type.
3471 UnresolvedSet<4> ViableConversions;
3472 UnresolvedSet<4> ExplicitConversions;
3473 const UnresolvedSetImpl *Conversions
3474 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3475
3476 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3477 E = Conversions->end();
3478 I != E;
3479 ++I) {
3480 if (CXXConversionDecl *Conversion
3481 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3482 if (Conversion->getConversionType().getNonReferenceType()
3483 ->isIntegralOrEnumerationType()) {
3484 if (Conversion->isExplicit())
3485 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3486 else
3487 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3488 }
3489 }
3490
3491 switch (ViableConversions.size()) {
3492 case 0:
3493 if (ExplicitConversions.size() == 1) {
3494 DeclAccessPair Found = ExplicitConversions[0];
3495 CXXConversionDecl *Conversion
3496 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3497
3498 // The user probably meant to invoke the given explicit
3499 // conversion; use it.
3500 QualType ConvTy
3501 = Conversion->getConversionType().getNonReferenceType();
3502 std::string TypeStr;
3503 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3504
3505 Diag(Loc, ExplicitConvDiag)
3506 << T << ConvTy
3507 << FixItHint::CreateInsertion(From->getLocStart(),
3508 "static_cast<" + TypeStr + ">(")
3509 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3510 ")");
3511 Diag(Conversion->getLocation(), ExplicitConvNote)
3512 << ConvTy->isEnumeralType() << ConvTy;
3513
3514 // If we aren't in a SFINAE context, build a call to the
3515 // explicit conversion function.
3516 if (isSFINAEContext())
3517 return ExprError();
3518
3519 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00003520 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3521 if (Result.isInvalid())
3522 return ExprError();
3523
3524 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003525 }
3526
3527 // We'll complain below about a non-integral condition type.
3528 break;
3529
3530 case 1: {
3531 // Apply this conversion.
3532 DeclAccessPair Found = ViableConversions[0];
3533 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003534
3535 CXXConversionDecl *Conversion
3536 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3537 QualType ConvTy
3538 = Conversion->getConversionType().getNonReferenceType();
3539 if (ConvDiag.getDiagID()) {
3540 if (isSFINAEContext())
3541 return ExprError();
3542
3543 Diag(Loc, ConvDiag)
3544 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3545 }
3546
Douglas Gregor668443e2011-01-20 00:18:04 +00003547 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003548 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00003549 if (Result.isInvalid())
3550 return ExprError();
3551
3552 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003553 break;
3554 }
3555
3556 default:
3557 Diag(Loc, AmbigDiag)
3558 << T << From->getSourceRange();
3559 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3560 CXXConversionDecl *Conv
3561 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3562 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3563 Diag(Conv->getLocation(), AmbigNote)
3564 << ConvTy->isEnumeralType() << ConvTy;
3565 }
John McCallb268a282010-08-23 23:25:46 +00003566 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003567 }
3568
Douglas Gregor5823da32010-06-29 23:25:20 +00003569 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003570 Diag(Loc, NotIntDiag)
3571 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003572
John McCallb268a282010-08-23 23:25:46 +00003573 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003574}
3575
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003576/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003577/// candidate functions, using the given function call arguments. If
3578/// @p SuppressUserConversions, then don't allow user-defined
3579/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003580///
3581/// \para PartialOverloading true if we are performing "partial" overloading
3582/// based on an incomplete set of function arguments. This feature is used by
3583/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003584void
3585Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003586 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003587 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003588 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003589 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003590 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003591 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003592 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003593 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003594 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregor02824322011-01-26 19:30:28 +00003595 "Use AddTemp∫lateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003596
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003597 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003598 if (!isa<CXXConstructorDecl>(Method)) {
3599 // If we get here, it's because we're calling a member function
3600 // that is named without a member access expression (e.g.,
3601 // "this->f") that was either written explicitly or created
3602 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003603 // function, e.g., X::f(). We use an empty type for the implied
3604 // object argument (C++ [over.call.func]p3), and the acting context
3605 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003606 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00003607 QualType(), Expr::Classification::makeSimpleLValue(),
3608 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003609 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003610 return;
3611 }
3612 // We treat a constructor like a non-member function, since its object
3613 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003614 }
3615
Douglas Gregorff7028a2009-11-13 23:59:09 +00003616 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003617 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003618
Douglas Gregor27381f32009-11-23 12:27:39 +00003619 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003620 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003621
Douglas Gregorffe14e32009-11-14 01:20:54 +00003622 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3623 // C++ [class.copy]p3:
3624 // A member function template is never instantiated to perform the copy
3625 // of a class object to an object of its class type.
3626 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3627 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003628 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003629 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3630 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003631 return;
3632 }
3633
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003634 // Add this candidate
3635 CandidateSet.push_back(OverloadCandidate());
3636 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003637 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003638 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003639 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003640 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003641 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003642 Candidate.ExplicitCallArguments = NumArgs;
3643
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003644 unsigned NumArgsInProto = Proto->getNumArgs();
3645
3646 // (C++ 13.3.2p2): A candidate function having fewer than m
3647 // parameters is viable only if it has an ellipsis in its parameter
3648 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003649 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3650 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003651 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003652 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003653 return;
3654 }
3655
3656 // (C++ 13.3.2p2): A candidate function having more than m parameters
3657 // is viable only if the (m+1)st parameter has a default argument
3658 // (8.3.6). For the purposes of overload resolution, the
3659 // parameter list is truncated on the right, so that there are
3660 // exactly m parameters.
3661 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003662 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003663 // Not enough arguments.
3664 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003665 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003666 return;
3667 }
3668
3669 // Determine the implicit conversion sequences for each of the
3670 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003671 Candidate.Conversions.resize(NumArgs);
3672 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3673 if (ArgIdx < NumArgsInProto) {
3674 // (C++ 13.3.2p3): for F to be a viable function, there shall
3675 // exist for each argument an implicit conversion sequence
3676 // (13.3.3.1) that converts that argument to the corresponding
3677 // parameter of F.
3678 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003679 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003680 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003681 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003682 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003683 if (Candidate.Conversions[ArgIdx].isBad()) {
3684 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003685 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003686 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003687 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003688 } else {
3689 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3690 // argument for which there is no corresponding parameter is
3691 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003692 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003693 }
3694 }
3695}
3696
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003697/// \brief Add all of the function declarations in the given function set to
3698/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003699void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003700 Expr **Args, unsigned NumArgs,
3701 OverloadCandidateSet& CandidateSet,
3702 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003703 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003704 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3705 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003706 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003707 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003708 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00003709 Args[0]->getType(), Args[0]->Classify(Context),
3710 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003711 CandidateSet, SuppressUserConversions);
3712 else
John McCalla0296f72010-03-19 07:35:19 +00003713 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003714 SuppressUserConversions);
3715 } else {
John McCalla0296f72010-03-19 07:35:19 +00003716 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003717 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3718 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003719 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003720 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003721 /*FIXME: explicit args */ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00003722 Args[0]->getType(),
3723 Args[0]->Classify(Context),
3724 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003725 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003726 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003727 else
John McCalla0296f72010-03-19 07:35:19 +00003728 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003729 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003730 Args, NumArgs, CandidateSet,
3731 SuppressUserConversions);
3732 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003733 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003734}
3735
John McCallf0f1cf02009-11-17 07:50:12 +00003736/// AddMethodCandidate - Adds a named decl (which is some kind of
3737/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003738void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003739 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00003740 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00003741 Expr **Args, unsigned NumArgs,
3742 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003743 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003744 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003745 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003746
3747 if (isa<UsingShadowDecl>(Decl))
3748 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3749
3750 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3751 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3752 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003753 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3754 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00003755 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003756 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003757 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003758 } else {
John McCalla0296f72010-03-19 07:35:19 +00003759 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00003760 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003761 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003762 }
3763}
3764
Douglas Gregor436424c2008-11-18 23:14:02 +00003765/// AddMethodCandidate - Adds the given C++ member function to the set
3766/// of candidate functions, using the given function call arguments
3767/// and the object argument (@c Object). For example, in a call
3768/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3769/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3770/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003771/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003772void
John McCalla0296f72010-03-19 07:35:19 +00003773Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003774 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00003775 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00003776 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003777 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003778 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003779 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003780 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003781 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003782 assert(!isa<CXXConstructorDecl>(Method) &&
3783 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003784
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003785 if (!CandidateSet.isNewCandidate(Method))
3786 return;
3787
Douglas Gregor27381f32009-11-23 12:27:39 +00003788 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003789 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003790
Douglas Gregor436424c2008-11-18 23:14:02 +00003791 // Add this candidate
3792 CandidateSet.push_back(OverloadCandidate());
3793 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003794 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003795 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003796 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003797 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003798 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00003799
3800 unsigned NumArgsInProto = Proto->getNumArgs();
3801
3802 // (C++ 13.3.2p2): A candidate function having fewer than m
3803 // parameters is viable only if it has an ellipsis in its parameter
3804 // list (8.3.5).
3805 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3806 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003807 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003808 return;
3809 }
3810
3811 // (C++ 13.3.2p2): A candidate function having more than m parameters
3812 // is viable only if the (m+1)st parameter has a default argument
3813 // (8.3.6). For the purposes of overload resolution, the
3814 // parameter list is truncated on the right, so that there are
3815 // exactly m parameters.
3816 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3817 if (NumArgs < MinRequiredArgs) {
3818 // Not enough arguments.
3819 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003820 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003821 return;
3822 }
3823
3824 Candidate.Viable = true;
3825 Candidate.Conversions.resize(NumArgs + 1);
3826
John McCall6e9f8f62009-12-03 04:06:58 +00003827 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003828 // The implicit object argument is ignored.
3829 Candidate.IgnoreObjectArgument = true;
3830 else {
3831 // Determine the implicit conversion sequence for the object
3832 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003833 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00003834 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
3835 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003836 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003837 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003838 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003839 return;
3840 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003841 }
3842
3843 // Determine the implicit conversion sequences for each of the
3844 // arguments.
3845 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3846 if (ArgIdx < NumArgsInProto) {
3847 // (C++ 13.3.2p3): for F to be a viable function, there shall
3848 // exist for each argument an implicit conversion sequence
3849 // (13.3.3.1) that converts that argument to the corresponding
3850 // parameter of F.
3851 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003852 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003853 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003854 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003855 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003856 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003857 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003858 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003859 break;
3860 }
3861 } else {
3862 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3863 // argument for which there is no corresponding parameter is
3864 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003865 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003866 }
3867 }
3868}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003869
Douglas Gregor97628d62009-08-21 00:16:32 +00003870/// \brief Add a C++ member function template as a candidate to the candidate
3871/// set, using template argument deduction to produce an appropriate member
3872/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003873void
Douglas Gregor97628d62009-08-21 00:16:32 +00003874Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003875 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003876 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003877 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003878 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00003879 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00003880 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003881 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003882 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003883 if (!CandidateSet.isNewCandidate(MethodTmpl))
3884 return;
3885
Douglas Gregor97628d62009-08-21 00:16:32 +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 Gregor97628d62009-08-21 00:16:32 +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 Gregor97628d62009-08-21 00:16:32 +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 Gregor97628d62009-08-21 00:16:32 +00003896 FunctionDecl *Specialization = 0;
3897 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003898 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003899 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003900 CandidateSet.push_back(OverloadCandidate());
3901 OverloadCandidate &Candidate = CandidateSet.back();
3902 Candidate.FoundDecl = FoundDecl;
3903 Candidate.Function = MethodTmpl->getTemplatedDecl();
3904 Candidate.Viable = false;
3905 Candidate.FailureKind = ovl_fail_bad_deduction;
3906 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);
3911 return;
3912 }
Mike Stump11289f42009-09-09 15:08:12 +00003913
Douglas Gregor97628d62009-08-21 00:16:32 +00003914 // Add the function template specialization produced by template argument
3915 // deduction as a candidate.
3916 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003917 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003918 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003919 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00003920 ActingContext, ObjectType, ObjectClassification,
3921 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003922}
3923
Douglas Gregor05155d82009-08-21 23:19:43 +00003924/// \brief Add a C++ function template specialization as a candidate
3925/// in the candidate set, using template argument deduction to produce
3926/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003927void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003928Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003929 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003930 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003931 Expr **Args, unsigned NumArgs,
3932 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003933 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003934 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3935 return;
3936
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003937 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003938 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003939 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003940 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003941 // candidate functions in the usual way.113) A given name can refer to one
3942 // or more function templates and also to a set of overloaded non-template
3943 // functions. In such a case, the candidate functions generated from each
3944 // function template are combined with the set of non-template candidate
3945 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003946 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003947 FunctionDecl *Specialization = 0;
3948 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003949 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003950 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003951 CandidateSet.push_back(OverloadCandidate());
3952 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003953 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003954 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3955 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003956 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003957 Candidate.IsSurrogate = false;
3958 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003959 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003960 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3961 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003962 return;
3963 }
Mike Stump11289f42009-09-09 15:08:12 +00003964
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003965 // Add the function template specialization produced by template argument
3966 // deduction as a candidate.
3967 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003968 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003969 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003970}
Mike Stump11289f42009-09-09 15:08:12 +00003971
Douglas Gregora1f013e2008-11-07 22:36:19 +00003972/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003973/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003974/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003975/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003976/// (which may or may not be the same type as the type that the
3977/// conversion function produces).
3978void
3979Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003980 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003981 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003982 Expr *From, QualType ToType,
3983 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003984 assert(!Conversion->getDescribedFunctionTemplate() &&
3985 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003986 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003987 if (!CandidateSet.isNewCandidate(Conversion))
3988 return;
3989
Douglas Gregor27381f32009-11-23 12:27:39 +00003990 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003991 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003992
Douglas Gregora1f013e2008-11-07 22:36:19 +00003993 // Add this candidate
3994 CandidateSet.push_back(OverloadCandidate());
3995 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003996 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003997 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003998 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003999 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004000 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004001 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004002 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004003 Candidate.Viable = true;
4004 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004005 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004006
Douglas Gregor6affc782010-08-19 15:37:02 +00004007 // C++ [over.match.funcs]p4:
4008 // For conversion functions, the function is considered to be a member of
4009 // the class of the implicit implied object argument for the purpose of
4010 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004011 //
4012 // Determine the implicit conversion sequence for the implicit
4013 // object parameter.
4014 QualType ImplicitParamType = From->getType();
4015 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4016 ImplicitParamType = FromPtrType->getPointeeType();
4017 CXXRecordDecl *ConversionContext
4018 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
4019
4020 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004021 = TryObjectArgumentInitialization(*this, From->getType(),
4022 From->Classify(Context),
4023 Conversion, ConversionContext);
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004024
John McCall0d1da222010-01-12 00:44:57 +00004025 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004026 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004027 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004028 return;
4029 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004030
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004031 // We won't go through a user-define type conversion function to convert a
4032 // derived to base as such conversions are given Conversion Rank. They only
4033 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4034 QualType FromCanon
4035 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4036 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4037 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4038 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004039 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004040 return;
4041 }
4042
Douglas Gregora1f013e2008-11-07 22:36:19 +00004043 // To determine what the conversion from the result of calling the
4044 // conversion function to the type we're eventually trying to
4045 // convert to (ToType), we need to synthesize a call to the
4046 // conversion function and attempt copy initialization from it. This
4047 // makes sure that we get the right semantics with respect to
4048 // lvalues/rvalues and the type. Fortunately, we can allocate this
4049 // call on the stack and we don't need its arguments to be
4050 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004051 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004052 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004053 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4054 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004055 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004056 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004057
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004058 QualType CallResultType
4059 = Conversion->getConversionType().getNonLValueExprType(Context);
4060 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4061 Candidate.Viable = false;
4062 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4063 return;
4064 }
4065
John McCall7decc9e2010-11-18 06:31:45 +00004066 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4067
Mike Stump11289f42009-09-09 15:08:12 +00004068 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004069 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4070 // allocator).
John McCall7decc9e2010-11-18 06:31:45 +00004071 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004072 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004073 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004074 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004075 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00004076 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004077
John McCall0d1da222010-01-12 00:44:57 +00004078 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004079 case ImplicitConversionSequence::StandardConversion:
4080 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004081
4082 // C++ [over.ics.user]p3:
4083 // If the user-defined conversion is specified by a specialization of a
4084 // conversion function template, the second standard conversion sequence
4085 // shall have exact match rank.
4086 if (Conversion->getPrimaryTemplate() &&
4087 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4088 Candidate.Viable = false;
4089 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4090 }
4091
Douglas Gregorcba72b12011-01-21 05:18:22 +00004092 // C++0x [dcl.init.ref]p5:
4093 // In the second case, if the reference is an rvalue reference and
4094 // the second standard conversion sequence of the user-defined
4095 // conversion sequence includes an lvalue-to-rvalue conversion, the
4096 // program is ill-formed.
4097 if (ToType->isRValueReferenceType() &&
4098 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4099 Candidate.Viable = false;
4100 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4101 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004102 break;
4103
4104 case ImplicitConversionSequence::BadConversion:
4105 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004106 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004107 break;
4108
4109 default:
Mike Stump11289f42009-09-09 15:08:12 +00004110 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004111 "Can only end up with a standard conversion sequence or failure");
4112 }
4113}
4114
Douglas Gregor05155d82009-08-21 23:19:43 +00004115/// \brief Adds a conversion function template specialization
4116/// candidate to the overload set, using template argument deduction
4117/// to deduce the template arguments of the conversion function
4118/// template from the type that we are converting to (C++
4119/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004120void
Douglas Gregor05155d82009-08-21 23:19:43 +00004121Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004122 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004123 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004124 Expr *From, QualType ToType,
4125 OverloadCandidateSet &CandidateSet) {
4126 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4127 "Only conversion function templates permitted here");
4128
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004129 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4130 return;
4131
John McCallbc077cf2010-02-08 23:07:23 +00004132 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004133 CXXConversionDecl *Specialization = 0;
4134 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004135 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004136 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004137 CandidateSet.push_back(OverloadCandidate());
4138 OverloadCandidate &Candidate = CandidateSet.back();
4139 Candidate.FoundDecl = FoundDecl;
4140 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4141 Candidate.Viable = false;
4142 Candidate.FailureKind = ovl_fail_bad_deduction;
4143 Candidate.IsSurrogate = false;
4144 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004145 Candidate.ExplicitCallArguments = 1;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004146 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4147 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004148 return;
4149 }
Mike Stump11289f42009-09-09 15:08:12 +00004150
Douglas Gregor05155d82009-08-21 23:19:43 +00004151 // Add the conversion function template specialization produced by
4152 // template argument deduction as a candidate.
4153 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004154 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004155 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004156}
4157
Douglas Gregorab7897a2008-11-19 22:57:39 +00004158/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4159/// converts the given @c Object to a function pointer via the
4160/// conversion function @c Conversion, and then attempts to call it
4161/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4162/// the type of function that we'll eventually be calling.
4163void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004164 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004165 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004166 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004167 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004168 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004169 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004170 if (!CandidateSet.isNewCandidate(Conversion))
4171 return;
4172
Douglas Gregor27381f32009-11-23 12:27:39 +00004173 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004174 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004175
Douglas Gregorab7897a2008-11-19 22:57:39 +00004176 CandidateSet.push_back(OverloadCandidate());
4177 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004178 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004179 Candidate.Function = 0;
4180 Candidate.Surrogate = Conversion;
4181 Candidate.Viable = true;
4182 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004183 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004184 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004185 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004186
4187 // Determine the implicit conversion sequence for the implicit
4188 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004189 ImplicitConversionSequence ObjectInit
Douglas Gregor02824322011-01-26 19:30:28 +00004190 = TryObjectArgumentInitialization(*this, Object->getType(),
4191 Object->Classify(Context),
4192 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004193 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004194 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004195 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004196 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004197 return;
4198 }
4199
4200 // The first conversion is actually a user-defined conversion whose
4201 // first conversion is ObjectInit's standard conversion (which is
4202 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004203 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004204 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004205 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004206 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00004207 Candidate.Conversions[0].UserDefined.FoundConversionFunction
4208 = FoundDecl.getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004209 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004210 = Candidate.Conversions[0].UserDefined.Before;
4211 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4212
Mike Stump11289f42009-09-09 15:08:12 +00004213 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004214 unsigned NumArgsInProto = Proto->getNumArgs();
4215
4216 // (C++ 13.3.2p2): A candidate function having fewer than m
4217 // parameters is viable only if it has an ellipsis in its parameter
4218 // list (8.3.5).
4219 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4220 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004221 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004222 return;
4223 }
4224
4225 // Function types don't have any default arguments, so just check if
4226 // we have enough arguments.
4227 if (NumArgs < NumArgsInProto) {
4228 // Not enough arguments.
4229 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004230 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004231 return;
4232 }
4233
4234 // Determine the implicit conversion sequences for each of the
4235 // arguments.
4236 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4237 if (ArgIdx < NumArgsInProto) {
4238 // (C++ 13.3.2p3): for F to be a viable function, there shall
4239 // exist for each argument an implicit conversion sequence
4240 // (13.3.3.1) that converts that argument to the corresponding
4241 // parameter of F.
4242 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004243 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004244 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004245 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004246 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004247 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004248 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004249 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004250 break;
4251 }
4252 } else {
4253 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4254 // argument for which there is no corresponding parameter is
4255 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004256 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004257 }
4258 }
4259}
4260
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004261/// \brief Add overload candidates for overloaded operators that are
4262/// member functions.
4263///
4264/// Add the overloaded operator candidates that are member functions
4265/// for the operator Op that was used in an operator expression such
4266/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4267/// CandidateSet will store the added overload candidates. (C++
4268/// [over.match.oper]).
4269void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4270 SourceLocation OpLoc,
4271 Expr **Args, unsigned NumArgs,
4272 OverloadCandidateSet& CandidateSet,
4273 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004274 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4275
4276 // C++ [over.match.oper]p3:
4277 // For a unary operator @ with an operand of a type whose
4278 // cv-unqualified version is T1, and for a binary operator @ with
4279 // a left operand of a type whose cv-unqualified version is T1 and
4280 // a right operand of a type whose cv-unqualified version is T2,
4281 // three sets of candidate functions, designated member
4282 // candidates, non-member candidates and built-in candidates, are
4283 // constructed as follows:
4284 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004285
4286 // -- If T1 is a class type, the set of member candidates is the
4287 // result of the qualified lookup of T1::operator@
4288 // (13.3.1.1.1); otherwise, the set of member candidates is
4289 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004290 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004291 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004292 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004293 return;
Mike Stump11289f42009-09-09 15:08:12 +00004294
John McCall27b18f82009-11-17 02:14:36 +00004295 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4296 LookupQualifiedName(Operators, T1Rec->getDecl());
4297 Operators.suppressDiagnostics();
4298
Mike Stump11289f42009-09-09 15:08:12 +00004299 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004300 OperEnd = Operators.end();
4301 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004302 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004303 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004304 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
4305 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004306 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004307 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004308}
4309
Douglas Gregora11693b2008-11-12 17:17:38 +00004310/// AddBuiltinCandidate - Add a candidate for a built-in
4311/// operator. ResultTy and ParamTys are the result and parameter types
4312/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004313/// arguments being passed to the candidate. IsAssignmentOperator
4314/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004315/// operator. NumContextualBoolArguments is the number of arguments
4316/// (at the beginning of the argument list) that will be contextually
4317/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004318void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004319 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004320 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004321 bool IsAssignmentOperator,
4322 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004323 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004324 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004325
Douglas Gregora11693b2008-11-12 17:17:38 +00004326 // Add this candidate
4327 CandidateSet.push_back(OverloadCandidate());
4328 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004329 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004330 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004331 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004332 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004333 Candidate.BuiltinTypes.ResultTy = ResultTy;
4334 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4335 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4336
4337 // Determine the implicit conversion sequences for each of the
4338 // arguments.
4339 Candidate.Viable = true;
4340 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004341 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004342 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004343 // C++ [over.match.oper]p4:
4344 // For the built-in assignment operators, conversions of the
4345 // left operand are restricted as follows:
4346 // -- no temporaries are introduced to hold the left operand, and
4347 // -- no user-defined conversions are applied to the left
4348 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004349 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004350 //
4351 // We block these conversions by turning off user-defined
4352 // conversions, since that is the only way that initialization of
4353 // a reference to a non-class type can occur from something that
4354 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004355 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004356 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004357 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004358 Candidate.Conversions[ArgIdx]
4359 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004360 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004361 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004362 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004363 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004364 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004365 }
John McCall0d1da222010-01-12 00:44:57 +00004366 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004367 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004368 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004369 break;
4370 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004371 }
4372}
4373
4374/// BuiltinCandidateTypeSet - A set of types that will be used for the
4375/// candidate operator functions for built-in operators (C++
4376/// [over.built]). The types are separated into pointer types and
4377/// enumeration types.
4378class BuiltinCandidateTypeSet {
4379 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004380 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004381
4382 /// PointerTypes - The set of pointer types that will be used in the
4383 /// built-in candidates.
4384 TypeSet PointerTypes;
4385
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004386 /// MemberPointerTypes - The set of member pointer types that will be
4387 /// used in the built-in candidates.
4388 TypeSet MemberPointerTypes;
4389
Douglas Gregora11693b2008-11-12 17:17:38 +00004390 /// EnumerationTypes - The set of enumeration types that will be
4391 /// used in the built-in candidates.
4392 TypeSet EnumerationTypes;
4393
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004394 /// \brief The set of vector types that will be used in the built-in
4395 /// candidates.
4396 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004397
4398 /// \brief A flag indicating non-record types are viable candidates
4399 bool HasNonRecordTypes;
4400
4401 /// \brief A flag indicating whether either arithmetic or enumeration types
4402 /// were present in the candidate set.
4403 bool HasArithmeticOrEnumeralTypes;
4404
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004405 /// Sema - The semantic analysis instance where we are building the
4406 /// candidate type set.
4407 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004408
Douglas Gregora11693b2008-11-12 17:17:38 +00004409 /// Context - The AST context in which we will build the type sets.
4410 ASTContext &Context;
4411
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004412 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4413 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004414 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004415
4416public:
4417 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004418 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004419
Mike Stump11289f42009-09-09 15:08:12 +00004420 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004421 : HasNonRecordTypes(false),
4422 HasArithmeticOrEnumeralTypes(false),
4423 SemaRef(SemaRef),
4424 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004425
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004426 void AddTypesConvertedFrom(QualType Ty,
4427 SourceLocation Loc,
4428 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004429 bool AllowExplicitConversions,
4430 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004431
4432 /// pointer_begin - First pointer type found;
4433 iterator pointer_begin() { return PointerTypes.begin(); }
4434
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004435 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004436 iterator pointer_end() { return PointerTypes.end(); }
4437
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004438 /// member_pointer_begin - First member pointer type found;
4439 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4440
4441 /// member_pointer_end - Past the last member pointer type found;
4442 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4443
Douglas Gregora11693b2008-11-12 17:17:38 +00004444 /// enumeration_begin - First enumeration type found;
4445 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4446
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004447 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004448 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004449
4450 iterator vector_begin() { return VectorTypes.begin(); }
4451 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00004452
4453 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4454 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregora11693b2008-11-12 17:17:38 +00004455};
4456
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004457/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004458/// the set of pointer types along with any more-qualified variants of
4459/// that type. For example, if @p Ty is "int const *", this routine
4460/// will add "int const *", "int const volatile *", "int const
4461/// restrict *", and "int const volatile restrict *" to the set of
4462/// pointer types. Returns true if the add of @p Ty itself succeeded,
4463/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004464///
4465/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004466bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004467BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4468 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004469
Douglas Gregora11693b2008-11-12 17:17:38 +00004470 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004471 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004472 return false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004473
4474 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004475 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004476 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004477 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004478 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004479 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004480 buildObjCPtr = true;
4481 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004482 else
4483 assert(false && "type was not a pointer type!");
4484 }
4485 else
4486 PointeeTy = PointerTy->getPointeeType();
4487
Sebastian Redl4990a632009-11-18 20:39:26 +00004488 // Don't add qualified variants of arrays. For one, they're not allowed
4489 // (the qualifier would sink to the element type), and for another, the
4490 // only overload situation where it matters is subscript or pointer +- int,
4491 // and those shouldn't have qualifier variants anyway.
4492 if (PointeeTy->isArrayType())
4493 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004494 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004495 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004496 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004497 bool hasVolatile = VisibleQuals.hasVolatile();
4498 bool hasRestrict = VisibleQuals.hasRestrict();
4499
John McCall8ccfcb52009-09-24 19:53:00 +00004500 // Iterate through all strict supersets of BaseCVR.
4501 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4502 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004503 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4504 // in the types.
4505 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4506 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004507 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004508 if (!buildObjCPtr)
4509 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4510 else
4511 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004512 }
4513
4514 return true;
4515}
4516
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004517/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4518/// to the set of pointer types along with any more-qualified variants of
4519/// that type. For example, if @p Ty is "int const *", this routine
4520/// will add "int const *", "int const volatile *", "int const
4521/// restrict *", and "int const volatile restrict *" to the set of
4522/// pointer types. Returns true if the add of @p Ty itself succeeded,
4523/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004524///
4525/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004526bool
4527BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4528 QualType Ty) {
4529 // Insert this type.
4530 if (!MemberPointerTypes.insert(Ty))
4531 return false;
4532
John McCall8ccfcb52009-09-24 19:53:00 +00004533 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4534 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004535
John McCall8ccfcb52009-09-24 19:53:00 +00004536 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004537 // Don't add qualified variants of arrays. For one, they're not allowed
4538 // (the qualifier would sink to the element type), and for another, the
4539 // only overload situation where it matters is subscript or pointer +- int,
4540 // and those shouldn't have qualifier variants anyway.
4541 if (PointeeTy->isArrayType())
4542 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004543 const Type *ClassTy = PointerTy->getClass();
4544
4545 // Iterate through all strict supersets of the pointee type's CVR
4546 // qualifiers.
4547 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4548 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4549 if ((CVR | BaseCVR) != CVR) continue;
4550
4551 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00004552 MemberPointerTypes.insert(
4553 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004554 }
4555
4556 return true;
4557}
4558
Douglas Gregora11693b2008-11-12 17:17:38 +00004559/// AddTypesConvertedFrom - Add each of the types to which the type @p
4560/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004561/// primarily interested in pointer types and enumeration types. We also
4562/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004563/// AllowUserConversions is true if we should look at the conversion
4564/// functions of a class type, and AllowExplicitConversions if we
4565/// should also include the explicit conversion functions of a class
4566/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004567void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004568BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004569 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004570 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004571 bool AllowExplicitConversions,
4572 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004573 // Only deal with canonical types.
4574 Ty = Context.getCanonicalType(Ty);
4575
4576 // Look through reference types; they aren't part of the type of an
4577 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004578 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004579 Ty = RefTy->getPointeeType();
4580
John McCall33ddac02011-01-19 10:06:00 +00004581 // If we're dealing with an array type, decay to the pointer.
4582 if (Ty->isArrayType())
4583 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4584
4585 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004586 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004587
Chandler Carruth00a38332010-12-13 01:44:01 +00004588 // Flag if we ever add a non-record type.
4589 const RecordType *TyRec = Ty->getAs<RecordType>();
4590 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4591
Chandler Carruth00a38332010-12-13 01:44:01 +00004592 // Flag if we encounter an arithmetic type.
4593 HasArithmeticOrEnumeralTypes =
4594 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4595
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004596 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4597 PointerTypes.insert(Ty);
4598 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004599 // Insert our type, and its more-qualified variants, into the set
4600 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004601 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004602 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004603 } else if (Ty->isMemberPointerType()) {
4604 // Member pointers are far easier, since the pointee can't be converted.
4605 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4606 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004607 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004608 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00004609 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004610 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004611 // We treat vector types as arithmetic types in many contexts as an
4612 // extension.
4613 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004614 VectorTypes.insert(Ty);
Chandler Carruth00a38332010-12-13 01:44:01 +00004615 } else if (AllowUserConversions && TyRec) {
4616 // No conversion functions in incomplete types.
4617 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4618 return;
Mike Stump11289f42009-09-09 15:08:12 +00004619
Chandler Carruth00a38332010-12-13 01:44:01 +00004620 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4621 const UnresolvedSetImpl *Conversions
4622 = ClassDecl->getVisibleConversionFunctions();
4623 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4624 E = Conversions->end(); I != E; ++I) {
4625 NamedDecl *D = I.getDecl();
4626 if (isa<UsingShadowDecl>(D))
4627 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004628
Chandler Carruth00a38332010-12-13 01:44:01 +00004629 // Skip conversion function templates; they don't tell us anything
4630 // about which builtin types we can convert to.
4631 if (isa<FunctionTemplateDecl>(D))
4632 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00004633
Chandler Carruth00a38332010-12-13 01:44:01 +00004634 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4635 if (AllowExplicitConversions || !Conv->isExplicit()) {
4636 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4637 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004638 }
4639 }
4640 }
4641}
4642
Douglas Gregor84605ae2009-08-24 13:43:27 +00004643/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4644/// the volatile- and non-volatile-qualified assignment operators for the
4645/// given type to the candidate set.
4646static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4647 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004648 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004649 unsigned NumArgs,
4650 OverloadCandidateSet &CandidateSet) {
4651 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004652
Douglas Gregor84605ae2009-08-24 13:43:27 +00004653 // T& operator=(T&, T)
4654 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4655 ParamTypes[1] = T;
4656 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4657 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004658
Douglas Gregor84605ae2009-08-24 13:43:27 +00004659 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4660 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004661 ParamTypes[0]
4662 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004663 ParamTypes[1] = T;
4664 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004665 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004666 }
4667}
Mike Stump11289f42009-09-09 15:08:12 +00004668
Sebastian Redl1054fae2009-10-25 17:03:50 +00004669/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4670/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004671static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4672 Qualifiers VRQuals;
4673 const RecordType *TyRec;
4674 if (const MemberPointerType *RHSMPType =
4675 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004676 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004677 else
4678 TyRec = ArgExpr->getType()->getAs<RecordType>();
4679 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004680 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004681 VRQuals.addVolatile();
4682 VRQuals.addRestrict();
4683 return VRQuals;
4684 }
4685
4686 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004687 if (!ClassDecl->hasDefinition())
4688 return VRQuals;
4689
John McCallad371252010-01-20 00:46:10 +00004690 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004691 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004692
John McCallad371252010-01-20 00:46:10 +00004693 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004694 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004695 NamedDecl *D = I.getDecl();
4696 if (isa<UsingShadowDecl>(D))
4697 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4698 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004699 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4700 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4701 CanTy = ResTypeRef->getPointeeType();
4702 // Need to go down the pointer/mempointer chain and add qualifiers
4703 // as see them.
4704 bool done = false;
4705 while (!done) {
4706 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4707 CanTy = ResTypePtr->getPointeeType();
4708 else if (const MemberPointerType *ResTypeMPtr =
4709 CanTy->getAs<MemberPointerType>())
4710 CanTy = ResTypeMPtr->getPointeeType();
4711 else
4712 done = true;
4713 if (CanTy.isVolatileQualified())
4714 VRQuals.addVolatile();
4715 if (CanTy.isRestrictQualified())
4716 VRQuals.addRestrict();
4717 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4718 return VRQuals;
4719 }
4720 }
4721 }
4722 return VRQuals;
4723}
John McCall52872982010-11-13 05:51:15 +00004724
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004725namespace {
John McCall52872982010-11-13 05:51:15 +00004726
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004727/// \brief Helper class to manage the addition of builtin operator overload
4728/// candidates. It provides shared state and utility methods used throughout
4729/// the process, as well as a helper method to add each group of builtin
4730/// operator overloads from the standard to a candidate set.
4731class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004732 // Common instance state available to all overload candidate addition methods.
4733 Sema &S;
4734 Expr **Args;
4735 unsigned NumArgs;
4736 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00004737 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruthc6586e52010-12-12 10:35:00 +00004738 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4739 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004740
Chandler Carruthc6586e52010-12-12 10:35:00 +00004741 // Define some constants used to index and iterate over the arithemetic types
4742 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00004743 // The "promoted arithmetic types" are the arithmetic
4744 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00004745 static const unsigned FirstIntegralType = 3;
4746 static const unsigned LastIntegralType = 18;
4747 static const unsigned FirstPromotedIntegralType = 3,
4748 LastPromotedIntegralType = 9;
4749 static const unsigned FirstPromotedArithmeticType = 0,
4750 LastPromotedArithmeticType = 9;
4751 static const unsigned NumArithmeticTypes = 18;
4752
Chandler Carruthc6586e52010-12-12 10:35:00 +00004753 /// \brief Get the canonical type for a given arithmetic type index.
4754 CanQualType getArithmeticType(unsigned index) {
4755 assert(index < NumArithmeticTypes);
4756 static CanQualType ASTContext::* const
4757 ArithmeticTypes[NumArithmeticTypes] = {
4758 // Start of promoted types.
4759 &ASTContext::FloatTy,
4760 &ASTContext::DoubleTy,
4761 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00004762
Chandler Carruthc6586e52010-12-12 10:35:00 +00004763 // Start of integral types.
4764 &ASTContext::IntTy,
4765 &ASTContext::LongTy,
4766 &ASTContext::LongLongTy,
4767 &ASTContext::UnsignedIntTy,
4768 &ASTContext::UnsignedLongTy,
4769 &ASTContext::UnsignedLongLongTy,
4770 // End of promoted types.
4771
4772 &ASTContext::BoolTy,
4773 &ASTContext::CharTy,
4774 &ASTContext::WCharTy,
4775 &ASTContext::Char16Ty,
4776 &ASTContext::Char32Ty,
4777 &ASTContext::SignedCharTy,
4778 &ASTContext::ShortTy,
4779 &ASTContext::UnsignedCharTy,
4780 &ASTContext::UnsignedShortTy,
4781 // End of integral types.
4782 // FIXME: What about complex?
4783 };
4784 return S.Context.*ArithmeticTypes[index];
4785 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004786
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004787 /// \brief Gets the canonical type resulting from the usual arithemetic
4788 /// converions for the given arithmetic types.
4789 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
4790 // Accelerator table for performing the usual arithmetic conversions.
4791 // The rules are basically:
4792 // - if either is floating-point, use the wider floating-point
4793 // - if same signedness, use the higher rank
4794 // - if same size, use unsigned of the higher rank
4795 // - use the larger type
4796 // These rules, together with the axiom that higher ranks are
4797 // never smaller, are sufficient to precompute all of these results
4798 // *except* when dealing with signed types of higher rank.
4799 // (we could precompute SLL x UI for all known platforms, but it's
4800 // better not to make any assumptions).
4801 enum PromotedType {
4802 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
4803 };
4804 static PromotedType ConversionsTable[LastPromotedArithmeticType]
4805 [LastPromotedArithmeticType] = {
4806 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4807 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4808 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4809 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4810 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4811 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4812 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4813 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4814 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
4815 };
4816
4817 assert(L < LastPromotedArithmeticType);
4818 assert(R < LastPromotedArithmeticType);
4819 int Idx = ConversionsTable[L][R];
4820
4821 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004822 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004823
4824 // Slow path: we need to compare widths.
4825 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004826 CanQualType LT = getArithmeticType(L),
4827 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004828 unsigned LW = S.Context.getIntWidth(LT),
4829 RW = S.Context.getIntWidth(RT);
4830
4831 // If they're different widths, use the signed type.
4832 if (LW > RW) return LT;
4833 else if (LW < RW) return RT;
4834
4835 // Otherwise, use the unsigned type of the signed type's rank.
4836 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
4837 assert(L == SLL || R == SLL);
4838 return S.Context.UnsignedLongLongTy;
4839 }
4840
Chandler Carruth5659c0c2010-12-12 09:22:45 +00004841 /// \brief Helper method to factor out the common pattern of adding overloads
4842 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004843 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
4844 bool HasVolatile) {
4845 QualType ParamTypes[2] = {
4846 S.Context.getLValueReferenceType(CandidateTy),
4847 S.Context.IntTy
4848 };
4849
4850 // Non-volatile version.
4851 if (NumArgs == 1)
4852 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4853 else
4854 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4855
4856 // Use a heuristic to reduce number of builtin candidates in the set:
4857 // add volatile version only if there are conversions to a volatile type.
4858 if (HasVolatile) {
4859 ParamTypes[0] =
4860 S.Context.getLValueReferenceType(
4861 S.Context.getVolatileType(CandidateTy));
4862 if (NumArgs == 1)
4863 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4864 else
4865 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4866 }
4867 }
4868
4869public:
4870 BuiltinOperatorOverloadBuilder(
4871 Sema &S, Expr **Args, unsigned NumArgs,
4872 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00004873 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004874 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
4875 OverloadCandidateSet &CandidateSet)
4876 : S(S), Args(Args), NumArgs(NumArgs),
4877 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00004878 HasArithmeticOrEnumeralCandidateType(
4879 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004880 CandidateTypes(CandidateTypes),
4881 CandidateSet(CandidateSet) {
4882 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004883 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004884 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004885 assert(getArithmeticType(LastPromotedIntegralType - 1)
4886 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004887 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004888 assert(getArithmeticType(FirstPromotedArithmeticType)
4889 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004890 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004891 assert(getArithmeticType(LastPromotedArithmeticType - 1)
4892 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004893 "Invalid last promoted arithmetic type");
4894 }
4895
4896 // C++ [over.built]p3:
4897 //
4898 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4899 // is either volatile or empty, there exist candidate operator
4900 // functions of the form
4901 //
4902 // VQ T& operator++(VQ T&);
4903 // T operator++(VQ T&, int);
4904 //
4905 // C++ [over.built]p4:
4906 //
4907 // For every pair (T, VQ), where T is an arithmetic type other
4908 // than bool, and VQ is either volatile or empty, there exist
4909 // candidate operator functions of the form
4910 //
4911 // VQ T& operator--(VQ T&);
4912 // T operator--(VQ T&, int);
4913 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004914 if (!HasArithmeticOrEnumeralCandidateType)
4915 return;
4916
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004917 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
4918 Arith < NumArithmeticTypes; ++Arith) {
4919 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00004920 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004921 VisibleTypeConversionsQuals.hasVolatile());
4922 }
4923 }
4924
4925 // C++ [over.built]p5:
4926 //
4927 // For every pair (T, VQ), where T is a cv-qualified or
4928 // cv-unqualified object type, and VQ is either volatile or
4929 // empty, there exist candidate operator functions of the form
4930 //
4931 // T*VQ& operator++(T*VQ&);
4932 // T*VQ& operator--(T*VQ&);
4933 // T* operator++(T*VQ&, int);
4934 // T* operator--(T*VQ&, int);
4935 void addPlusPlusMinusMinusPointerOverloads() {
4936 for (BuiltinCandidateTypeSet::iterator
4937 Ptr = CandidateTypes[0].pointer_begin(),
4938 PtrEnd = CandidateTypes[0].pointer_end();
4939 Ptr != PtrEnd; ++Ptr) {
4940 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00004941 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004942 continue;
4943
4944 addPlusPlusMinusMinusStyleOverloads(*Ptr,
4945 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4946 VisibleTypeConversionsQuals.hasVolatile()));
4947 }
4948 }
4949
4950 // C++ [over.built]p6:
4951 // For every cv-qualified or cv-unqualified object type T, there
4952 // exist candidate operator functions of the form
4953 //
4954 // T& operator*(T*);
4955 //
4956 // C++ [over.built]p7:
Douglas Gregor02824322011-01-26 19:30:28 +00004957 // For every function type T that does not have cv-qualifiers or a
4958 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004959 // T& operator*(T*);
4960 void addUnaryStarPointerOverloads() {
4961 for (BuiltinCandidateTypeSet::iterator
4962 Ptr = CandidateTypes[0].pointer_begin(),
4963 PtrEnd = CandidateTypes[0].pointer_end();
4964 Ptr != PtrEnd; ++Ptr) {
4965 QualType ParamTy = *Ptr;
4966 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00004967 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
4968 continue;
4969
Douglas Gregor02824322011-01-26 19:30:28 +00004970 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
4971 if (Proto->getTypeQuals() || Proto->getRefQualifier())
4972 continue;
4973
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004974 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
4975 &ParamTy, Args, 1, CandidateSet);
4976 }
4977 }
4978
4979 // C++ [over.built]p9:
4980 // For every promoted arithmetic type T, there exist candidate
4981 // operator functions of the form
4982 //
4983 // T operator+(T);
4984 // T operator-(T);
4985 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00004986 if (!HasArithmeticOrEnumeralCandidateType)
4987 return;
4988
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004989 for (unsigned Arith = FirstPromotedArithmeticType;
4990 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004991 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004992 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4993 }
4994
4995 // Extension: We also add these operators for vector types.
4996 for (BuiltinCandidateTypeSet::iterator
4997 Vec = CandidateTypes[0].vector_begin(),
4998 VecEnd = CandidateTypes[0].vector_end();
4999 Vec != VecEnd; ++Vec) {
5000 QualType VecTy = *Vec;
5001 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5002 }
5003 }
5004
5005 // C++ [over.built]p8:
5006 // For every type T, there exist candidate operator functions of
5007 // the form
5008 //
5009 // T* operator+(T*);
5010 void addUnaryPlusPointerOverloads() {
5011 for (BuiltinCandidateTypeSet::iterator
5012 Ptr = CandidateTypes[0].pointer_begin(),
5013 PtrEnd = CandidateTypes[0].pointer_end();
5014 Ptr != PtrEnd; ++Ptr) {
5015 QualType ParamTy = *Ptr;
5016 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5017 }
5018 }
5019
5020 // C++ [over.built]p10:
5021 // For every promoted integral type T, there exist candidate
5022 // operator functions of the form
5023 //
5024 // T operator~(T);
5025 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005026 if (!HasArithmeticOrEnumeralCandidateType)
5027 return;
5028
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005029 for (unsigned Int = FirstPromotedIntegralType;
5030 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005031 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005032 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5033 }
5034
5035 // Extension: We also add this operator for vector types.
5036 for (BuiltinCandidateTypeSet::iterator
5037 Vec = CandidateTypes[0].vector_begin(),
5038 VecEnd = CandidateTypes[0].vector_end();
5039 Vec != VecEnd; ++Vec) {
5040 QualType VecTy = *Vec;
5041 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5042 }
5043 }
5044
5045 // C++ [over.match.oper]p16:
5046 // For every pointer to member type T, there exist candidate operator
5047 // functions of the form
5048 //
5049 // bool operator==(T,T);
5050 // bool operator!=(T,T);
5051 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5052 /// Set of (canonical) types that we've already handled.
5053 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5054
5055 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5056 for (BuiltinCandidateTypeSet::iterator
5057 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5058 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5059 MemPtr != MemPtrEnd;
5060 ++MemPtr) {
5061 // Don't add the same builtin candidate twice.
5062 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5063 continue;
5064
5065 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5066 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5067 CandidateSet);
5068 }
5069 }
5070 }
5071
5072 // C++ [over.built]p15:
5073 //
5074 // For every pointer or enumeration type T, there exist
5075 // candidate operator functions of the form
5076 //
5077 // bool operator<(T, T);
5078 // bool operator>(T, T);
5079 // bool operator<=(T, T);
5080 // bool operator>=(T, T);
5081 // bool operator==(T, T);
5082 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005083 void addRelationalPointerOrEnumeralOverloads() {
5084 // C++ [over.built]p1:
5085 // If there is a user-written candidate with the same name and parameter
5086 // types as a built-in candidate operator function, the built-in operator
5087 // function is hidden and is not included in the set of candidate
5088 // functions.
5089 //
5090 // The text is actually in a note, but if we don't implement it then we end
5091 // up with ambiguities when the user provides an overloaded operator for
5092 // an enumeration type. Note that only enumeration types have this problem,
5093 // so we track which enumeration types we've seen operators for. Also, the
5094 // only other overloaded operator with enumeration argumenst, operator=,
5095 // cannot be overloaded for enumeration types, so this is the only place
5096 // where we must suppress candidates like this.
5097 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5098 UserDefinedBinaryOperators;
5099
5100 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5101 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5102 CandidateTypes[ArgIdx].enumeration_end()) {
5103 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5104 CEnd = CandidateSet.end();
5105 C != CEnd; ++C) {
5106 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5107 continue;
5108
5109 QualType FirstParamType =
5110 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5111 QualType SecondParamType =
5112 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5113
5114 // Skip if either parameter isn't of enumeral type.
5115 if (!FirstParamType->isEnumeralType() ||
5116 !SecondParamType->isEnumeralType())
5117 continue;
5118
5119 // Add this operator to the set of known user-defined operators.
5120 UserDefinedBinaryOperators.insert(
5121 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5122 S.Context.getCanonicalType(SecondParamType)));
5123 }
5124 }
5125 }
5126
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005127 /// Set of (canonical) types that we've already handled.
5128 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5129
5130 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5131 for (BuiltinCandidateTypeSet::iterator
5132 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5133 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5134 Ptr != PtrEnd; ++Ptr) {
5135 // Don't add the same builtin candidate twice.
5136 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5137 continue;
5138
5139 QualType ParamTypes[2] = { *Ptr, *Ptr };
5140 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5141 CandidateSet);
5142 }
5143 for (BuiltinCandidateTypeSet::iterator
5144 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5145 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5146 Enum != EnumEnd; ++Enum) {
5147 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5148
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005149 // Don't add the same builtin candidate twice, or if a user defined
5150 // candidate exists.
5151 if (!AddedTypes.insert(CanonType) ||
5152 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5153 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005154 continue;
5155
5156 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005157 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5158 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005159 }
5160 }
5161 }
5162
5163 // C++ [over.built]p13:
5164 //
5165 // For every cv-qualified or cv-unqualified object type T
5166 // there exist candidate operator functions of the form
5167 //
5168 // T* operator+(T*, ptrdiff_t);
5169 // T& operator[](T*, ptrdiff_t); [BELOW]
5170 // T* operator-(T*, ptrdiff_t);
5171 // T* operator+(ptrdiff_t, T*);
5172 // T& operator[](ptrdiff_t, T*); [BELOW]
5173 //
5174 // C++ [over.built]p14:
5175 //
5176 // For every T, where T is a pointer to object type, there
5177 // exist candidate operator functions of the form
5178 //
5179 // ptrdiff_t operator-(T, T);
5180 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5181 /// Set of (canonical) types that we've already handled.
5182 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5183
5184 for (int Arg = 0; Arg < 2; ++Arg) {
5185 QualType AsymetricParamTypes[2] = {
5186 S.Context.getPointerDiffType(),
5187 S.Context.getPointerDiffType(),
5188 };
5189 for (BuiltinCandidateTypeSet::iterator
5190 Ptr = CandidateTypes[Arg].pointer_begin(),
5191 PtrEnd = CandidateTypes[Arg].pointer_end();
5192 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005193 QualType PointeeTy = (*Ptr)->getPointeeType();
5194 if (!PointeeTy->isObjectType())
5195 continue;
5196
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005197 AsymetricParamTypes[Arg] = *Ptr;
5198 if (Arg == 0 || Op == OO_Plus) {
5199 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5200 // T* operator+(ptrdiff_t, T*);
5201 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5202 CandidateSet);
5203 }
5204 if (Op == OO_Minus) {
5205 // ptrdiff_t operator-(T, T);
5206 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5207 continue;
5208
5209 QualType ParamTypes[2] = { *Ptr, *Ptr };
5210 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5211 Args, 2, CandidateSet);
5212 }
5213 }
5214 }
5215 }
5216
5217 // C++ [over.built]p12:
5218 //
5219 // For every pair of promoted arithmetic types L and R, there
5220 // exist candidate operator functions of the form
5221 //
5222 // LR operator*(L, R);
5223 // LR operator/(L, R);
5224 // LR operator+(L, R);
5225 // LR operator-(L, R);
5226 // bool operator<(L, R);
5227 // bool operator>(L, R);
5228 // bool operator<=(L, R);
5229 // bool operator>=(L, R);
5230 // bool operator==(L, R);
5231 // bool operator!=(L, R);
5232 //
5233 // where LR is the result of the usual arithmetic conversions
5234 // between types L and R.
5235 //
5236 // C++ [over.built]p24:
5237 //
5238 // For every pair of promoted arithmetic types L and R, there exist
5239 // candidate operator functions of the form
5240 //
5241 // LR operator?(bool, L, R);
5242 //
5243 // where LR is the result of the usual arithmetic conversions
5244 // between types L and R.
5245 // Our candidates ignore the first parameter.
5246 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005247 if (!HasArithmeticOrEnumeralCandidateType)
5248 return;
5249
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005250 for (unsigned Left = FirstPromotedArithmeticType;
5251 Left < LastPromotedArithmeticType; ++Left) {
5252 for (unsigned Right = FirstPromotedArithmeticType;
5253 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005254 QualType LandR[2] = { getArithmeticType(Left),
5255 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005256 QualType Result =
5257 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005258 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005259 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5260 }
5261 }
5262
5263 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5264 // conditional operator for vector types.
5265 for (BuiltinCandidateTypeSet::iterator
5266 Vec1 = CandidateTypes[0].vector_begin(),
5267 Vec1End = CandidateTypes[0].vector_end();
5268 Vec1 != Vec1End; ++Vec1) {
5269 for (BuiltinCandidateTypeSet::iterator
5270 Vec2 = CandidateTypes[1].vector_begin(),
5271 Vec2End = CandidateTypes[1].vector_end();
5272 Vec2 != Vec2End; ++Vec2) {
5273 QualType LandR[2] = { *Vec1, *Vec2 };
5274 QualType Result = S.Context.BoolTy;
5275 if (!isComparison) {
5276 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5277 Result = *Vec1;
5278 else
5279 Result = *Vec2;
5280 }
5281
5282 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5283 }
5284 }
5285 }
5286
5287 // C++ [over.built]p17:
5288 //
5289 // For every pair of promoted integral types L and R, there
5290 // exist candidate operator functions of the form
5291 //
5292 // LR operator%(L, R);
5293 // LR operator&(L, R);
5294 // LR operator^(L, R);
5295 // LR operator|(L, R);
5296 // L operator<<(L, R);
5297 // L operator>>(L, R);
5298 //
5299 // where LR is the result of the usual arithmetic conversions
5300 // between types L and R.
5301 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005302 if (!HasArithmeticOrEnumeralCandidateType)
5303 return;
5304
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005305 for (unsigned Left = FirstPromotedIntegralType;
5306 Left < LastPromotedIntegralType; ++Left) {
5307 for (unsigned Right = FirstPromotedIntegralType;
5308 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005309 QualType LandR[2] = { getArithmeticType(Left),
5310 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005311 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5312 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005313 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005314 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5315 }
5316 }
5317 }
5318
5319 // C++ [over.built]p20:
5320 //
5321 // For every pair (T, VQ), where T is an enumeration or
5322 // pointer to member type and VQ is either volatile or
5323 // empty, there exist candidate operator functions of the form
5324 //
5325 // VQ T& operator=(VQ T&, T);
5326 void addAssignmentMemberPointerOrEnumeralOverloads() {
5327 /// Set of (canonical) types that we've already handled.
5328 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5329
5330 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5331 for (BuiltinCandidateTypeSet::iterator
5332 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5333 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5334 Enum != EnumEnd; ++Enum) {
5335 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5336 continue;
5337
5338 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5339 CandidateSet);
5340 }
5341
5342 for (BuiltinCandidateTypeSet::iterator
5343 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5344 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5345 MemPtr != MemPtrEnd; ++MemPtr) {
5346 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5347 continue;
5348
5349 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5350 CandidateSet);
5351 }
5352 }
5353 }
5354
5355 // C++ [over.built]p19:
5356 //
5357 // For every pair (T, VQ), where T is any type and VQ is either
5358 // volatile or empty, there exist candidate operator functions
5359 // of the form
5360 //
5361 // T*VQ& operator=(T*VQ&, T*);
5362 //
5363 // C++ [over.built]p21:
5364 //
5365 // For every pair (T, VQ), where T is a cv-qualified or
5366 // cv-unqualified object type and VQ is either volatile or
5367 // empty, there exist candidate operator functions of the form
5368 //
5369 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5370 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5371 void addAssignmentPointerOverloads(bool isEqualOp) {
5372 /// Set of (canonical) types that we've already handled.
5373 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5374
5375 for (BuiltinCandidateTypeSet::iterator
5376 Ptr = CandidateTypes[0].pointer_begin(),
5377 PtrEnd = CandidateTypes[0].pointer_end();
5378 Ptr != PtrEnd; ++Ptr) {
5379 // If this is operator=, keep track of the builtin candidates we added.
5380 if (isEqualOp)
5381 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005382 else if (!(*Ptr)->getPointeeType()->isObjectType())
5383 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005384
5385 // non-volatile version
5386 QualType ParamTypes[2] = {
5387 S.Context.getLValueReferenceType(*Ptr),
5388 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5389 };
5390 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5391 /*IsAssigmentOperator=*/ isEqualOp);
5392
5393 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5394 VisibleTypeConversionsQuals.hasVolatile()) {
5395 // volatile version
5396 ParamTypes[0] =
5397 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5398 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5399 /*IsAssigmentOperator=*/isEqualOp);
5400 }
5401 }
5402
5403 if (isEqualOp) {
5404 for (BuiltinCandidateTypeSet::iterator
5405 Ptr = CandidateTypes[1].pointer_begin(),
5406 PtrEnd = CandidateTypes[1].pointer_end();
5407 Ptr != PtrEnd; ++Ptr) {
5408 // Make sure we don't add the same candidate twice.
5409 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5410 continue;
5411
Chandler Carruth8e543b32010-12-12 08:17:55 +00005412 QualType ParamTypes[2] = {
5413 S.Context.getLValueReferenceType(*Ptr),
5414 *Ptr,
5415 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005416
5417 // non-volatile version
5418 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5419 /*IsAssigmentOperator=*/true);
5420
5421 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5422 VisibleTypeConversionsQuals.hasVolatile()) {
5423 // volatile version
5424 ParamTypes[0] =
5425 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00005426 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5427 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005428 }
5429 }
5430 }
5431 }
5432
5433 // C++ [over.built]p18:
5434 //
5435 // For every triple (L, VQ, R), where L is an arithmetic type,
5436 // VQ is either volatile or empty, and R is a promoted
5437 // arithmetic type, there exist candidate operator functions of
5438 // the form
5439 //
5440 // VQ L& operator=(VQ L&, R);
5441 // VQ L& operator*=(VQ L&, R);
5442 // VQ L& operator/=(VQ L&, R);
5443 // VQ L& operator+=(VQ L&, R);
5444 // VQ L& operator-=(VQ L&, R);
5445 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005446 if (!HasArithmeticOrEnumeralCandidateType)
5447 return;
5448
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005449 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5450 for (unsigned Right = FirstPromotedArithmeticType;
5451 Right < LastPromotedArithmeticType; ++Right) {
5452 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005453 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005454
5455 // Add this built-in operator as a candidate (VQ is empty).
5456 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005457 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005458 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5459 /*IsAssigmentOperator=*/isEqualOp);
5460
5461 // Add this built-in operator as a candidate (VQ is 'volatile').
5462 if (VisibleTypeConversionsQuals.hasVolatile()) {
5463 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005464 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005465 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005466 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5467 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005468 /*IsAssigmentOperator=*/isEqualOp);
5469 }
5470 }
5471 }
5472
5473 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5474 for (BuiltinCandidateTypeSet::iterator
5475 Vec1 = CandidateTypes[0].vector_begin(),
5476 Vec1End = CandidateTypes[0].vector_end();
5477 Vec1 != Vec1End; ++Vec1) {
5478 for (BuiltinCandidateTypeSet::iterator
5479 Vec2 = CandidateTypes[1].vector_begin(),
5480 Vec2End = CandidateTypes[1].vector_end();
5481 Vec2 != Vec2End; ++Vec2) {
5482 QualType ParamTypes[2];
5483 ParamTypes[1] = *Vec2;
5484 // Add this built-in operator as a candidate (VQ is empty).
5485 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5486 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5487 /*IsAssigmentOperator=*/isEqualOp);
5488
5489 // Add this built-in operator as a candidate (VQ is 'volatile').
5490 if (VisibleTypeConversionsQuals.hasVolatile()) {
5491 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5492 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005493 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5494 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005495 /*IsAssigmentOperator=*/isEqualOp);
5496 }
5497 }
5498 }
5499 }
5500
5501 // C++ [over.built]p22:
5502 //
5503 // For every triple (L, VQ, R), where L is an integral type, VQ
5504 // is either volatile or empty, and R is a promoted integral
5505 // type, there exist candidate operator functions of the form
5506 //
5507 // VQ L& operator%=(VQ L&, R);
5508 // VQ L& operator<<=(VQ L&, R);
5509 // VQ L& operator>>=(VQ L&, R);
5510 // VQ L& operator&=(VQ L&, R);
5511 // VQ L& operator^=(VQ L&, R);
5512 // VQ L& operator|=(VQ L&, R);
5513 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005514 if (!HasArithmeticOrEnumeralCandidateType)
5515 return;
5516
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005517 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5518 for (unsigned Right = FirstPromotedIntegralType;
5519 Right < LastPromotedIntegralType; ++Right) {
5520 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005521 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005522
5523 // Add this built-in operator as a candidate (VQ is empty).
5524 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005525 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005526 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5527 if (VisibleTypeConversionsQuals.hasVolatile()) {
5528 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00005529 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005530 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5531 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5532 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5533 CandidateSet);
5534 }
5535 }
5536 }
5537 }
5538
5539 // C++ [over.operator]p23:
5540 //
5541 // There also exist candidate operator functions of the form
5542 //
5543 // bool operator!(bool);
5544 // bool operator&&(bool, bool);
5545 // bool operator||(bool, bool);
5546 void addExclaimOverload() {
5547 QualType ParamTy = S.Context.BoolTy;
5548 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5549 /*IsAssignmentOperator=*/false,
5550 /*NumContextualBoolArguments=*/1);
5551 }
5552 void addAmpAmpOrPipePipeOverload() {
5553 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5554 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5555 /*IsAssignmentOperator=*/false,
5556 /*NumContextualBoolArguments=*/2);
5557 }
5558
5559 // C++ [over.built]p13:
5560 //
5561 // For every cv-qualified or cv-unqualified object type T there
5562 // exist candidate operator functions of the form
5563 //
5564 // T* operator+(T*, ptrdiff_t); [ABOVE]
5565 // T& operator[](T*, ptrdiff_t);
5566 // T* operator-(T*, ptrdiff_t); [ABOVE]
5567 // T* operator+(ptrdiff_t, T*); [ABOVE]
5568 // T& operator[](ptrdiff_t, T*);
5569 void addSubscriptOverloads() {
5570 for (BuiltinCandidateTypeSet::iterator
5571 Ptr = CandidateTypes[0].pointer_begin(),
5572 PtrEnd = CandidateTypes[0].pointer_end();
5573 Ptr != PtrEnd; ++Ptr) {
5574 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5575 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005576 if (!PointeeType->isObjectType())
5577 continue;
5578
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005579 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5580
5581 // T& operator[](T*, ptrdiff_t)
5582 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5583 }
5584
5585 for (BuiltinCandidateTypeSet::iterator
5586 Ptr = CandidateTypes[1].pointer_begin(),
5587 PtrEnd = CandidateTypes[1].pointer_end();
5588 Ptr != PtrEnd; ++Ptr) {
5589 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5590 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005591 if (!PointeeType->isObjectType())
5592 continue;
5593
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005594 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5595
5596 // T& operator[](ptrdiff_t, T*)
5597 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5598 }
5599 }
5600
5601 // C++ [over.built]p11:
5602 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5603 // C1 is the same type as C2 or is a derived class of C2, T is an object
5604 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5605 // there exist candidate operator functions of the form
5606 //
5607 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5608 //
5609 // where CV12 is the union of CV1 and CV2.
5610 void addArrowStarOverloads() {
5611 for (BuiltinCandidateTypeSet::iterator
5612 Ptr = CandidateTypes[0].pointer_begin(),
5613 PtrEnd = CandidateTypes[0].pointer_end();
5614 Ptr != PtrEnd; ++Ptr) {
5615 QualType C1Ty = (*Ptr);
5616 QualType C1;
5617 QualifierCollector Q1;
5618 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5619 if (!isa<RecordType>(C1))
5620 continue;
5621 // heuristic to reduce number of builtin candidates in the set.
5622 // Add volatile/restrict version only if there are conversions to a
5623 // volatile/restrict type.
5624 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5625 continue;
5626 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5627 continue;
5628 for (BuiltinCandidateTypeSet::iterator
5629 MemPtr = CandidateTypes[1].member_pointer_begin(),
5630 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5631 MemPtr != MemPtrEnd; ++MemPtr) {
5632 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5633 QualType C2 = QualType(mptr->getClass(), 0);
5634 C2 = C2.getUnqualifiedType();
5635 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5636 break;
5637 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5638 // build CV12 T&
5639 QualType T = mptr->getPointeeType();
5640 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5641 T.isVolatileQualified())
5642 continue;
5643 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5644 T.isRestrictQualified())
5645 continue;
5646 T = Q1.apply(S.Context, T);
5647 QualType ResultTy = S.Context.getLValueReferenceType(T);
5648 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5649 }
5650 }
5651 }
5652
5653 // Note that we don't consider the first argument, since it has been
5654 // contextually converted to bool long ago. The candidates below are
5655 // therefore added as binary.
5656 //
5657 // C++ [over.built]p25:
5658 // For every type T, where T is a pointer, pointer-to-member, or scoped
5659 // enumeration type, there exist candidate operator functions of the form
5660 //
5661 // T operator?(bool, T, T);
5662 //
5663 void addConditionalOperatorOverloads() {
5664 /// Set of (canonical) types that we've already handled.
5665 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5666
5667 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5668 for (BuiltinCandidateTypeSet::iterator
5669 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5670 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5671 Ptr != PtrEnd; ++Ptr) {
5672 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5673 continue;
5674
5675 QualType ParamTypes[2] = { *Ptr, *Ptr };
5676 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5677 }
5678
5679 for (BuiltinCandidateTypeSet::iterator
5680 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5681 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5682 MemPtr != MemPtrEnd; ++MemPtr) {
5683 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5684 continue;
5685
5686 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5687 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5688 }
5689
5690 if (S.getLangOptions().CPlusPlus0x) {
5691 for (BuiltinCandidateTypeSet::iterator
5692 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5693 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5694 Enum != EnumEnd; ++Enum) {
5695 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5696 continue;
5697
5698 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5699 continue;
5700
5701 QualType ParamTypes[2] = { *Enum, *Enum };
5702 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5703 }
5704 }
5705 }
5706 }
5707};
5708
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005709} // end anonymous namespace
5710
5711/// AddBuiltinOperatorCandidates - Add the appropriate built-in
5712/// operator overloads to the candidate set (C++ [over.built]), based
5713/// on the operator @p Op and the arguments given. For example, if the
5714/// operator is a binary '+', this routine might add "int
5715/// operator+(int, int)" to cover integer addition.
5716void
5717Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5718 SourceLocation OpLoc,
5719 Expr **Args, unsigned NumArgs,
5720 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005721 // Find all of the types that the arguments can convert to, but only
5722 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00005723 // that make use of these types. Also record whether we encounter non-record
5724 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005725 Qualifiers VisibleTypeConversionsQuals;
5726 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005727 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5728 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00005729
5730 bool HasNonRecordCandidateType = false;
5731 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005732 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5733 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5734 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5735 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5736 OpLoc,
5737 true,
5738 (Op == OO_Exclaim ||
5739 Op == OO_AmpAmp ||
5740 Op == OO_PipePipe),
5741 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00005742 HasNonRecordCandidateType = HasNonRecordCandidateType ||
5743 CandidateTypes[ArgIdx].hasNonRecordTypes();
5744 HasArithmeticOrEnumeralCandidateType =
5745 HasArithmeticOrEnumeralCandidateType ||
5746 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005747 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005748
Chandler Carruth00a38332010-12-13 01:44:01 +00005749 // Exit early when no non-record types have been added to the candidate set
5750 // for any of the arguments to the operator.
5751 if (!HasNonRecordCandidateType)
5752 return;
5753
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005754 // Setup an object to manage the common state for building overloads.
5755 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
5756 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005757 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005758 CandidateTypes, CandidateSet);
5759
5760 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00005761 switch (Op) {
5762 case OO_None:
5763 case NUM_OVERLOADED_OPERATORS:
5764 assert(false && "Expected an overloaded operator");
5765 break;
5766
Chandler Carruth5184de02010-12-12 08:51:33 +00005767 case OO_New:
5768 case OO_Delete:
5769 case OO_Array_New:
5770 case OO_Array_Delete:
5771 case OO_Call:
5772 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
5773 break;
5774
5775 case OO_Comma:
5776 case OO_Arrow:
5777 // C++ [over.match.oper]p3:
5778 // -- For the operator ',', the unary operator '&', or the
5779 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00005780 break;
5781
5782 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00005783 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005784 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00005785 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00005786
5787 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00005788 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005789 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00005790 } else {
5791 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
5792 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5793 }
Douglas Gregord08452f2008-11-19 15:42:04 +00005794 break;
5795
Chandler Carruth5184de02010-12-12 08:51:33 +00005796 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00005797 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00005798 OpBuilder.addUnaryStarPointerOverloads();
5799 else
5800 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5801 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005802
Chandler Carruth5184de02010-12-12 08:51:33 +00005803 case OO_Slash:
5804 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00005805 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005806
5807 case OO_PlusPlus:
5808 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005809 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
5810 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00005811 break;
5812
Douglas Gregor84605ae2009-08-24 13:43:27 +00005813 case OO_EqualEqual:
5814 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005815 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00005816 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00005817
Douglas Gregora11693b2008-11-12 17:17:38 +00005818 case OO_Less:
5819 case OO_Greater:
5820 case OO_LessEqual:
5821 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005822 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00005823 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
5824 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005825
Douglas Gregora11693b2008-11-12 17:17:38 +00005826 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00005827 case OO_Caret:
5828 case OO_Pipe:
5829 case OO_LessLess:
5830 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005831 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00005832 break;
5833
Chandler Carruth5184de02010-12-12 08:51:33 +00005834 case OO_Amp: // '&' is either unary or binary
5835 if (NumArgs == 1)
5836 // C++ [over.match.oper]p3:
5837 // -- For the operator ',', the unary operator '&', or the
5838 // operator '->', the built-in candidates set is empty.
5839 break;
5840
5841 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
5842 break;
5843
5844 case OO_Tilde:
5845 OpBuilder.addUnaryTildePromotedIntegralOverloads();
5846 break;
5847
Douglas Gregora11693b2008-11-12 17:17:38 +00005848 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005849 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005850 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00005851
5852 case OO_PlusEqual:
5853 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005854 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005855 // Fall through.
5856
5857 case OO_StarEqual:
5858 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005859 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005860 break;
5861
5862 case OO_PercentEqual:
5863 case OO_LessLessEqual:
5864 case OO_GreaterGreaterEqual:
5865 case OO_AmpEqual:
5866 case OO_CaretEqual:
5867 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005868 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005869 break;
5870
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005871 case OO_Exclaim:
5872 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00005873 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005874
Douglas Gregora11693b2008-11-12 17:17:38 +00005875 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005876 case OO_PipePipe:
5877 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00005878 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005879
5880 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005881 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005882 break;
5883
5884 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005885 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005886 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005887
5888 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005889 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00005890 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5891 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005892 }
5893}
5894
Douglas Gregore254f902009-02-04 00:32:51 +00005895/// \brief Add function candidates found via argument-dependent lookup
5896/// to the set of overloading candidates.
5897///
5898/// This routine performs argument-dependent name lookup based on the
5899/// given function name (which may also be an operator name) and adds
5900/// all of the overload candidates found by ADL to the overload
5901/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005902void
Douglas Gregore254f902009-02-04 00:32:51 +00005903Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005904 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005905 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005906 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005907 OverloadCandidateSet& CandidateSet,
5908 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005909 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005910
John McCall91f61fc2010-01-26 06:04:06 +00005911 // FIXME: This approach for uniquing ADL results (and removing
5912 // redundant candidates from the set) relies on pointer-equality,
5913 // which means we need to key off the canonical decl. However,
5914 // always going back to the canonical decl might not get us the
5915 // right set of default arguments. What default arguments are
5916 // we supposed to consider on ADL candidates, anyway?
5917
Douglas Gregorcabea402009-09-22 15:41:20 +00005918 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005919 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005920
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005921 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005922 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5923 CandEnd = CandidateSet.end();
5924 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005925 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005926 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005927 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005928 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005929 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005930
5931 // For each of the ADL candidates we found, add it to the overload
5932 // set.
John McCall8fe68082010-01-26 07:16:45 +00005933 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005934 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005935 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005936 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005937 continue;
5938
John McCalla0296f72010-03-19 07:35:19 +00005939 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005940 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005941 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005942 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005943 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005944 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005945 }
Douglas Gregore254f902009-02-04 00:32:51 +00005946}
5947
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005948/// isBetterOverloadCandidate - Determines whether the first overload
5949/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005950bool
John McCall5c32be02010-08-24 20:38:10 +00005951isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00005952 const OverloadCandidate &Cand1,
5953 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005954 SourceLocation Loc,
5955 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005956 // Define viable functions to be better candidates than non-viable
5957 // functions.
5958 if (!Cand2.Viable)
5959 return Cand1.Viable;
5960 else if (!Cand1.Viable)
5961 return false;
5962
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005963 // C++ [over.match.best]p1:
5964 //
5965 // -- if F is a static member function, ICS1(F) is defined such
5966 // that ICS1(F) is neither better nor worse than ICS1(G) for
5967 // any function G, and, symmetrically, ICS1(G) is neither
5968 // better nor worse than ICS1(F).
5969 unsigned StartArg = 0;
5970 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5971 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005972
Douglas Gregord3cb3562009-07-07 23:38:56 +00005973 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005974 // A viable function F1 is defined to be a better function than another
5975 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005976 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005977 unsigned NumArgs = Cand1.Conversions.size();
5978 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5979 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005980 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00005981 switch (CompareImplicitConversionSequences(S,
5982 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005983 Cand2.Conversions[ArgIdx])) {
5984 case ImplicitConversionSequence::Better:
5985 // Cand1 has a better conversion sequence.
5986 HasBetterConversion = true;
5987 break;
5988
5989 case ImplicitConversionSequence::Worse:
5990 // Cand1 can't be better than Cand2.
5991 return false;
5992
5993 case ImplicitConversionSequence::Indistinguishable:
5994 // Do nothing.
5995 break;
5996 }
5997 }
5998
Mike Stump11289f42009-09-09 15:08:12 +00005999 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006000 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006001 if (HasBetterConversion)
6002 return true;
6003
Mike Stump11289f42009-09-09 15:08:12 +00006004 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006005 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006006 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006007 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6008 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006009
6010 // -- F1 and F2 are function template specializations, and the function
6011 // template for F1 is more specialized than the template for F2
6012 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006013 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006014 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006015 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006016 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006017 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6018 Cand2.Function->getPrimaryTemplate(),
6019 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00006020 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006021 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006022 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006023 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006024 }
6025
Douglas Gregora1f013e2008-11-07 22:36:19 +00006026 // -- the context is an initialization by user-defined conversion
6027 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6028 // from the return type of F1 to the destination type (i.e.,
6029 // the type of the entity being initialized) is a better
6030 // conversion sequence than the standard conversion sequence
6031 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006032 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006033 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006034 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006035 switch (CompareStandardConversionSequences(S,
6036 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006037 Cand2.FinalConversion)) {
6038 case ImplicitConversionSequence::Better:
6039 // Cand1 has a better conversion sequence.
6040 return true;
6041
6042 case ImplicitConversionSequence::Worse:
6043 // Cand1 can't be better than Cand2.
6044 return false;
6045
6046 case ImplicitConversionSequence::Indistinguishable:
6047 // Do nothing
6048 break;
6049 }
6050 }
6051
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006052 return false;
6053}
6054
Mike Stump11289f42009-09-09 15:08:12 +00006055/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006056/// within an overload candidate set.
6057///
6058/// \param CandidateSet the set of candidate functions.
6059///
6060/// \param Loc the location of the function name (or operator symbol) for
6061/// which overload resolution occurs.
6062///
Mike Stump11289f42009-09-09 15:08:12 +00006063/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006064/// function, Best points to the candidate function found.
6065///
6066/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006067OverloadingResult
6068OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006069 iterator &Best,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006070 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006071 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006072 Best = end();
6073 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6074 if (Cand->Viable)
Douglas Gregord5b730c92010-09-12 08:07:23 +00006075 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
6076 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006077 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006078 }
6079
6080 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006081 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006082 return OR_No_Viable_Function;
6083
6084 // Make sure that this function is better than every other viable
6085 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006086 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006087 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006088 Cand != Best &&
Douglas Gregord5b730c92010-09-12 08:07:23 +00006089 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
6090 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006091 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006092 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006093 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006094 }
Mike Stump11289f42009-09-09 15:08:12 +00006095
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006096 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006097 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006098 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006099 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006100 return OR_Deleted;
6101
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006102 // C++ [basic.def.odr]p2:
6103 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00006104 // when referred to from a potentially-evaluated expression. [Note: this
6105 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006106 // (clause 13), user-defined conversions (12.3.2), allocation function for
6107 // placement new (5.3.4), as well as non-default initialization (8.5).
6108 if (Best->Function)
John McCall5c32be02010-08-24 20:38:10 +00006109 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006110
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006111 return OR_Success;
6112}
6113
John McCall53262c92010-01-12 02:15:36 +00006114namespace {
6115
6116enum OverloadCandidateKind {
6117 oc_function,
6118 oc_method,
6119 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006120 oc_function_template,
6121 oc_method_template,
6122 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006123 oc_implicit_default_constructor,
6124 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006125 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00006126};
6127
John McCalle1ac8d12010-01-13 00:25:19 +00006128OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6129 FunctionDecl *Fn,
6130 std::string &Description) {
6131 bool isTemplate = false;
6132
6133 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6134 isTemplate = true;
6135 Description = S.getTemplateArgumentBindingsText(
6136 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6137 }
John McCallfd0b2f82010-01-06 09:43:14 +00006138
6139 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006140 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006141 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006142
John McCall53262c92010-01-12 02:15:36 +00006143 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6144 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006145 }
6146
6147 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6148 // This actually gets spelled 'candidate function' for now, but
6149 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006150 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006151 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006152
Douglas Gregorec3bec02010-09-27 22:37:28 +00006153 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006154 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006155 return oc_implicit_copy_assignment;
6156 }
6157
John McCalle1ac8d12010-01-13 00:25:19 +00006158 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006159}
6160
6161} // end anonymous namespace
6162
6163// Notes the location of an overload candidate.
6164void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006165 std::string FnDesc;
6166 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6167 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6168 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00006169}
6170
John McCall0d1da222010-01-12 00:44:57 +00006171/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6172/// "lead" diagnostic; it will be given two arguments, the source and
6173/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006174void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6175 Sema &S,
6176 SourceLocation CaretLoc,
6177 const PartialDiagnostic &PDiag) const {
6178 S.Diag(CaretLoc, PDiag)
6179 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006180 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006181 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6182 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006183 }
John McCall12f97bc2010-01-08 04:41:39 +00006184}
6185
John McCall0d1da222010-01-12 00:44:57 +00006186namespace {
6187
John McCall6a61b522010-01-13 09:16:55 +00006188void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6189 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6190 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006191 assert(Cand->Function && "for now, candidate must be a function");
6192 FunctionDecl *Fn = Cand->Function;
6193
6194 // There's a conversion slot for the object argument if this is a
6195 // non-constructor method. Note that 'I' corresponds the
6196 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006197 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006198 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006199 if (I == 0)
6200 isObjectArgument = true;
6201 else
6202 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006203 }
6204
John McCalle1ac8d12010-01-13 00:25:19 +00006205 std::string FnDesc;
6206 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6207
John McCall6a61b522010-01-13 09:16:55 +00006208 Expr *FromExpr = Conv.Bad.FromExpr;
6209 QualType FromTy = Conv.Bad.getFromType();
6210 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006211
John McCallfb7ad0f2010-02-02 02:42:52 +00006212 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006213 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006214 Expr *E = FromExpr->IgnoreParens();
6215 if (isa<UnaryOperator>(E))
6216 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006217 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006218
6219 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6220 << (unsigned) FnKind << FnDesc
6221 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6222 << ToTy << Name << I+1;
6223 return;
6224 }
6225
John McCall6d174642010-01-23 08:10:49 +00006226 // Do some hand-waving analysis to see if the non-viability is due
6227 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006228 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6229 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6230 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6231 CToTy = RT->getPointeeType();
6232 else {
6233 // TODO: detect and diagnose the full richness of const mismatches.
6234 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6235 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6236 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6237 }
6238
6239 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6240 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6241 // It is dumb that we have to do this here.
6242 while (isa<ArrayType>(CFromTy))
6243 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6244 while (isa<ArrayType>(CToTy))
6245 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6246
6247 Qualifiers FromQs = CFromTy.getQualifiers();
6248 Qualifiers ToQs = CToTy.getQualifiers();
6249
6250 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6251 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6252 << (unsigned) FnKind << FnDesc
6253 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6254 << FromTy
6255 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6256 << (unsigned) isObjectArgument << I+1;
6257 return;
6258 }
6259
6260 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6261 assert(CVR && "unexpected qualifiers mismatch");
6262
6263 if (isObjectArgument) {
6264 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6265 << (unsigned) FnKind << FnDesc
6266 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6267 << FromTy << (CVR - 1);
6268 } else {
6269 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6270 << (unsigned) FnKind << FnDesc
6271 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6272 << FromTy << (CVR - 1) << I+1;
6273 }
6274 return;
6275 }
6276
John McCall6d174642010-01-23 08:10:49 +00006277 // Diagnose references or pointers to incomplete types differently,
6278 // since it's far from impossible that the incompleteness triggered
6279 // the failure.
6280 QualType TempFromTy = FromTy.getNonReferenceType();
6281 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6282 TempFromTy = PTy->getPointeeType();
6283 if (TempFromTy->isIncompleteType()) {
6284 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6285 << (unsigned) FnKind << FnDesc
6286 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6287 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6288 return;
6289 }
6290
Douglas Gregor56f2e342010-06-30 23:01:39 +00006291 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006292 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006293 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6294 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6295 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6296 FromPtrTy->getPointeeType()) &&
6297 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6298 !ToPtrTy->getPointeeType()->isIncompleteType() &&
6299 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
6300 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006301 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006302 }
6303 } else if (const ObjCObjectPointerType *FromPtrTy
6304 = FromTy->getAs<ObjCObjectPointerType>()) {
6305 if (const ObjCObjectPointerType *ToPtrTy
6306 = ToTy->getAs<ObjCObjectPointerType>())
6307 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6308 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6309 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6310 FromPtrTy->getPointeeType()) &&
6311 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006312 BaseToDerivedConversion = 2;
6313 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6314 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6315 !FromTy->isIncompleteType() &&
6316 !ToRefTy->getPointeeType()->isIncompleteType() &&
6317 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6318 BaseToDerivedConversion = 3;
6319 }
6320
6321 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00006322 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006323 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006324 << (unsigned) FnKind << FnDesc
6325 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006326 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006327 << FromTy << ToTy << I+1;
6328 return;
6329 }
6330
John McCall47000992010-01-14 03:28:57 +00006331 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00006332 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6333 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006334 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006335 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00006336}
6337
6338void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6339 unsigned NumFormalArgs) {
6340 // TODO: treat calls to a missing default constructor as a special case
6341
6342 FunctionDecl *Fn = Cand->Function;
6343 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6344
6345 unsigned MinParams = Fn->getMinRequiredArguments();
6346
6347 // at least / at most / exactly
6348 unsigned mode, modeCount;
6349 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006350 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6351 (Cand->FailureKind == ovl_fail_bad_deduction &&
6352 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
Douglas Gregor7825bf32011-01-06 22:09:01 +00006353 if (MinParams != FnTy->getNumArgs() ||
6354 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00006355 mode = 0; // "at least"
6356 else
6357 mode = 2; // "exactly"
6358 modeCount = MinParams;
6359 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006360 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6361 (Cand->FailureKind == ovl_fail_bad_deduction &&
6362 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006363 if (MinParams != FnTy->getNumArgs())
6364 mode = 1; // "at most"
6365 else
6366 mode = 2; // "exactly"
6367 modeCount = FnTy->getNumArgs();
6368 }
6369
6370 std::string Description;
6371 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6372
6373 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00006374 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6375 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00006376}
6377
John McCall8b9ed552010-02-01 18:53:26 +00006378/// Diagnose a failed template-argument deduction.
6379void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6380 Expr **Args, unsigned NumArgs) {
6381 FunctionDecl *Fn = Cand->Function; // pattern
6382
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006383 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006384 NamedDecl *ParamD;
6385 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6386 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6387 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006388 switch (Cand->DeductionFailure.Result) {
6389 case Sema::TDK_Success:
6390 llvm_unreachable("TDK_success while diagnosing bad deduction");
6391
6392 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006393 assert(ParamD && "no parameter found for incomplete deduction result");
6394 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6395 << ParamD->getDeclName();
6396 return;
6397 }
6398
John McCall42d7d192010-08-05 09:05:08 +00006399 case Sema::TDK_Underqualified: {
6400 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6401 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6402
6403 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6404
6405 // Param will have been canonicalized, but it should just be a
6406 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00006407 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00006408 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00006409 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00006410 assert(S.Context.hasSameType(Param, NonCanonParam));
6411
6412 // Arg has also been canonicalized, but there's nothing we can do
6413 // about that. It also doesn't matter as much, because it won't
6414 // have any template parameters in it (because deduction isn't
6415 // done on dependent types).
6416 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6417
6418 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6419 << ParamD->getDeclName() << Arg << NonCanonParam;
6420 return;
6421 }
6422
6423 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00006424 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006425 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006426 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006427 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006428 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006429 which = 1;
6430 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006431 which = 2;
6432 }
6433
6434 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6435 << which << ParamD->getDeclName()
6436 << *Cand->DeductionFailure.getFirstArg()
6437 << *Cand->DeductionFailure.getSecondArg();
6438 return;
6439 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006440
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006441 case Sema::TDK_InvalidExplicitArguments:
6442 assert(ParamD && "no parameter found for invalid explicit arguments");
6443 if (ParamD->getDeclName())
6444 S.Diag(Fn->getLocation(),
6445 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6446 << ParamD->getDeclName();
6447 else {
6448 int index = 0;
6449 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6450 index = TTP->getIndex();
6451 else if (NonTypeTemplateParmDecl *NTTP
6452 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6453 index = NTTP->getIndex();
6454 else
6455 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6456 S.Diag(Fn->getLocation(),
6457 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6458 << (index + 1);
6459 }
6460 return;
6461
Douglas Gregor02eb4832010-05-08 18:13:28 +00006462 case Sema::TDK_TooManyArguments:
6463 case Sema::TDK_TooFewArguments:
6464 DiagnoseArityMismatch(S, Cand, NumArgs);
6465 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006466
6467 case Sema::TDK_InstantiationDepth:
6468 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6469 return;
6470
6471 case Sema::TDK_SubstitutionFailure: {
6472 std::string ArgString;
6473 if (TemplateArgumentList *Args
6474 = Cand->DeductionFailure.getTemplateArgumentList())
6475 ArgString = S.getTemplateArgumentBindingsText(
6476 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6477 *Args);
6478 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6479 << ArgString;
6480 return;
6481 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006482
John McCall8b9ed552010-02-01 18:53:26 +00006483 // TODO: diagnose these individually, then kill off
6484 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006485 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006486 case Sema::TDK_FailedOverloadResolution:
6487 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6488 return;
6489 }
6490}
6491
6492/// Generates a 'note' diagnostic for an overload candidate. We've
6493/// already generated a primary error at the call site.
6494///
6495/// It really does need to be a single diagnostic with its caret
6496/// pointed at the candidate declaration. Yes, this creates some
6497/// major challenges of technical writing. Yes, this makes pointing
6498/// out problems with specific arguments quite awkward. It's still
6499/// better than generating twenty screens of text for every failed
6500/// overload.
6501///
6502/// It would be great to be able to express per-candidate problems
6503/// more richly for those diagnostic clients that cared, but we'd
6504/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006505void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6506 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006507 FunctionDecl *Fn = Cand->Function;
6508
John McCall12f97bc2010-01-08 04:41:39 +00006509 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00006510 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006511 std::string FnDesc;
6512 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006513
6514 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006515 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00006516 return;
John McCall12f97bc2010-01-08 04:41:39 +00006517 }
6518
John McCalle1ac8d12010-01-13 00:25:19 +00006519 // We don't really have anything else to say about viable candidates.
6520 if (Cand->Viable) {
6521 S.NoteOverloadCandidate(Fn);
6522 return;
6523 }
John McCall0d1da222010-01-12 00:44:57 +00006524
John McCall6a61b522010-01-13 09:16:55 +00006525 switch (Cand->FailureKind) {
6526 case ovl_fail_too_many_arguments:
6527 case ovl_fail_too_few_arguments:
6528 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006529
John McCall6a61b522010-01-13 09:16:55 +00006530 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006531 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6532
John McCallfe796dd2010-01-23 05:17:32 +00006533 case ovl_fail_trivial_conversion:
6534 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006535 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006536 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006537
John McCall65eb8792010-02-25 01:37:24 +00006538 case ovl_fail_bad_conversion: {
6539 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6540 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006541 if (Cand->Conversions[I].isBad())
6542 return DiagnoseBadConversion(S, Cand, I);
6543
6544 // FIXME: this currently happens when we're called from SemaInit
6545 // when user-conversion overload fails. Figure out how to handle
6546 // those conditions and diagnose them well.
6547 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006548 }
John McCall65eb8792010-02-25 01:37:24 +00006549 }
John McCalld3224162010-01-08 00:58:21 +00006550}
6551
6552void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6553 // Desugar the type of the surrogate down to a function type,
6554 // retaining as many typedefs as possible while still showing
6555 // the function type (and, therefore, its parameter types).
6556 QualType FnType = Cand->Surrogate->getConversionType();
6557 bool isLValueReference = false;
6558 bool isRValueReference = false;
6559 bool isPointer = false;
6560 if (const LValueReferenceType *FnTypeRef =
6561 FnType->getAs<LValueReferenceType>()) {
6562 FnType = FnTypeRef->getPointeeType();
6563 isLValueReference = true;
6564 } else if (const RValueReferenceType *FnTypeRef =
6565 FnType->getAs<RValueReferenceType>()) {
6566 FnType = FnTypeRef->getPointeeType();
6567 isRValueReference = true;
6568 }
6569 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6570 FnType = FnTypePtr->getPointeeType();
6571 isPointer = true;
6572 }
6573 // Desugar down to a function type.
6574 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6575 // Reconstruct the pointer/reference as appropriate.
6576 if (isPointer) FnType = S.Context.getPointerType(FnType);
6577 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6578 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6579
6580 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6581 << FnType;
6582}
6583
6584void NoteBuiltinOperatorCandidate(Sema &S,
6585 const char *Opc,
6586 SourceLocation OpLoc,
6587 OverloadCandidate *Cand) {
6588 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6589 std::string TypeStr("operator");
6590 TypeStr += Opc;
6591 TypeStr += "(";
6592 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6593 if (Cand->Conversions.size() == 1) {
6594 TypeStr += ")";
6595 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6596 } else {
6597 TypeStr += ", ";
6598 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6599 TypeStr += ")";
6600 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6601 }
6602}
6603
6604void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6605 OverloadCandidate *Cand) {
6606 unsigned NoOperands = Cand->Conversions.size();
6607 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6608 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006609 if (ICS.isBad()) break; // all meaningless after first invalid
6610 if (!ICS.isAmbiguous()) continue;
6611
John McCall5c32be02010-08-24 20:38:10 +00006612 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006613 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006614 }
6615}
6616
John McCall3712d9e2010-01-15 23:32:50 +00006617SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6618 if (Cand->Function)
6619 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006620 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006621 return Cand->Surrogate->getLocation();
6622 return SourceLocation();
6623}
6624
John McCallad2587a2010-01-12 00:48:53 +00006625struct CompareOverloadCandidatesForDisplay {
6626 Sema &S;
6627 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006628
6629 bool operator()(const OverloadCandidate *L,
6630 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006631 // Fast-path this check.
6632 if (L == R) return false;
6633
John McCall12f97bc2010-01-08 04:41:39 +00006634 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006635 if (L->Viable) {
6636 if (!R->Viable) return true;
6637
6638 // TODO: introduce a tri-valued comparison for overload
6639 // candidates. Would be more worthwhile if we had a sort
6640 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006641 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6642 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006643 } else if (R->Viable)
6644 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006645
John McCall3712d9e2010-01-15 23:32:50 +00006646 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006647
John McCall3712d9e2010-01-15 23:32:50 +00006648 // Criteria by which we can sort non-viable candidates:
6649 if (!L->Viable) {
6650 // 1. Arity mismatches come after other candidates.
6651 if (L->FailureKind == ovl_fail_too_many_arguments ||
6652 L->FailureKind == ovl_fail_too_few_arguments)
6653 return false;
6654 if (R->FailureKind == ovl_fail_too_many_arguments ||
6655 R->FailureKind == ovl_fail_too_few_arguments)
6656 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006657
John McCallfe796dd2010-01-23 05:17:32 +00006658 // 2. Bad conversions come first and are ordered by the number
6659 // of bad conversions and quality of good conversions.
6660 if (L->FailureKind == ovl_fail_bad_conversion) {
6661 if (R->FailureKind != ovl_fail_bad_conversion)
6662 return true;
6663
6664 // If there's any ordering between the defined conversions...
6665 // FIXME: this might not be transitive.
6666 assert(L->Conversions.size() == R->Conversions.size());
6667
6668 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006669 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6670 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006671 switch (CompareImplicitConversionSequences(S,
6672 L->Conversions[I],
6673 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006674 case ImplicitConversionSequence::Better:
6675 leftBetter++;
6676 break;
6677
6678 case ImplicitConversionSequence::Worse:
6679 leftBetter--;
6680 break;
6681
6682 case ImplicitConversionSequence::Indistinguishable:
6683 break;
6684 }
6685 }
6686 if (leftBetter > 0) return true;
6687 if (leftBetter < 0) return false;
6688
6689 } else if (R->FailureKind == ovl_fail_bad_conversion)
6690 return false;
6691
John McCall3712d9e2010-01-15 23:32:50 +00006692 // TODO: others?
6693 }
6694
6695 // Sort everything else by location.
6696 SourceLocation LLoc = GetLocationForCandidate(L);
6697 SourceLocation RLoc = GetLocationForCandidate(R);
6698
6699 // Put candidates without locations (e.g. builtins) at the end.
6700 if (LLoc.isInvalid()) return false;
6701 if (RLoc.isInvalid()) return true;
6702
6703 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006704 }
6705};
6706
John McCallfe796dd2010-01-23 05:17:32 +00006707/// CompleteNonViableCandidate - Normally, overload resolution only
6708/// computes up to the first
6709void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6710 Expr **Args, unsigned NumArgs) {
6711 assert(!Cand->Viable);
6712
6713 // Don't do anything on failures other than bad conversion.
6714 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6715
6716 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006717 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006718 unsigned ConvCount = Cand->Conversions.size();
6719 while (true) {
6720 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6721 ConvIdx++;
6722 if (Cand->Conversions[ConvIdx - 1].isBad())
6723 break;
6724 }
6725
6726 if (ConvIdx == ConvCount)
6727 return;
6728
John McCall65eb8792010-02-25 01:37:24 +00006729 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6730 "remaining conversion is initialized?");
6731
Douglas Gregoradc7a702010-04-16 17:45:54 +00006732 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006733 // operation somehow.
6734 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006735
6736 const FunctionProtoType* Proto;
6737 unsigned ArgIdx = ConvIdx;
6738
6739 if (Cand->IsSurrogate) {
6740 QualType ConvType
6741 = Cand->Surrogate->getConversionType().getNonReferenceType();
6742 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6743 ConvType = ConvPtrType->getPointeeType();
6744 Proto = ConvType->getAs<FunctionProtoType>();
6745 ArgIdx--;
6746 } else if (Cand->Function) {
6747 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6748 if (isa<CXXMethodDecl>(Cand->Function) &&
6749 !isa<CXXConstructorDecl>(Cand->Function))
6750 ArgIdx--;
6751 } else {
6752 // Builtin binary operator with a bad first conversion.
6753 assert(ConvCount <= 3);
6754 for (; ConvIdx != ConvCount; ++ConvIdx)
6755 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006756 = TryCopyInitialization(S, Args[ConvIdx],
6757 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6758 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006759 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006760 return;
6761 }
6762
6763 // Fill in the rest of the conversions.
6764 unsigned NumArgsInProto = Proto->getNumArgs();
6765 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6766 if (ArgIdx < NumArgsInProto)
6767 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006768 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6769 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006770 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006771 else
6772 Cand->Conversions[ConvIdx].setEllipsis();
6773 }
6774}
6775
John McCalld3224162010-01-08 00:58:21 +00006776} // end anonymous namespace
6777
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006778/// PrintOverloadCandidates - When overload resolution fails, prints
6779/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006780/// set.
John McCall5c32be02010-08-24 20:38:10 +00006781void OverloadCandidateSet::NoteCandidates(Sema &S,
6782 OverloadCandidateDisplayKind OCD,
6783 Expr **Args, unsigned NumArgs,
6784 const char *Opc,
6785 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006786 // Sort the candidates by viability and position. Sorting directly would
6787 // be prohibitive, so we make a set of pointers and sort those.
6788 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00006789 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6790 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00006791 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006792 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006793 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00006794 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006795 if (Cand->Function || Cand->IsSurrogate)
6796 Cands.push_back(Cand);
6797 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6798 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006799 }
6800 }
6801
John McCallad2587a2010-01-12 00:48:53 +00006802 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00006803 CompareOverloadCandidatesForDisplay(S));
John McCall12f97bc2010-01-08 04:41:39 +00006804
John McCall0d1da222010-01-12 00:44:57 +00006805 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006806
John McCall12f97bc2010-01-08 04:41:39 +00006807 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00006808 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006809 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006810 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6811 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006812
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006813 // Set an arbitrary limit on the number of candidate functions we'll spam
6814 // the user with. FIXME: This limit should depend on details of the
6815 // candidate list.
6816 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6817 break;
6818 }
6819 ++CandsShown;
6820
John McCalld3224162010-01-08 00:58:21 +00006821 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00006822 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006823 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00006824 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006825 else {
6826 assert(Cand->Viable &&
6827 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006828 // Generally we only see ambiguities including viable builtin
6829 // operators if overload resolution got screwed up by an
6830 // ambiguous user-defined conversion.
6831 //
6832 // FIXME: It's quite possible for different conversions to see
6833 // different ambiguities, though.
6834 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00006835 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00006836 ReportedAmbiguousConversions = true;
6837 }
John McCalld3224162010-01-08 00:58:21 +00006838
John McCall0d1da222010-01-12 00:44:57 +00006839 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00006840 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006841 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006842 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006843
6844 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00006845 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006846}
6847
John McCalla0296f72010-03-19 07:35:19 +00006848static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006849 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006850 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006851
John McCalla0296f72010-03-19 07:35:19 +00006852 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006853}
6854
Douglas Gregorcd695e52008-11-10 20:40:00 +00006855/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6856/// an overloaded function (C++ [over.over]), where @p From is an
6857/// expression with overloaded function type and @p ToType is the type
6858/// we're trying to resolve to. For example:
6859///
6860/// @code
6861/// int f(double);
6862/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006863///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006864/// int (*pfd)(double) = f; // selects f(double)
6865/// @endcode
6866///
6867/// This routine returns the resulting FunctionDecl if it could be
6868/// resolved, and NULL otherwise. When @p Complain is true, this
6869/// routine will emit diagnostics if there is an error.
6870FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006871Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006872 bool Complain,
6873 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006874 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006875 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006876 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006877 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006878 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006879 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006880 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006881 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006882 FunctionType = MemTypePtr->getPointeeType();
6883 IsMember = true;
6884 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006885
Douglas Gregorcd695e52008-11-10 20:40:00 +00006886 // C++ [over.over]p1:
6887 // [...] [Note: any redundant set of parentheses surrounding the
6888 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006889 // C++ [over.over]p1:
6890 // [...] The overloaded function name can be preceded by the &
6891 // operator.
John McCall7d460512010-08-24 23:26:21 +00006892 // However, remember whether the expression has member-pointer form:
6893 // C++ [expr.unary.op]p4:
6894 // A pointer to member is only formed when an explicit & is used
6895 // and its operand is a qualified-id not enclosed in
6896 // parentheses.
John McCall8d08b9b2010-08-27 09:08:28 +00006897 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6898 OverloadExpr *OvlExpr = Ovl.Expression;
John McCall7d460512010-08-24 23:26:21 +00006899
Douglas Gregor064fdb22010-04-14 23:11:21 +00006900 // We expect a pointer or reference to function, or a function pointer.
6901 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6902 if (!FunctionType->isFunctionType()) {
6903 if (Complain)
6904 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6905 << OvlExpr->getName() << ToType;
6906
6907 return 0;
6908 }
6909
John McCall24d18942010-08-24 22:52:39 +00006910 // If the overload expression doesn't have the form of a pointer to
John McCall7d460512010-08-24 23:26:21 +00006911 // member, don't try to convert it to a pointer-to-member type.
John McCall8d08b9b2010-08-27 09:08:28 +00006912 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCall24d18942010-08-24 22:52:39 +00006913 if (!Complain) return 0;
6914
6915 // TODO: Should we condition this on whether any functions might
6916 // have matched, or is it more appropriate to do that in callers?
6917 // TODO: a fixit wouldn't hurt.
6918 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6919 << ToType << OvlExpr->getSourceRange();
6920 return 0;
6921 }
6922
6923 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6924 if (OvlExpr->hasExplicitTemplateArgs()) {
6925 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6926 ExplicitTemplateArgs = &ETABuffer;
6927 }
6928
Douglas Gregor064fdb22010-04-14 23:11:21 +00006929 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006930
Douglas Gregorcd695e52008-11-10 20:40:00 +00006931 // Look through all of the overloaded functions, searching for one
6932 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006933 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006934 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006935
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006936 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006937 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6938 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006939 // Look through any using declarations to find the underlying function.
6940 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6941
Douglas Gregorcd695e52008-11-10 20:40:00 +00006942 // C++ [over.over]p3:
6943 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006944 // targets of type "pointer-to-function" or "reference-to-function."
6945 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006946 // type "pointer-to-member-function."
6947 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006948
Mike Stump11289f42009-09-09 15:08:12 +00006949 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006950 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006951 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006952 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006953 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006954 // static when converting to member pointer.
6955 if (Method->isStatic() == IsMember)
6956 continue;
6957 } else if (IsMember)
6958 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006959
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006960 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006961 // If the name is a function template, template argument deduction is
6962 // done (14.8.2.2), and if the argument deduction succeeds, the
6963 // resulting template argument list is used to generate a single
6964 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006965 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00006966 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006967 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006968 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006969 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006970 FunctionType, Specialization, Info)) {
6971 // FIXME: make a note of the failed deduction for diagnostics.
6972 (void)Result;
6973 } else {
Douglas Gregor4ed49f32010-09-29 21:14:36 +00006974 // Template argument deduction ensures that we have an exact match.
6975 // This function template specicalization works.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006976 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006977 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006978 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006979 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor9b146582009-07-08 20:55:45 +00006980 }
John McCalld14a8642009-11-21 08:51:07 +00006981
6982 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006983 }
Mike Stump11289f42009-09-09 15:08:12 +00006984
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006985 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006986 // Skip non-static functions when converting to pointer, and static
6987 // when converting to member pointer.
6988 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006989 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006990
6991 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006992 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006993 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006994 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006995 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006996
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006997 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006998 QualType ResultTy;
6999 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
7000 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
7001 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00007002 Matches.push_back(std::make_pair(I.getPair(),
7003 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007004 FoundNonTemplateFunction = true;
7005 }
Mike Stump11289f42009-09-09 15:08:12 +00007006 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00007007 }
7008
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007009 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00007010 if (Matches.empty()) {
7011 if (Complain) {
7012 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
7013 << OvlExpr->getName() << FunctionType;
7014 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7015 E = OvlExpr->decls_end();
7016 I != E; ++I)
7017 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
7018 NoteOverloadCandidate(F);
7019 }
7020
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007021 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00007022 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00007023 FunctionDecl *Result = Matches[0].second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007024 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007025 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007026 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00007027 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007028 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007029 return Result;
7030 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007031
7032 // C++ [over.over]p4:
7033 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00007034 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007035 // [...] and any given function template specialization F1 is
7036 // eliminated if the set contains a second function template
7037 // specialization whose function template is more specialized
7038 // than the function template of F1 according to the partial
7039 // ordering rules of 14.5.5.2.
7040
7041 // The algorithm specified above is quadratic. We instead use a
7042 // two-pass algorithm (similar to the one used to identify the
7043 // best viable function in an overload set) that identifies the
7044 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00007045
7046 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7047 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7048 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00007049
7050 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00007051 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00007052 TPOC_Other, 0, From->getLocStart(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007053 PDiag(),
7054 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00007055 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00007056 PDiag(diag::note_ovl_candidate)
7057 << (unsigned) oc_function_template);
Douglas Gregorbdd7b232010-09-12 08:16:09 +00007058 if (Result == MatchesCopy.end())
7059 return 0;
7060
John McCall58cc69d2010-01-27 01:50:18 +00007061 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00007062 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007063 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00007064 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00007065 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007066 }
Mike Stump11289f42009-09-09 15:08:12 +00007067
Douglas Gregorfae1d712009-09-26 03:56:17 +00007068 // [...] any function template specializations in the set are
7069 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00007070 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00007071 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00007072 ++I;
7073 else {
John McCalla0296f72010-03-19 07:35:19 +00007074 Matches[I] = Matches[--N];
7075 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00007076 }
7077 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00007078
Mike Stump11289f42009-09-09 15:08:12 +00007079 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007080 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00007081 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00007082 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00007083 FoundResult = Matches[0].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007084 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00007085 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
7086 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007087 }
Mike Stump11289f42009-09-09 15:08:12 +00007088
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007089 // FIXME: We should probably return the same thing that BestViableFunction
7090 // returns (even if we issue the diagnostics here).
Douglas Gregore81f58e2010-11-08 03:40:48 +00007091 if (Complain) {
7092 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
7093 << Matches[0].second->getDeclName();
7094 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7095 NoteOverloadCandidate(Matches[I].second);
7096 }
7097
Douglas Gregorcd695e52008-11-10 20:40:00 +00007098 return 0;
7099}
7100
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007101/// \brief Given an expression that refers to an overloaded function, try to
7102/// resolve that overloaded function expression down to a single function.
7103///
7104/// This routine can only resolve template-ids that refer to a single function
7105/// template, where that template-id refers to a single template whose template
7106/// arguments are either provided by the template-id or have defaults,
7107/// as described in C++0x [temp.arg.explicit]p3.
7108FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
7109 // C++ [over.over]p1:
7110 // [...] [Note: any redundant set of parentheses surrounding the
7111 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007112 // C++ [over.over]p1:
7113 // [...] The overloaded function name can be preceded by the &
7114 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00007115
7116 if (From->getType() != Context.OverloadTy)
7117 return 0;
7118
John McCall8d08b9b2010-08-27 09:08:28 +00007119 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007120
7121 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00007122 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007123 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007124
7125 TemplateArgumentListInfo ExplicitTemplateArgs;
7126 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007127
7128 // Look through all of the overloaded functions, searching for one
7129 // whose type matches exactly.
7130 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00007131 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7132 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007133 // C++0x [temp.arg.explicit]p3:
7134 // [...] In contexts where deduction is done and fails, or in contexts
7135 // where deduction is not done, if a template argument list is
7136 // specified and it, along with any default template arguments,
7137 // identifies a single function template specialization, then the
7138 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00007139 FunctionTemplateDecl *FunctionTemplate
7140 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007141
7142 // C++ [over.over]p2:
7143 // If the name is a function template, template argument deduction is
7144 // done (14.8.2.2), and if the argument deduction succeeds, the
7145 // resulting template argument list is used to generate a single
7146 // function template specialization, which is added to the set of
7147 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007148 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00007149 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007150 if (TemplateDeductionResult Result
7151 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7152 Specialization, Info)) {
7153 // FIXME: make a note of the failed deduction for diagnostics.
7154 (void)Result;
7155 continue;
7156 }
7157
7158 // Multiple matches; we can't resolve to a single declaration.
7159 if (Matched)
7160 return 0;
7161
7162 Matched = Specialization;
7163 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007164
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007165 return Matched;
7166}
7167
Douglas Gregorcabea402009-09-22 15:41:20 +00007168/// \brief Add a single candidate to the overload set.
7169static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00007170 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00007171 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007172 Expr **Args, unsigned NumArgs,
7173 OverloadCandidateSet &CandidateSet,
7174 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00007175 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00007176 if (isa<UsingShadowDecl>(Callee))
7177 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7178
Douglas Gregorcabea402009-09-22 15:41:20 +00007179 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00007180 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00007181 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007182 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007183 return;
John McCalld14a8642009-11-21 08:51:07 +00007184 }
7185
7186 if (FunctionTemplateDecl *FuncTemplate
7187 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00007188 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7189 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007190 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00007191 return;
7192 }
7193
7194 assert(false && "unhandled case in overloaded call candidate");
7195
7196 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00007197}
7198
7199/// \brief Add the overload candidates named by callee and/or found by argument
7200/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00007201void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00007202 Expr **Args, unsigned NumArgs,
7203 OverloadCandidateSet &CandidateSet,
7204 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00007205
7206#ifndef NDEBUG
7207 // Verify that ArgumentDependentLookup is consistent with the rules
7208 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00007209 //
Douglas Gregorcabea402009-09-22 15:41:20 +00007210 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7211 // and let Y be the lookup set produced by argument dependent
7212 // lookup (defined as follows). If X contains
7213 //
7214 // -- a declaration of a class member, or
7215 //
7216 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00007217 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00007218 //
7219 // -- a declaration that is neither a function or a function
7220 // template
7221 //
7222 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00007223
John McCall57500772009-12-16 12:17:52 +00007224 if (ULE->requiresADL()) {
7225 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7226 E = ULE->decls_end(); I != E; ++I) {
7227 assert(!(*I)->getDeclContext()->isRecord());
7228 assert(isa<UsingShadowDecl>(*I) ||
7229 !(*I)->getDeclContext()->isFunctionOrMethod());
7230 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00007231 }
7232 }
7233#endif
7234
John McCall57500772009-12-16 12:17:52 +00007235 // It would be nice to avoid this copy.
7236 TemplateArgumentListInfo TABuffer;
7237 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7238 if (ULE->hasExplicitTemplateArgs()) {
7239 ULE->copyTemplateArgumentsInto(TABuffer);
7240 ExplicitTemplateArgs = &TABuffer;
7241 }
7242
7243 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7244 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00007245 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007246 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00007247 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00007248
John McCall57500772009-12-16 12:17:52 +00007249 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00007250 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7251 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007252 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007253 CandidateSet,
7254 PartialOverloading);
7255}
John McCalld681c392009-12-16 08:11:27 +00007256
7257/// Attempts to recover from a call where no functions were found.
7258///
7259/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00007260static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007261BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00007262 UnresolvedLookupExpr *ULE,
7263 SourceLocation LParenLoc,
7264 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007265 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00007266
7267 CXXScopeSpec SS;
7268 if (ULE->getQualifier()) {
7269 SS.setScopeRep(ULE->getQualifier());
7270 SS.setRange(ULE->getQualifierRange());
7271 }
7272
John McCall57500772009-12-16 12:17:52 +00007273 TemplateArgumentListInfo TABuffer;
7274 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7275 if (ULE->hasExplicitTemplateArgs()) {
7276 ULE->copyTemplateArgumentsInto(TABuffer);
7277 ExplicitTemplateArgs = &TABuffer;
7278 }
7279
John McCalld681c392009-12-16 08:11:27 +00007280 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7281 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00007282 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00007283 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00007284
John McCall57500772009-12-16 12:17:52 +00007285 assert(!R.empty() && "lookup results empty despite recovery");
7286
7287 // Build an implicit member call if appropriate. Just drop the
7288 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00007289 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00007290 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00007291 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7292 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00007293 else if (ExplicitTemplateArgs)
7294 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7295 else
7296 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7297
7298 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007299 return ExprError();
John McCall57500772009-12-16 12:17:52 +00007300
7301 // This shouldn't cause an infinite loop because we're giving it
7302 // an expression with non-empty lookup results, which should never
7303 // end up here.
John McCallb268a282010-08-23 23:25:46 +00007304 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007305 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007306}
Douglas Gregor4038cf42010-06-08 17:35:15 +00007307
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007308/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00007309/// (which eventually refers to the declaration Func) and the call
7310/// arguments Args/NumArgs, attempt to resolve the function call down
7311/// to a specific function. If overload resolution succeeds, returns
7312/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00007313/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007314/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00007315ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007316Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00007317 SourceLocation LParenLoc,
7318 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007319 SourceLocation RParenLoc) {
7320#ifndef NDEBUG
7321 if (ULE->requiresADL()) {
7322 // To do ADL, we must have found an unqualified name.
7323 assert(!ULE->getQualifier() && "qualified name with ADL");
7324
7325 // We don't perform ADL for implicit declarations of builtins.
7326 // Verify that this was correctly set up.
7327 FunctionDecl *F;
7328 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7329 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7330 F->getBuiltinID() && F->isImplicit())
7331 assert(0 && "performing ADL for builtin");
7332
7333 // We don't perform ADL in C.
7334 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7335 }
7336#endif
7337
John McCallbc077cf2010-02-08 23:07:23 +00007338 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00007339
John McCall57500772009-12-16 12:17:52 +00007340 // Add the functions denoted by the callee to the set of candidate
7341 // functions, including those from argument-dependent lookup.
7342 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00007343
7344 // If we found nothing, try to recover.
7345 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7346 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00007347 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007348 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007349 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007350
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007351 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007352 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00007353 case OR_Success: {
7354 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00007355 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007356 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7357 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00007358 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007359 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
7360 RParenLoc);
John McCall57500772009-12-16 12:17:52 +00007361 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007362
7363 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00007364 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007365 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00007366 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007367 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007368 break;
7369
7370 case OR_Ambiguous:
7371 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007372 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007373 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007374 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007375
7376 case OR_Deleted:
7377 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7378 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00007379 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00007380 << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007381 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007382 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007383 }
7384
Douglas Gregorb412e172010-07-25 18:17:45 +00007385 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007386 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007387}
7388
John McCall4c4c1df2010-01-26 03:27:55 +00007389static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007390 return Functions.size() > 1 ||
7391 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7392}
7393
Douglas Gregor084d8552009-03-13 23:49:33 +00007394/// \brief Create a unary operation that may resolve to an overloaded
7395/// operator.
7396///
7397/// \param OpLoc The location of the operator itself (e.g., '*').
7398///
7399/// \param OpcIn The UnaryOperator::Opcode that describes this
7400/// operator.
7401///
7402/// \param Functions The set of non-member functions that will be
7403/// considered by overload resolution. The caller needs to build this
7404/// set based on the context using, e.g.,
7405/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7406/// set should not contain any member functions; those will be added
7407/// by CreateOverloadedUnaryOp().
7408///
7409/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007410ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007411Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7412 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007413 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007414 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007415
7416 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7417 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7418 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007419 // TODO: provide better source location info.
7420 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007421
John McCalle26a8722010-12-04 08:14:53 +00007422 if (Input->getObjectKind() == OK_ObjCProperty)
7423 ConvertPropertyForRValue(Input);
7424
Douglas Gregor084d8552009-03-13 23:49:33 +00007425 Expr *Args[2] = { Input, 0 };
7426 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007427
Douglas Gregor084d8552009-03-13 23:49:33 +00007428 // For post-increment and post-decrement, add the implicit '0' as
7429 // the second argument, so that we know this is a post-increment or
7430 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007431 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007432 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007433 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7434 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007435 NumArgs = 2;
7436 }
7437
7438 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007439 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007440 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor630dec52010-06-17 15:46:20 +00007441 Opc,
7442 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007443 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00007444 OpLoc));
7445
John McCall58cc69d2010-01-27 01:50:18 +00007446 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007447 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007448 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007449 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007450 /*ADL*/ true, IsOverloaded(Fns),
7451 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007452 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7453 &Args[0], NumArgs,
7454 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007455 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00007456 OpLoc));
7457 }
7458
7459 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007460 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007461
7462 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007463 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00007464
7465 // Add operator candidates that are member functions.
7466 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7467
John McCall4c4c1df2010-01-26 03:27:55 +00007468 // Add candidates from ADL.
7469 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007470 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007471 /*ExplicitTemplateArgs*/ 0,
7472 CandidateSet);
7473
Douglas Gregor084d8552009-03-13 23:49:33 +00007474 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007475 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007476
7477 // Perform overload resolution.
7478 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007479 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007480 case OR_Success: {
7481 // We found a built-in operator or an overloaded operator.
7482 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007483
Douglas Gregor084d8552009-03-13 23:49:33 +00007484 if (FnDecl) {
7485 // We matched an overloaded operator. Build a call to that
7486 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007487
Douglas Gregor084d8552009-03-13 23:49:33 +00007488 // Convert the arguments.
7489 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007490 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007491
John McCall16df1e52010-03-30 21:47:33 +00007492 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7493 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00007494 return ExprError();
7495 } else {
7496 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007497 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007498 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007499 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007500 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00007501 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007502 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007503 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007504 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007505 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007506 }
7507
John McCall4fa0d5f2010-05-06 18:15:07 +00007508 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7509
John McCall7decc9e2010-11-18 06:31:45 +00007510 // Determine the result type.
7511 QualType ResultTy = FnDecl->getResultType();
7512 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7513 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00007514
Douglas Gregor084d8552009-03-13 23:49:33 +00007515 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007516 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007517
Eli Friedman030eee42009-11-18 03:58:17 +00007518 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007519 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007520 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007521 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007522
John McCallb268a282010-08-23 23:25:46 +00007523 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007524 FnDecl))
7525 return ExprError();
7526
John McCallb268a282010-08-23 23:25:46 +00007527 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007528 } else {
7529 // We matched a built-in operator. Convert the arguments, then
7530 // break out so that we will build the appropriate built-in
7531 // operator node.
7532 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007533 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00007534 return ExprError();
7535
7536 break;
7537 }
7538 }
7539
7540 case OR_No_Viable_Function:
7541 // No viable function; fall through to handling this as a
7542 // built-in operator, which will produce an error message for us.
7543 break;
7544
7545 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007546 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregor084d8552009-03-13 23:49:33 +00007547 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007548 << Input->getType()
Douglas Gregor084d8552009-03-13 23:49:33 +00007549 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007550 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7551 Args, NumArgs,
7552 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007553 return ExprError();
7554
7555 case OR_Deleted:
7556 Diag(OpLoc, diag::err_ovl_deleted_oper)
7557 << Best->Function->isDeleted()
7558 << UnaryOperator::getOpcodeStr(Opc)
7559 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007560 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00007561 return ExprError();
7562 }
7563
7564 // Either we found no viable overloaded operator or we matched a
7565 // built-in operator. In either case, fall through to trying to
7566 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00007567 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007568}
7569
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007570/// \brief Create a binary operation that may resolve to an overloaded
7571/// operator.
7572///
7573/// \param OpLoc The location of the operator itself (e.g., '+').
7574///
7575/// \param OpcIn The BinaryOperator::Opcode that describes this
7576/// operator.
7577///
7578/// \param Functions The set of non-member functions that will be
7579/// considered by overload resolution. The caller needs to build this
7580/// set based on the context using, e.g.,
7581/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7582/// set should not contain any member functions; those will be added
7583/// by CreateOverloadedBinOp().
7584///
7585/// \param LHS Left-hand argument.
7586/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00007587ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007588Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007589 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00007590 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007591 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007592 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00007593 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007594
7595 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7596 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7597 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7598
7599 // If either side is type-dependent, create an appropriate dependent
7600 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00007601 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00007602 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00007603 // If there are no functions to store, just build a dependent
7604 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00007605 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00007606 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00007607 Context.DependentTy,
7608 VK_RValue, OK_Ordinary,
7609 OpLoc));
Douglas Gregor5287f092009-11-05 00:51:44 +00007610
7611 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7612 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007613 VK_LValue,
7614 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00007615 Context.DependentTy,
7616 Context.DependentTy,
7617 OpLoc));
7618 }
John McCall4c4c1df2010-01-26 03:27:55 +00007619
7620 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00007621 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007622 // TODO: provide better source location info in DNLoc component.
7623 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00007624 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007625 = UnresolvedLookupExpr::Create(Context, NamingClass, 0, SourceRange(),
7626 OpNameInfo, /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007627 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007628 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00007629 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007630 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007631 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007632 OpLoc));
7633 }
7634
John McCalle26a8722010-12-04 08:14:53 +00007635 // Always do property rvalue conversions on the RHS.
7636 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7637 ConvertPropertyForRValue(Args[1]);
7638
7639 // The LHS is more complicated.
7640 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
7641
7642 // There's a tension for assignment operators between primitive
7643 // property assignment and the overloaded operators.
7644 if (BinaryOperator::isAssignmentOp(Opc)) {
7645 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7646
7647 // Is the property "logically" settable?
7648 bool Settable = (PRE->isExplicitProperty() ||
7649 PRE->getImplicitPropertySetter());
7650
7651 // To avoid gratuitously inventing semantics, use the primitive
7652 // unless it isn't. Thoughts in case we ever really care:
7653 // - If the property isn't logically settable, we have to
7654 // load and hope.
7655 // - If the property is settable and this is simple assignment,
7656 // we really should use the primitive.
7657 // - If the property is settable, then we could try overloading
7658 // on a generic lvalue of the appropriate type; if it works
7659 // out to a builtin candidate, we would do that same operation
7660 // on the property, and otherwise just error.
7661 if (Settable)
7662 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7663 }
7664
7665 ConvertPropertyForRValue(Args[0]);
7666 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007667
Sebastian Redl6a96bf72009-11-18 23:10:33 +00007668 // If this is the assignment operator, we only perform overload resolution
7669 // if the left-hand side is a class or enumeration type. This is actually
7670 // a hack. The standard requires that we do overload resolution between the
7671 // various built-in candidates, but as DR507 points out, this can lead to
7672 // problems. So we do it this way, which pretty much follows what GCC does.
7673 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00007674 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00007675 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007676
John McCalle26a8722010-12-04 08:14:53 +00007677 // If this is the .* operator, which is not overloadable, just
7678 // create a built-in binary operator.
7679 if (Opc == BO_PtrMemD)
7680 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7681
Douglas Gregor084d8552009-03-13 23:49:33 +00007682 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007683 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007684
7685 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007686 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007687
7688 // Add operator candidates that are member functions.
7689 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7690
John McCall4c4c1df2010-01-26 03:27:55 +00007691 // Add candidates from ADL.
7692 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7693 Args, 2,
7694 /*ExplicitTemplateArgs*/ 0,
7695 CandidateSet);
7696
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007697 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007698 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007699
7700 // Perform overload resolution.
7701 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007702 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00007703 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007704 // We found a built-in operator or an overloaded operator.
7705 FunctionDecl *FnDecl = Best->Function;
7706
7707 if (FnDecl) {
7708 // We matched an overloaded operator. Build a call to that
7709 // operator.
7710
7711 // Convert the arguments.
7712 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00007713 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00007714 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007715
Chandler Carruth8e543b32010-12-12 08:17:55 +00007716 ExprResult Arg1 =
7717 PerformCopyInitialization(
7718 InitializedEntity::InitializeParameter(Context,
7719 FnDecl->getParamDecl(0)),
7720 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007721 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007722 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007723
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007724 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007725 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007726 return ExprError();
7727
7728 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007729 } else {
7730 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00007731 ExprResult Arg0 = PerformCopyInitialization(
7732 InitializedEntity::InitializeParameter(Context,
7733 FnDecl->getParamDecl(0)),
7734 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007735 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007736 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007737
Chandler Carruth8e543b32010-12-12 08:17:55 +00007738 ExprResult Arg1 =
7739 PerformCopyInitialization(
7740 InitializedEntity::InitializeParameter(Context,
7741 FnDecl->getParamDecl(1)),
7742 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007743 if (Arg1.isInvalid())
7744 return ExprError();
7745 Args[0] = LHS = Arg0.takeAs<Expr>();
7746 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007747 }
7748
John McCall4fa0d5f2010-05-06 18:15:07 +00007749 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7750
John McCall7decc9e2010-11-18 06:31:45 +00007751 // Determine the result type.
7752 QualType ResultTy = FnDecl->getResultType();
7753 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7754 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007755
7756 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007757 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007758
John McCallb268a282010-08-23 23:25:46 +00007759 CXXOperatorCallExpr *TheCall =
7760 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007761 Args, 2, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007762
John McCallb268a282010-08-23 23:25:46 +00007763 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007764 FnDecl))
7765 return ExprError();
7766
John McCallb268a282010-08-23 23:25:46 +00007767 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007768 } else {
7769 // We matched a built-in operator. Convert the arguments, then
7770 // break out so that we will build the appropriate built-in
7771 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00007772 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007773 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00007774 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007775 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007776 return ExprError();
7777
7778 break;
7779 }
7780 }
7781
Douglas Gregor66950a32009-09-30 21:46:01 +00007782 case OR_No_Viable_Function: {
7783 // C++ [over.match.oper]p9:
7784 // If the operator is the operator , [...] and there are no
7785 // viable functions, then the operator is assumed to be the
7786 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00007787 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00007788 break;
7789
Chandler Carruth8e543b32010-12-12 08:17:55 +00007790 // For class as left operand for assignment or compound assigment
7791 // operator do not fall through to handling in built-in, but report that
7792 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00007793 ExprResult Result = ExprError();
Douglas Gregor66950a32009-09-30 21:46:01 +00007794 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00007795 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007796 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7797 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007798 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007799 } else {
7800 // No viable function; try to create a built-in operation, which will
7801 // produce an error. Then, show the non-viable candidates.
7802 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007803 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007804 assert(Result.isInvalid() &&
7805 "C++ binary operator overloading is missing candidates!");
7806 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00007807 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7808 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007809 return move(Result);
7810 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007811
7812 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007813 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007814 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007815 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00007816 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007817 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7818 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007819 return ExprError();
7820
7821 case OR_Deleted:
7822 Diag(OpLoc, diag::err_ovl_deleted_oper)
7823 << Best->Function->isDeleted()
7824 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007825 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007826 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007827 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007828 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007829
Douglas Gregor66950a32009-09-30 21:46:01 +00007830 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007831 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007832}
7833
John McCalldadc5752010-08-24 06:29:42 +00007834ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00007835Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7836 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007837 Expr *Base, Expr *Idx) {
7838 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007839 DeclarationName OpName =
7840 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7841
7842 // If either side is type-dependent, create an appropriate dependent
7843 // expression.
7844 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7845
John McCall58cc69d2010-01-27 01:50:18 +00007846 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007847 // CHECKME: no 'operator' keyword?
7848 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7849 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007850 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007851 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007852 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007853 /*ADL*/ true, /*Overloaded*/ false,
7854 UnresolvedSetIterator(),
7855 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007856 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007857
Sebastian Redladba46e2009-10-29 20:17:01 +00007858 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7859 Args, 2,
7860 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007861 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00007862 RLoc));
7863 }
7864
John McCalle26a8722010-12-04 08:14:53 +00007865 if (Args[0]->getObjectKind() == OK_ObjCProperty)
7866 ConvertPropertyForRValue(Args[0]);
7867 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7868 ConvertPropertyForRValue(Args[1]);
7869
Sebastian Redladba46e2009-10-29 20:17:01 +00007870 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007871 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007872
7873 // Subscript can only be overloaded as a member function.
7874
7875 // Add operator candidates that are member functions.
7876 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7877
7878 // Add builtin operator candidates.
7879 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7880
7881 // Perform overload resolution.
7882 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007883 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00007884 case OR_Success: {
7885 // We found a built-in operator or an overloaded operator.
7886 FunctionDecl *FnDecl = Best->Function;
7887
7888 if (FnDecl) {
7889 // We matched an overloaded operator. Build a call to that
7890 // operator.
7891
John McCalla0296f72010-03-19 07:35:19 +00007892 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007893 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007894
Sebastian Redladba46e2009-10-29 20:17:01 +00007895 // Convert the arguments.
7896 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007897 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007898 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007899 return ExprError();
7900
Anders Carlssona68e51e2010-01-29 18:37:50 +00007901 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007902 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00007903 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007904 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00007905 FnDecl->getParamDecl(0)),
7906 SourceLocation(),
7907 Owned(Args[1]));
7908 if (InputInit.isInvalid())
7909 return ExprError();
7910
7911 Args[1] = InputInit.takeAs<Expr>();
7912
Sebastian Redladba46e2009-10-29 20:17:01 +00007913 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00007914 QualType ResultTy = FnDecl->getResultType();
7915 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7916 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007917
7918 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007919 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007920
John McCallb268a282010-08-23 23:25:46 +00007921 CXXOperatorCallExpr *TheCall =
7922 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7923 FnExpr, Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00007924 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007925
John McCallb268a282010-08-23 23:25:46 +00007926 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00007927 FnDecl))
7928 return ExprError();
7929
John McCallb268a282010-08-23 23:25:46 +00007930 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00007931 } else {
7932 // We matched a built-in operator. Convert the arguments, then
7933 // break out so that we will build the appropriate built-in
7934 // operator node.
7935 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007936 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007937 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007938 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007939 return ExprError();
7940
7941 break;
7942 }
7943 }
7944
7945 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007946 if (CandidateSet.empty())
7947 Diag(LLoc, diag::err_ovl_no_oper)
7948 << Args[0]->getType() << /*subscript*/ 0
7949 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7950 else
7951 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7952 << Args[0]->getType()
7953 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007954 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7955 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00007956 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007957 }
7958
7959 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007960 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
7961 << "[]"
7962 << Args[0]->getType() << Args[1]->getType()
7963 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007964 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7965 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007966 return ExprError();
7967
7968 case OR_Deleted:
7969 Diag(LLoc, diag::err_ovl_deleted_oper)
7970 << Best->Function->isDeleted() << "[]"
7971 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007972 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7973 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007974 return ExprError();
7975 }
7976
7977 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00007978 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007979}
7980
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007981/// BuildCallToMemberFunction - Build a call to a member
7982/// function. MemExpr is the expression that refers to the member
7983/// function (and includes the object parameter), Args/NumArgs are the
7984/// arguments to the function call (not including the object
7985/// parameter). The caller needs to validate that the member
7986/// expression refers to a member function or an overloaded member
7987/// function.
John McCalldadc5752010-08-24 06:29:42 +00007988ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007989Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7990 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007991 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007992 // Dig out the member expression. This holds both the object
7993 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007994 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7995
John McCall10eae182009-11-30 22:42:35 +00007996 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007997 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007998 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007999 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00008000 if (isa<MemberExpr>(NakedMemExpr)) {
8001 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00008002 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00008003 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008004 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00008005 } else {
8006 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008007 Qualifier = UnresExpr->getQualifier();
8008
John McCall6e9f8f62009-12-03 04:06:58 +00008009 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00008010 Expr::Classification ObjectClassification
8011 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
8012 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00008013
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008014 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00008015 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00008016
John McCall2d74de92009-12-01 22:10:20 +00008017 // FIXME: avoid copy.
8018 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8019 if (UnresExpr->hasExplicitTemplateArgs()) {
8020 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8021 TemplateArgs = &TemplateArgsBuffer;
8022 }
8023
John McCall10eae182009-11-30 22:42:35 +00008024 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
8025 E = UnresExpr->decls_end(); I != E; ++I) {
8026
John McCall6e9f8f62009-12-03 04:06:58 +00008027 NamedDecl *Func = *I;
8028 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
8029 if (isa<UsingShadowDecl>(Func))
8030 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
8031
Douglas Gregor02824322011-01-26 19:30:28 +00008032
Francois Pichet64225792011-01-18 05:04:39 +00008033 // Microsoft supports direct constructor calls.
8034 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
8035 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
8036 CandidateSet);
8037 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00008038 // If explicit template arguments were provided, we can't call a
8039 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00008040 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00008041 continue;
8042
John McCalla0296f72010-03-19 07:35:19 +00008043 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00008044 ObjectClassification,
8045 Args, NumArgs, CandidateSet,
8046 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008047 } else {
John McCall10eae182009-11-30 22:42:35 +00008048 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00008049 I.getPair(), ActingDC, TemplateArgs,
Douglas Gregor02824322011-01-26 19:30:28 +00008050 ObjectType, ObjectClassification,
8051 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008052 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008053 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008054 }
Mike Stump11289f42009-09-09 15:08:12 +00008055
John McCall10eae182009-11-30 22:42:35 +00008056 DeclarationName DeclName = UnresExpr->getMemberName();
8057
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008058 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008059 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00008060 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008061 case OR_Success:
8062 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008063 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00008064 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008065 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008066 break;
8067
8068 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00008069 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008070 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008071 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008072 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008073 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008074 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008075
8076 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00008077 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008078 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008079 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008080 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008081 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008082
8083 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00008084 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00008085 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00008086 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008087 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008088 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008089 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008090 }
8091
John McCall16df1e52010-03-30 21:47:33 +00008092 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00008093
John McCall2d74de92009-12-01 22:10:20 +00008094 // If overload resolution picked a static member, build a
8095 // non-member call based on that function.
8096 if (Method->isStatic()) {
8097 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8098 Args, NumArgs, RParenLoc);
8099 }
8100
John McCall10eae182009-11-30 22:42:35 +00008101 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008102 }
8103
John McCall7decc9e2010-11-18 06:31:45 +00008104 QualType ResultType = Method->getResultType();
8105 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8106 ResultType = ResultType.getNonLValueExprType(Context);
8107
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008108 assert(Method && "Member call to something that isn't a method?");
John McCallb268a282010-08-23 23:25:46 +00008109 CXXMemberCallExpr *TheCall =
8110 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008111 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008112
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008113 // Check for a valid return type.
8114 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00008115 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00008116 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008117
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008118 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00008119 // We only need to do this if there was actually an overload; otherwise
8120 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00008121 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00008122 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00008123 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
8124 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00008125 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008126 MemExpr->setBase(ObjectArg);
8127
8128 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00008129 const FunctionProtoType *Proto =
8130 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00008131 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008132 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00008133 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008134
John McCallb268a282010-08-23 23:25:46 +00008135 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00008136 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00008137
John McCallb268a282010-08-23 23:25:46 +00008138 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008139}
8140
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008141/// BuildCallToObjectOfClassType - Build a call to an object of class
8142/// type (C++ [over.call.object]), which can end up invoking an
8143/// overloaded function call operator (@c operator()) or performing a
8144/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00008145ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008146Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00008147 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008148 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008149 SourceLocation RParenLoc) {
John McCalle26a8722010-12-04 08:14:53 +00008150 if (Object->getObjectKind() == OK_ObjCProperty)
8151 ConvertPropertyForRValue(Object);
8152
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008153 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008154 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00008155
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008156 // C++ [over.call.object]p1:
8157 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00008158 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008159 // candidate functions includes at least the function call
8160 // operators of T. The function call operators of T are obtained by
8161 // ordinary lookup of the name operator() in the context of
8162 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00008163 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00008164 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008165
8166 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00008167 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008168 << Object->getSourceRange()))
8169 return true;
8170
John McCall27b18f82009-11-17 02:14:36 +00008171 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8172 LookupQualifiedName(R, Record->getDecl());
8173 R.suppressDiagnostics();
8174
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008175 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00008176 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008177 AddMethodCandidate(Oper.getPair(), Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00008178 Object->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00008179 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00008180 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008181
Douglas Gregorab7897a2008-11-19 22:57:39 +00008182 // C++ [over.call.object]p2:
8183 // In addition, for each conversion function declared in T of the
8184 // form
8185 //
8186 // operator conversion-type-id () cv-qualifier;
8187 //
8188 // where cv-qualifier is the same cv-qualification as, or a
8189 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00008190 // denotes the type "pointer to function of (P1,...,Pn) returning
8191 // R", or the type "reference to pointer to function of
8192 // (P1,...,Pn) returning R", or the type "reference to function
8193 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00008194 // is also considered as a candidate function. Similarly,
8195 // surrogate call functions are added to the set of candidate
8196 // functions for each conversion function declared in an
8197 // accessible base class provided the function is not hidden
8198 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00008199 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00008200 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00008201 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00008202 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00008203 NamedDecl *D = *I;
8204 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8205 if (isa<UsingShadowDecl>(D))
8206 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8207
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008208 // Skip over templated conversion functions; they aren't
8209 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00008210 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008211 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00008212
John McCall6e9f8f62009-12-03 04:06:58 +00008213 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00008214
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008215 // Strip the reference type (if any) and then the pointer type (if
8216 // any) to get down to what might be a function type.
8217 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8218 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8219 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00008220
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008221 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00008222 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00008223 Object, Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008224 }
Mike Stump11289f42009-09-09 15:08:12 +00008225
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008226 // Perform overload resolution.
8227 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008228 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
8229 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008230 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00008231 // Overload resolution succeeded; we'll build the appropriate call
8232 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008233 break;
8234
8235 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00008236 if (CandidateSet.empty())
8237 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8238 << Object->getType() << /*call*/ 1
8239 << Object->getSourceRange();
8240 else
8241 Diag(Object->getSourceRange().getBegin(),
8242 diag::err_ovl_no_viable_object_call)
8243 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008244 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008245 break;
8246
8247 case OR_Ambiguous:
8248 Diag(Object->getSourceRange().getBegin(),
8249 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008250 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008251 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008252 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008253
8254 case OR_Deleted:
8255 Diag(Object->getSourceRange().getBegin(),
8256 diag::err_ovl_deleted_object_call)
8257 << Best->Function->isDeleted()
8258 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008259 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008260 break;
Mike Stump11289f42009-09-09 15:08:12 +00008261 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008262
Douglas Gregorb412e172010-07-25 18:17:45 +00008263 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008264 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008265
Douglas Gregorab7897a2008-11-19 22:57:39 +00008266 if (Best->Function == 0) {
8267 // Since there is no function declaration, this is one of the
8268 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00008269 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00008270 = cast<CXXConversionDecl>(
8271 Best->Conversions[0].UserDefined.ConversionFunction);
8272
John McCalla0296f72010-03-19 07:35:19 +00008273 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008274 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008275
Douglas Gregorab7897a2008-11-19 22:57:39 +00008276 // We selected one of the surrogate functions that converts the
8277 // object parameter to a function pointer. Perform the conversion
8278 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00008279
8280 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00008281 // and then call it.
Douglas Gregor668443e2011-01-20 00:18:04 +00008282 ExprResult Call = BuildCXXMemberCallExpr(Object, Best->FoundDecl, Conv);
8283 if (Call.isInvalid())
8284 return ExprError();
8285
8286 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008287 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008288 }
8289
John McCalla0296f72010-03-19 07:35:19 +00008290 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008291 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008292
Douglas Gregorab7897a2008-11-19 22:57:39 +00008293 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8294 // that calls this method, using Object for the implicit object
8295 // parameter and passing along the remaining arguments.
8296 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008297 const FunctionProtoType *Proto =
8298 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008299
8300 unsigned NumArgsInProto = Proto->getNumArgs();
8301 unsigned NumArgsToCheck = NumArgs;
8302
8303 // Build the full argument list for the method call (the
8304 // implicit object parameter is placed at the beginning of the
8305 // list).
8306 Expr **MethodArgs;
8307 if (NumArgs < NumArgsInProto) {
8308 NumArgsToCheck = NumArgsInProto;
8309 MethodArgs = new Expr*[NumArgsInProto + 1];
8310 } else {
8311 MethodArgs = new Expr*[NumArgs + 1];
8312 }
8313 MethodArgs[0] = Object;
8314 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8315 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00008316
John McCall7decc9e2010-11-18 06:31:45 +00008317 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008318
8319 // Once we've built TheCall, all of the expressions are properly
8320 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00008321 QualType ResultTy = Method->getResultType();
8322 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8323 ResultTy = ResultTy.getNonLValueExprType(Context);
8324
John McCallb268a282010-08-23 23:25:46 +00008325 CXXOperatorCallExpr *TheCall =
8326 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
8327 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00008328 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008329 delete [] MethodArgs;
8330
John McCallb268a282010-08-23 23:25:46 +00008331 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00008332 Method))
8333 return true;
8334
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008335 // We may have default arguments. If so, we need to allocate more
8336 // slots in the call for them.
8337 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00008338 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008339 else if (NumArgs > NumArgsInProto)
8340 NumArgsToCheck = NumArgsInProto;
8341
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008342 bool IsError = false;
8343
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008344 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008345 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008346 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008347 TheCall->setArg(0, Object);
8348
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008349
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008350 // Check the argument types.
8351 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008352 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008353 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008354 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00008355
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008356 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008357
John McCalldadc5752010-08-24 06:29:42 +00008358 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008359 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008360 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008361 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00008362 SourceLocation(), Arg);
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008363
8364 IsError |= InputInit.isInvalid();
8365 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008366 } else {
John McCalldadc5752010-08-24 06:29:42 +00008367 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008368 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8369 if (DefArg.isInvalid()) {
8370 IsError = true;
8371 break;
8372 }
8373
8374 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008375 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008376
8377 TheCall->setArg(i + 1, Arg);
8378 }
8379
8380 // If this is a variadic call, handle args passed through "...".
8381 if (Proto->isVariadic()) {
8382 // Promote the arguments (C99 6.5.2.2p7).
8383 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8384 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00008385 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008386 TheCall->setArg(i + 1, Arg);
8387 }
8388 }
8389
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008390 if (IsError) return true;
8391
John McCallb268a282010-08-23 23:25:46 +00008392 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00008393 return true;
8394
John McCalle172be52010-08-24 06:09:16 +00008395 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008396}
8397
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008398/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00008399/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008400/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00008401ExprResult
John McCallb268a282010-08-23 23:25:46 +00008402Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008403 assert(Base->getType()->isRecordType() &&
8404 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00008405
John McCalle26a8722010-12-04 08:14:53 +00008406 if (Base->getObjectKind() == OK_ObjCProperty)
8407 ConvertPropertyForRValue(Base);
8408
John McCallbc077cf2010-02-08 23:07:23 +00008409 SourceLocation Loc = Base->getExprLoc();
8410
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008411 // C++ [over.ref]p1:
8412 //
8413 // [...] An expression x->m is interpreted as (x.operator->())->m
8414 // for a class object x of type T if T::operator->() exists and if
8415 // the operator is selected as the best match function by the
8416 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00008417 DeclarationName OpName =
8418 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00008419 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008420 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00008421
John McCallbc077cf2010-02-08 23:07:23 +00008422 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00008423 PDiag(diag::err_typecheck_incomplete_tag)
8424 << Base->getSourceRange()))
8425 return ExprError();
8426
John McCall27b18f82009-11-17 02:14:36 +00008427 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8428 LookupQualifiedName(R, BaseRecord->getDecl());
8429 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00008430
8431 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00008432 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00008433 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
8434 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00008435 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008436
8437 // Perform overload resolution.
8438 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008439 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008440 case OR_Success:
8441 // Overload resolution succeeded; we'll build the call below.
8442 break;
8443
8444 case OR_No_Viable_Function:
8445 if (CandidateSet.empty())
8446 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00008447 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008448 else
8449 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00008450 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008451 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008452 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008453
8454 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008455 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8456 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008457 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008458 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008459
8460 case OR_Deleted:
8461 Diag(OpLoc, diag::err_ovl_deleted_oper)
8462 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00008463 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008464 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008465 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008466 }
8467
John McCalla0296f72010-03-19 07:35:19 +00008468 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008469 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00008470
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008471 // Convert the object parameter.
8472 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008473 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8474 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00008475 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00008476
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008477 // Build the operator call.
John McCall7decc9e2010-11-18 06:31:45 +00008478 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008479
John McCall7decc9e2010-11-18 06:31:45 +00008480 QualType ResultTy = Method->getResultType();
8481 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8482 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00008483 CXXOperatorCallExpr *TheCall =
8484 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008485 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008486
John McCallb268a282010-08-23 23:25:46 +00008487 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008488 Method))
8489 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008490 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008491}
8492
Douglas Gregorcd695e52008-11-10 20:40:00 +00008493/// FixOverloadedFunctionReference - E is an expression that refers to
8494/// a C++ overloaded function (possibly with some parentheses and
8495/// perhaps a '&' around it). We have resolved the overloaded function
8496/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008497/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00008498Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00008499 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00008500 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008501 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8502 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008503 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008504 return PE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008505
8506 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8507 }
8508
8509 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008510 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8511 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00008512 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008513 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00008514 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00008515 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00008516 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008517 return ICE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008518
John McCallcf142162010-08-07 06:22:56 +00008519 return ImplicitCastExpr::Create(Context, ICE->getType(),
8520 ICE->getCastKind(),
8521 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00008522 ICE->getValueKind());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008523 }
8524
8525 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00008526 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00008527 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008528 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8529 if (Method->isStatic()) {
8530 // Do nothing: static member functions aren't any different
8531 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00008532 } else {
John McCalle66edc12009-11-24 19:00:30 +00008533 // Fix the sub expression, which really has to be an
8534 // UnresolvedLookupExpr holding an overloaded member function
8535 // or template.
John McCall16df1e52010-03-30 21:47:33 +00008536 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8537 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00008538 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008539 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008540
John McCalld14a8642009-11-21 08:51:07 +00008541 assert(isa<DeclRefExpr>(SubExpr)
8542 && "fixed to something other than a decl ref");
8543 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8544 && "fixed to a member ref with no nested name qualifier");
8545
8546 // We have taken the address of a pointer to member
8547 // function. Perform the computation here so that we get the
8548 // appropriate pointer to member type.
8549 QualType ClassType
8550 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8551 QualType MemPtrType
8552 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8553
John McCall7decc9e2010-11-18 06:31:45 +00008554 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8555 VK_RValue, OK_Ordinary,
8556 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008557 }
8558 }
John McCall16df1e52010-03-30 21:47:33 +00008559 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8560 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008561 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008562 return UnOp;
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008563
John McCalle3027922010-08-25 11:45:40 +00008564 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008565 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00008566 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008567 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008568 }
John McCalld14a8642009-11-21 08:51:07 +00008569
8570 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00008571 // FIXME: avoid copy.
8572 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00008573 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00008574 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8575 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00008576 }
8577
John McCalld14a8642009-11-21 08:51:07 +00008578 return DeclRefExpr::Create(Context,
8579 ULE->getQualifier(),
8580 ULE->getQualifierRange(),
8581 Fn,
8582 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00008583 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008584 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008585 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00008586 }
8587
John McCall10eae182009-11-30 22:42:35 +00008588 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00008589 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00008590 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8591 if (MemExpr->hasExplicitTemplateArgs()) {
8592 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8593 TemplateArgs = &TemplateArgsBuffer;
8594 }
John McCall6b51f282009-11-23 01:53:49 +00008595
John McCall2d74de92009-12-01 22:10:20 +00008596 Expr *Base;
8597
John McCall7decc9e2010-11-18 06:31:45 +00008598 // If we're filling in a static method where we used to have an
8599 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00008600 if (MemExpr->isImplicitAccess()) {
8601 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8602 return DeclRefExpr::Create(Context,
8603 MemExpr->getQualifier(),
8604 MemExpr->getQualifierRange(),
8605 Fn,
8606 MemExpr->getMemberLoc(),
8607 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008608 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008609 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00008610 } else {
8611 SourceLocation Loc = MemExpr->getMemberLoc();
8612 if (MemExpr->getQualifier())
8613 Loc = MemExpr->getQualifierRange().getBegin();
8614 Base = new (Context) CXXThisExpr(Loc,
8615 MemExpr->getBaseType(),
8616 /*isImplicit=*/true);
8617 }
John McCall2d74de92009-12-01 22:10:20 +00008618 } else
John McCallc3007a22010-10-26 07:05:15 +00008619 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00008620
8621 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008622 MemExpr->isArrow(),
8623 MemExpr->getQualifier(),
8624 MemExpr->getQualifierRange(),
8625 Fn,
John McCall16df1e52010-03-30 21:47:33 +00008626 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008627 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00008628 TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008629 Fn->getType(),
8630 cast<CXXMethodDecl>(Fn)->isStatic()
8631 ? VK_LValue : VK_RValue,
8632 OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008633 }
8634
John McCallc3007a22010-10-26 07:05:15 +00008635 llvm_unreachable("Invalid reference to overloaded function");
8636 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008637}
8638
John McCalldadc5752010-08-24 06:29:42 +00008639ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8640 DeclAccessPair Found,
8641 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00008642 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008643}
8644
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008645} // end namespace clang