blob: b6045123fe2189f4982e1d47ce5467c04be01325 [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.
John Wiegley01296292011-04-08 18:41:53 +000039static ExprResult
John McCall7decc9e2010-11-18 06:31:45 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41 SourceLocation Loc = SourceLocation()) {
John Wiegley01296292011-04-08 18:41:53 +000042 ExprResult E = S.Owned(new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc));
43 E = S.DefaultFunctionArrayConversion(E.take());
44 if (E.isInvalid())
45 return ExprError();
46 return move(E);
John McCall7decc9e2010-11-18 06:31:45 +000047}
48
John McCall5c32be02010-08-24 20:38:10 +000049static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
50 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000051 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000052 bool CStyle,
53 bool AllowObjCWritebackConversion);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000054
55static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
56 QualType &ToType,
57 bool InOverloadResolution,
58 StandardConversionSequence &SCS,
59 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000060static OverloadingResult
61IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
62 UserDefinedConversionSequence& User,
63 OverloadCandidateSet& Conversions,
64 bool AllowExplicit);
65
66
67static ImplicitConversionSequence::CompareKind
68CompareStandardConversionSequences(Sema &S,
69 const StandardConversionSequence& SCS1,
70 const StandardConversionSequence& SCS2);
71
72static ImplicitConversionSequence::CompareKind
73CompareQualificationConversions(Sema &S,
74 const StandardConversionSequence& SCS1,
75 const StandardConversionSequence& SCS2);
76
77static ImplicitConversionSequence::CompareKind
78CompareDerivedToBaseConversions(Sema &S,
79 const StandardConversionSequence& SCS1,
80 const StandardConversionSequence& SCS2);
81
82
83
Douglas Gregor5251f1b2008-10-21 16:13:35 +000084/// GetConversionCategory - Retrieve the implicit conversion
85/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000086ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000087GetConversionCategory(ImplicitConversionKind Kind) {
88 static const ImplicitConversionCategory
89 Category[(int)ICK_Num_Conversion_Kinds] = {
90 ICC_Identity,
91 ICC_Lvalue_Transformation,
92 ICC_Lvalue_Transformation,
93 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000094 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000095 ICC_Qualification_Adjustment,
96 ICC_Promotion,
97 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000098 ICC_Promotion,
99 ICC_Conversion,
100 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 ICC_Conversion,
102 ICC_Conversion,
103 ICC_Conversion,
104 ICC_Conversion,
105 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000106 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000107 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000108 ICC_Conversion,
109 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000110 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000111 ICC_Conversion
112 };
113 return Category[(int)Kind];
114}
115
116/// GetConversionRank - Retrieve the implicit conversion rank
117/// corresponding to the given implicit conversion kind.
118ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
119 static const ImplicitConversionRank
120 Rank[(int)ICK_Num_Conversion_Kinds] = {
121 ICR_Exact_Match,
122 ICR_Exact_Match,
123 ICR_Exact_Match,
124 ICR_Exact_Match,
125 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000126 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000127 ICR_Promotion,
128 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000129 ICR_Promotion,
130 ICR_Conversion,
131 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_Conversion,
135 ICR_Conversion,
136 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000137 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000138 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000139 ICR_Conversion,
140 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000141 ICR_Complex_Real_Conversion,
142 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000143 ICR_Conversion,
144 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145 };
146 return Rank[(int)Kind];
147}
148
149/// GetImplicitConversionName - Return the name of this kind of
150/// implicit conversion.
151const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000152 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 "No conversion",
154 "Lvalue-to-rvalue",
155 "Array-to-pointer",
156 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000157 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000158 "Qualification",
159 "Integral promotion",
160 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000161 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000162 "Integral conversion",
163 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000164 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000165 "Floating-integral conversion",
166 "Pointer conversion",
167 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000168 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000169 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000170 "Derived-to-base conversion",
171 "Vector conversion",
172 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000173 "Complex-real conversion",
174 "Block Pointer conversion",
175 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000176 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000177 };
178 return Name[Kind];
179}
180
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000181/// StandardConversionSequence - Set the standard conversion
182/// sequence to the identity conversion.
183void StandardConversionSequence::setAsIdentityConversion() {
184 First = ICK_Identity;
185 Second = ICK_Identity;
186 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000187 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000188 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000189 ReferenceBinding = false;
190 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000191 IsLvalueReference = true;
192 BindsToFunctionLvalue = false;
193 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000194 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000195 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000196 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000197}
198
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000199/// getRank - Retrieve the rank of this standard conversion sequence
200/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
201/// implicit conversions.
202ImplicitConversionRank StandardConversionSequence::getRank() const {
203 ImplicitConversionRank Rank = ICR_Exact_Match;
204 if (GetConversionRank(First) > Rank)
205 Rank = GetConversionRank(First);
206 if (GetConversionRank(Second) > Rank)
207 Rank = GetConversionRank(Second);
208 if (GetConversionRank(Third) > Rank)
209 Rank = GetConversionRank(Third);
210 return Rank;
211}
212
213/// isPointerConversionToBool - Determines whether this conversion is
214/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000215/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000216/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000217bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218 // Note that FromType has not necessarily been transformed by the
219 // array-to-pointer or function-to-pointer implicit conversions, so
220 // check for their presence as well as checking whether FromType is
221 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000222 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000223 (getFromType()->isPointerType() ||
224 getFromType()->isObjCObjectPointerType() ||
225 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000226 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000227 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
228 return true;
229
230 return false;
231}
232
Douglas Gregor5c407d92008-10-23 00:40:37 +0000233/// isPointerConversionToVoidPointer - Determines whether this
234/// conversion is a conversion of a pointer to a void pointer. This is
235/// used as part of the ranking of standard conversion sequences (C++
236/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000237bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000238StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000239isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000240 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000241 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000242
243 // Note that FromType has not necessarily been transformed by the
244 // array-to-pointer implicit conversion, so check for its presence
245 // and redo the conversion to get a pointer.
246 if (First == ICK_Array_To_Pointer)
247 FromType = Context.getArrayDecayedType(FromType);
248
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000249 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000250 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000251 return ToPtrType->getPointeeType()->isVoidType();
252
253 return false;
254}
255
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000256/// DebugPrint - Print this standard conversion sequence to standard
257/// error. Useful for debugging overloading issues.
258void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000259 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000260 bool PrintedSomething = false;
261 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000262 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000263 PrintedSomething = true;
264 }
265
266 if (Second != ICK_Identity) {
267 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000268 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000269 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000270 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000271
272 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000273 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000274 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000275 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000276 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000277 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000278 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000279 PrintedSomething = true;
280 }
281
282 if (Third != ICK_Identity) {
283 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000284 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000285 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000286 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000287 PrintedSomething = true;
288 }
289
290 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000291 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000292 }
293}
294
295/// DebugPrint - Print this user-defined conversion sequence to standard
296/// error. Useful for debugging overloading issues.
297void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000298 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000299 if (Before.First || Before.Second || Before.Third) {
300 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000301 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000302 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000303 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000304 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000305 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000306 After.DebugPrint();
307 }
308}
309
310/// DebugPrint - Print this implicit conversion sequence to standard
311/// error. Useful for debugging overloading issues.
312void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000313 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000314 switch (ConversionKind) {
315 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000316 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000317 Standard.DebugPrint();
318 break;
319 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000320 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000321 UserDefined.DebugPrint();
322 break;
323 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000324 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000325 break;
John McCall0d1da222010-01-12 00:44:57 +0000326 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000327 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000328 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000329 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000330 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000331 break;
332 }
333
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000334 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000335}
336
John McCall0d1da222010-01-12 00:44:57 +0000337void AmbiguousConversionSequence::construct() {
338 new (&conversions()) ConversionSet();
339}
340
341void AmbiguousConversionSequence::destruct() {
342 conversions().~ConversionSet();
343}
344
345void
346AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
347 FromTypePtr = O.FromTypePtr;
348 ToTypePtr = O.ToTypePtr;
349 new (&conversions()) ConversionSet(O.conversions());
350}
351
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000352namespace {
353 // Structure used by OverloadCandidate::DeductionFailureInfo to store
354 // template parameter and template argument information.
355 struct DFIParamWithArguments {
356 TemplateParameter Param;
357 TemplateArgument FirstArg;
358 TemplateArgument SecondArg;
359 };
360}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000361
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000362/// \brief Convert from Sema's representation of template deduction information
363/// to the form used in overload-candidate information.
364OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000365static MakeDeductionFailureInfo(ASTContext &Context,
366 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000367 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000368 OverloadCandidate::DeductionFailureInfo Result;
369 Result.Result = static_cast<unsigned>(TDK);
370 Result.Data = 0;
371 switch (TDK) {
372 case Sema::TDK_Success:
373 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000374 case Sema::TDK_TooManyArguments:
375 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000376 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000377
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000378 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000379 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000380 Result.Data = Info.Param.getOpaqueValue();
381 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000382
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000383 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000384 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000385 // FIXME: Should allocate from normal heap so that we can free this later.
386 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000387 Saved->Param = Info.Param;
388 Saved->FirstArg = Info.FirstArg;
389 Saved->SecondArg = Info.SecondArg;
390 Result.Data = Saved;
391 break;
392 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000393
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000394 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000395 Result.Data = Info.take();
396 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000397
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000398 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000399 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000400 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000401 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000402
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000403 return Result;
404}
John McCall0d1da222010-01-12 00:44:57 +0000405
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000406void OverloadCandidate::DeductionFailureInfo::Destroy() {
407 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
408 case Sema::TDK_Success:
409 case Sema::TDK_InstantiationDepth:
410 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000411 case Sema::TDK_TooManyArguments:
412 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000413 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000414 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000415
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000416 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000417 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000418 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000419 Data = 0;
420 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000421
422 case Sema::TDK_SubstitutionFailure:
423 // FIXME: Destroy the template arugment list?
424 Data = 0;
425 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000426
Douglas Gregor461761d2010-05-08 18:20:53 +0000427 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000428 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000429 case Sema::TDK_FailedOverloadResolution:
430 break;
431 }
432}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000433
434TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000435OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
436 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
437 case Sema::TDK_Success:
438 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000439 case Sema::TDK_TooManyArguments:
440 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000441 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000442 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000443
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000444 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000445 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000446 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000447
448 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000449 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000450 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000451
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000452 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000453 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000454 case Sema::TDK_FailedOverloadResolution:
455 break;
456 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000457
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000458 return TemplateParameter();
459}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000460
Douglas Gregord09efd42010-05-08 20:07:26 +0000461TemplateArgumentList *
462OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
463 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
464 case Sema::TDK_Success:
465 case Sema::TDK_InstantiationDepth:
466 case Sema::TDK_TooManyArguments:
467 case Sema::TDK_TooFewArguments:
468 case Sema::TDK_Incomplete:
469 case Sema::TDK_InvalidExplicitArguments:
470 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000471 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000472 return 0;
473
474 case Sema::TDK_SubstitutionFailure:
475 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000476
Douglas Gregord09efd42010-05-08 20:07:26 +0000477 // Unhandled
478 case Sema::TDK_NonDeducedMismatch:
479 case Sema::TDK_FailedOverloadResolution:
480 break;
481 }
482
483 return 0;
484}
485
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000486const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
487 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
488 case Sema::TDK_Success:
489 case Sema::TDK_InstantiationDepth:
490 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000491 case Sema::TDK_TooManyArguments:
492 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000493 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000494 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000495 return 0;
496
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000497 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000498 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000499 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000500
Douglas Gregor461761d2010-05-08 18:20:53 +0000501 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000502 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000503 case Sema::TDK_FailedOverloadResolution:
504 break;
505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000506
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000507 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000508}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000509
510const TemplateArgument *
511OverloadCandidate::DeductionFailureInfo::getSecondArg() {
512 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
513 case Sema::TDK_Success:
514 case Sema::TDK_InstantiationDepth:
515 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000516 case Sema::TDK_TooManyArguments:
517 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000518 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000519 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000520 return 0;
521
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000522 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000523 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000524 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
525
Douglas Gregor461761d2010-05-08 18:20:53 +0000526 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000527 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000528 case Sema::TDK_FailedOverloadResolution:
529 break;
530 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000531
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000532 return 0;
533}
534
535void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000536 inherited::clear();
537 Functions.clear();
538}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000539
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000540// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000541// overload of the declarations in Old. This routine returns false if
542// New and Old cannot be overloaded, e.g., if New has the same
543// signature as some function in Old (C++ 1.3.10) or if the Old
544// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000545// it does return false, MatchedDecl will point to the decl that New
546// cannot be overloaded with. This decl may be a UsingShadowDecl on
547// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000548//
549// Example: Given the following input:
550//
551// void f(int, float); // #1
552// void f(int, int); // #2
553// int f(int, int); // #3
554//
555// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000556// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000557//
John McCall3d988d92009-12-02 08:47:38 +0000558// When we process #2, Old contains only the FunctionDecl for #1. By
559// comparing the parameter types, we see that #1 and #2 are overloaded
560// (since they have different signatures), so this routine returns
561// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000562//
John McCall3d988d92009-12-02 08:47:38 +0000563// When we process #3, Old is an overload set containing #1 and #2. We
564// compare the signatures of #3 to #1 (they're overloaded, so we do
565// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
566// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000567// signature), IsOverload returns false and MatchedDecl will be set to
568// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000569//
570// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
571// into a class by a using declaration. The rules for whether to hide
572// shadow declarations ignore some properties which otherwise figure
573// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000574Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000575Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
576 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000577 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000578 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000579 NamedDecl *OldD = *I;
580
581 bool OldIsUsingDecl = false;
582 if (isa<UsingShadowDecl>(OldD)) {
583 OldIsUsingDecl = true;
584
585 // We can always introduce two using declarations into the same
586 // context, even if they have identical signatures.
587 if (NewIsUsingDecl) continue;
588
589 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
590 }
591
592 // If either declaration was introduced by a using declaration,
593 // we'll need to use slightly different rules for matching.
594 // Essentially, these rules are the normal rules, except that
595 // function templates hide function templates with different
596 // return types or template parameter lists.
597 bool UseMemberUsingDeclRules =
598 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
599
John McCall3d988d92009-12-02 08:47:38 +0000600 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000601 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
602 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
603 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
604 continue;
605 }
606
John McCalldaa3d6b2009-12-09 03:35:25 +0000607 Match = *I;
608 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000609 }
John McCall3d988d92009-12-02 08:47:38 +0000610 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000611 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
612 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
613 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
614 continue;
615 }
616
John McCalldaa3d6b2009-12-09 03:35:25 +0000617 Match = *I;
618 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000619 }
John McCalla8987a2942010-11-10 03:01:53 +0000620 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000621 // We can overload with these, which can show up when doing
622 // redeclaration checks for UsingDecls.
623 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000624 } else if (isa<TagDecl>(OldD)) {
625 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000626 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
627 // Optimistically assume that an unresolved using decl will
628 // overload; if it doesn't, we'll have to diagnose during
629 // template instantiation.
630 } else {
John McCall1f82f242009-11-18 22:49:29 +0000631 // (C++ 13p1):
632 // Only function declarations can be overloaded; object and type
633 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000634 Match = *I;
635 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000636 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000637 }
John McCall1f82f242009-11-18 22:49:29 +0000638
John McCalldaa3d6b2009-12-09 03:35:25 +0000639 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000640}
641
John McCalle9cccd82010-06-16 08:42:20 +0000642bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
643 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000644 // If both of the functions are extern "C", then they are not
645 // overloads.
646 if (Old->isExternC() && New->isExternC())
647 return false;
648
John McCall1f82f242009-11-18 22:49:29 +0000649 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
650 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
651
652 // C++ [temp.fct]p2:
653 // A function template can be overloaded with other function templates
654 // and with normal (non-template) functions.
655 if ((OldTemplate == 0) != (NewTemplate == 0))
656 return true;
657
658 // Is the function New an overload of the function Old?
659 QualType OldQType = Context.getCanonicalType(Old->getType());
660 QualType NewQType = Context.getCanonicalType(New->getType());
661
662 // Compare the signatures (C++ 1.3.10) of the two functions to
663 // determine whether they are overloads. If we find any mismatch
664 // in the signature, they are overloads.
665
666 // If either of these functions is a K&R-style function (no
667 // prototype), then we consider them to have matching signatures.
668 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
669 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
670 return false;
671
John McCall424cec92011-01-19 06:33:43 +0000672 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
673 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000674
675 // The signature of a function includes the types of its
676 // parameters (C++ 1.3.10), which includes the presence or absence
677 // of the ellipsis; see C++ DR 357).
678 if (OldQType != NewQType &&
679 (OldType->getNumArgs() != NewType->getNumArgs() ||
680 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000681 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000682 return true;
683
684 // C++ [temp.over.link]p4:
685 // The signature of a function template consists of its function
686 // signature, its return type and its template parameter list. The names
687 // of the template parameters are significant only for establishing the
688 // relationship between the template parameters and the rest of the
689 // signature.
690 //
691 // We check the return type and template parameter lists for function
692 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000693 //
694 // However, we don't consider either of these when deciding whether
695 // a member introduced by a shadow declaration is hidden.
696 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000697 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
698 OldTemplate->getTemplateParameters(),
699 false, TPL_TemplateMatch) ||
700 OldType->getResultType() != NewType->getResultType()))
701 return true;
702
703 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000704 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000705 //
706 // As part of this, also check whether one of the member functions
707 // is static, in which case they are not overloads (C++
708 // 13.1p2). While not part of the definition of the signature,
709 // this check is important to determine whether these functions
710 // can be overloaded.
711 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
712 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
713 if (OldMethod && NewMethod &&
714 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000715 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000716 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
717 if (!UseUsingDeclRules &&
718 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
719 (OldMethod->getRefQualifier() == RQ_None ||
720 NewMethod->getRefQualifier() == RQ_None)) {
721 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000722 // - Member function declarations with the same name and the same
723 // parameter-type-list as well as member function template
724 // declarations with the same name, the same parameter-type-list, and
725 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000726 // them, but not all, have a ref-qualifier (8.3.5).
727 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
728 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
729 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
730 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000731
John McCall1f82f242009-11-18 22:49:29 +0000732 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000733 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000734
John McCall1f82f242009-11-18 22:49:29 +0000735 // The signatures match; this is not an overload.
736 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000737}
738
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +0000739/// \brief Checks availability of the function depending on the current
740/// function context. Inside an unavailable function, unavailability is ignored.
741///
742/// \returns true if \arg FD is unavailable and current context is inside
743/// an available function, false otherwise.
744bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
745 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
746}
747
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000748/// TryImplicitConversion - Attempt to perform an implicit conversion
749/// from the given expression (Expr) to the given type (ToType). This
750/// function returns an implicit conversion sequence that can be used
751/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000752///
753/// void f(float f);
754/// void g(int i) { f(i); }
755///
756/// this routine would produce an implicit conversion sequence to
757/// describe the initialization of f from i, which will be a standard
758/// conversion sequence containing an lvalue-to-rvalue conversion (C++
759/// 4.1) followed by a floating-integral conversion (C++ 4.9).
760//
761/// Note that this routine only determines how the conversion can be
762/// performed; it does not actually perform the conversion. As such,
763/// it will not produce any diagnostics if no conversion is available,
764/// but will instead return an implicit conversion sequence of kind
765/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000766///
767/// If @p SuppressUserConversions, then user-defined conversions are
768/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000769/// If @p AllowExplicit, then explicit user-defined conversions are
770/// permitted.
John McCall31168b02011-06-15 23:02:42 +0000771///
772/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
773/// writeback conversion, which allows __autoreleasing id* parameters to
774/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +0000775static ImplicitConversionSequence
776TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
777 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000778 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000779 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000780 bool CStyle,
781 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000782 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000783 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000784 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +0000785 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000786 return ICS;
787 }
788
John McCall5c32be02010-08-24 20:38:10 +0000789 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000790 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000791 return ICS;
792 }
793
Douglas Gregor836a7e82010-08-11 02:15:33 +0000794 // C++ [over.ics.user]p4:
795 // A conversion of an expression of class type to the same class
796 // type is given Exact Match rank, and a conversion of an
797 // expression of class type to a base class of that type is
798 // given Conversion rank, in spite of the fact that a copy/move
799 // constructor (i.e., a user-defined conversion function) is
800 // called for those cases.
801 QualType FromType = From->getType();
802 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000803 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
804 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000805 ICS.setStandard();
806 ICS.Standard.setAsIdentityConversion();
807 ICS.Standard.setFromType(FromType);
808 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000809
Douglas Gregor5ab11652010-04-17 22:01:05 +0000810 // We don't actually check at this point whether there is a valid
811 // copy/move constructor, since overloading just assumes that it
812 // exists. When we actually perform initialization, we'll find the
813 // appropriate constructor to copy the returned object, if needed.
814 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000815
Douglas Gregor5ab11652010-04-17 22:01:05 +0000816 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000817 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000818 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000819
Douglas Gregor836a7e82010-08-11 02:15:33 +0000820 return ICS;
821 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000822
Douglas Gregor836a7e82010-08-11 02:15:33 +0000823 if (SuppressUserConversions) {
824 // We're not in the case above, so there is no conversion that
825 // we can perform.
826 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000827 return ICS;
828 }
829
830 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000831 OverloadCandidateSet Conversions(From->getExprLoc());
832 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000833 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000834 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000835
836 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000837 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000838 // C++ [over.ics.user]p4:
839 // A conversion of an expression of class type to the same class
840 // type is given Exact Match rank, and a conversion of an
841 // expression of class type to a base class of that type is
842 // given Conversion rank, in spite of the fact that a copy
843 // constructor (i.e., a user-defined conversion function) is
844 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000845 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000846 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000847 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000848 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
849 QualType ToCanon
850 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000851 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000852 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000853 // Turn this into a "standard" conversion sequence, so that it
854 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000855 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000856 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000857 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000858 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000859 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000860 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000861 ICS.Standard.Second = ICK_Derived_To_Base;
862 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000863 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000864
865 // C++ [over.best.ics]p4:
866 // However, when considering the argument of a user-defined
867 // conversion function that is a candidate by 13.3.1.3 when
868 // invoked for the copying of the temporary in the second step
869 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
870 // 13.3.1.6 in all cases, only standard conversion sequences and
871 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000872 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000873 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000874 }
John McCalle8c8cd22010-01-13 22:30:33 +0000875 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000876 ICS.setAmbiguous();
877 ICS.Ambiguous.setFromType(From->getType());
878 ICS.Ambiguous.setToType(ToType);
879 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
880 Cand != Conversions.end(); ++Cand)
881 if (Cand->Viable)
882 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000883 } else {
John McCall65eb8792010-02-25 01:37:24 +0000884 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000885 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000886
887 return ICS;
888}
889
John McCall31168b02011-06-15 23:02:42 +0000890ImplicitConversionSequence
891Sema::TryImplicitConversion(Expr *From, QualType ToType,
892 bool SuppressUserConversions,
893 bool AllowExplicit,
894 bool InOverloadResolution,
895 bool CStyle,
896 bool AllowObjCWritebackConversion) {
897 return clang::TryImplicitConversion(*this, From, ToType,
898 SuppressUserConversions, AllowExplicit,
899 InOverloadResolution, CStyle,
900 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +0000901}
902
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000903/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +0000904/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000905/// converted expression. Flavor is the kind of conversion we're
906/// performing, used in the error message. If @p AllowExplicit,
907/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +0000908ExprResult
909Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000910 AssignmentAction Action, bool AllowExplicit) {
911 ImplicitConversionSequence ICS;
912 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
913}
914
John Wiegley01296292011-04-08 18:41:53 +0000915ExprResult
916Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000917 AssignmentAction Action, bool AllowExplicit,
918 ImplicitConversionSequence& ICS) {
John McCall31168b02011-06-15 23:02:42 +0000919 // Objective-C ARC: Determine whether we will allow the writeback conversion.
920 bool AllowObjCWritebackConversion
921 = getLangOptions().ObjCAutoRefCount &&
922 (Action == AA_Passing || Action == AA_Sending);
923
924
John McCall5c32be02010-08-24 20:38:10 +0000925 ICS = clang::TryImplicitConversion(*this, From, ToType,
926 /*SuppressUserConversions=*/false,
927 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000928 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +0000929 /*CStyle=*/false,
930 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000931 return PerformImplicitConversion(From, ToType, ICS, Action);
932}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000933
934/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000935/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +0000936bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
937 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000938 if (Context.hasSameUnqualifiedType(FromType, ToType))
939 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000940
John McCall991eb4b2010-12-21 00:44:39 +0000941 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
942 // where F adds one of the following at most once:
943 // - a pointer
944 // - a member pointer
945 // - a block pointer
946 CanQualType CanTo = Context.getCanonicalType(ToType);
947 CanQualType CanFrom = Context.getCanonicalType(FromType);
948 Type::TypeClass TyClass = CanTo->getTypeClass();
949 if (TyClass != CanFrom->getTypeClass()) return false;
950 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
951 if (TyClass == Type::Pointer) {
952 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
953 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
954 } else if (TyClass == Type::BlockPointer) {
955 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
956 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
957 } else if (TyClass == Type::MemberPointer) {
958 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
959 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
960 } else {
961 return false;
962 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000963
John McCall991eb4b2010-12-21 00:44:39 +0000964 TyClass = CanTo->getTypeClass();
965 if (TyClass != CanFrom->getTypeClass()) return false;
966 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
967 return false;
968 }
969
970 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
971 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
972 if (!EInfo.getNoReturn()) return false;
973
974 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
975 assert(QualType(FromFn, 0).isCanonical());
976 if (QualType(FromFn, 0) != CanTo) return false;
977
978 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000979 return true;
980}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000981
Douglas Gregor46188682010-05-18 22:42:18 +0000982/// \brief Determine whether the conversion from FromType to ToType is a valid
983/// vector conversion.
984///
985/// \param ICK Will be set to the vector conversion kind, if this is a vector
986/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000987static bool IsVectorConversion(ASTContext &Context, QualType FromType,
988 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +0000989 // We need at least one of these types to be a vector type to have a vector
990 // conversion.
991 if (!ToType->isVectorType() && !FromType->isVectorType())
992 return false;
993
994 // Identical types require no conversions.
995 if (Context.hasSameUnqualifiedType(FromType, ToType))
996 return false;
997
998 // There are no conversions between extended vector types, only identity.
999 if (ToType->isExtVectorType()) {
1000 // There are no conversions between extended vector types other than the
1001 // identity conversion.
1002 if (FromType->isExtVectorType())
1003 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001004
Douglas Gregor46188682010-05-18 22:42:18 +00001005 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001006 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001007 ICK = ICK_Vector_Splat;
1008 return true;
1009 }
1010 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001011
1012 // We can perform the conversion between vector types in the following cases:
1013 // 1)vector types are equivalent AltiVec and GCC vector types
1014 // 2)lax vector conversions are permitted and the vector types are of the
1015 // same size
1016 if (ToType->isVectorType() && FromType->isVectorType()) {
1017 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +00001018 (Context.getLangOptions().LaxVectorConversions &&
1019 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001020 ICK = ICK_Vector_Conversion;
1021 return true;
1022 }
Douglas Gregor46188682010-05-18 22:42:18 +00001023 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001024
Douglas Gregor46188682010-05-18 22:42:18 +00001025 return false;
1026}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001027
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001028/// IsStandardConversion - Determines whether there is a standard
1029/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1030/// expression From to the type ToType. Standard conversion sequences
1031/// only consider non-class types; for conversions that involve class
1032/// types, use TryImplicitConversion. If a conversion exists, SCS will
1033/// contain the standard conversion sequence required to perform this
1034/// conversion and this routine will return true. Otherwise, this
1035/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001036static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1037 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001038 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001039 bool CStyle,
1040 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001041 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001042
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001043 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001044 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001045 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001046 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001047 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001048 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001049
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001050 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001051 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001052 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001053 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001054 return false;
1055
Mike Stump11289f42009-09-09 15:08:12 +00001056 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001057 }
1058
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001059 // The first conversion can be an lvalue-to-rvalue conversion,
1060 // array-to-pointer conversion, or function-to-pointer conversion
1061 // (C++ 4p1).
1062
John McCall5c32be02010-08-24 20:38:10 +00001063 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001064 DeclAccessPair AccessPair;
1065 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001066 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001067 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001068 // We were able to resolve the address of the overloaded function,
1069 // so we can convert to the type of that function.
1070 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001071
1072 // we can sometimes resolve &foo<int> regardless of ToType, so check
1073 // if the type matches (identity) or we are converting to bool
1074 if (!S.Context.hasSameUnqualifiedType(
1075 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1076 QualType resultTy;
1077 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001078 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001079 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1080 // otherwise, only a boolean conversion is standard
1081 if (!ToType->isBooleanType())
1082 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001083 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001084
Chandler Carruthffce2452011-03-29 08:08:18 +00001085 // Check if the "from" expression is taking the address of an overloaded
1086 // function and recompute the FromType accordingly. Take advantage of the
1087 // fact that non-static member functions *must* have such an address-of
1088 // expression.
1089 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1090 if (Method && !Method->isStatic()) {
1091 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1092 "Non-unary operator on non-static member address");
1093 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1094 == UO_AddrOf &&
1095 "Non-address-of operator on non-static member address");
1096 const Type *ClassType
1097 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1098 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001099 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1100 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1101 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001102 "Non-address-of operator for overloaded function expression");
1103 FromType = S.Context.getPointerType(FromType);
1104 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001105
Douglas Gregor980fb162010-04-29 18:24:40 +00001106 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001107 assert(S.Context.hasSameType(
1108 FromType,
1109 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001110 } else {
1111 return false;
1112 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001113 }
Mike Stump11289f42009-09-09 15:08:12 +00001114 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001115 // An lvalue (3.10) of a non-function, non-array type T can be
1116 // converted to an rvalue.
John McCall086a4642010-11-24 05:12:34 +00001117 bool argIsLValue = From->isLValue();
1118 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001119 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001120 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001121 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001122
1123 // If T is a non-class type, the type of the rvalue is the
1124 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001125 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1126 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001127 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001128 } else if (FromType->isArrayType()) {
1129 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001130 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001131
1132 // An lvalue or rvalue of type "array of N T" or "array of unknown
1133 // bound of T" can be converted to an rvalue of type "pointer to
1134 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001135 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001136
John McCall5c32be02010-08-24 20:38:10 +00001137 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001138 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001139 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001140
1141 // For the purpose of ranking in overload resolution
1142 // (13.3.3.1.1), this conversion is considered an
1143 // array-to-pointer conversion followed by a qualification
1144 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001145 SCS.Second = ICK_Identity;
1146 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001147 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001148 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001149 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001150 }
John McCall086a4642010-11-24 05:12:34 +00001151 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001152 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001153 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001154
1155 // An lvalue of function type T can be converted to an rvalue of
1156 // type "pointer to T." The result is a pointer to the
1157 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001158 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001159 } else {
1160 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001161 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001162 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001163 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001164
1165 // The second conversion can be an integral promotion, floating
1166 // point promotion, integral conversion, floating point conversion,
1167 // floating-integral conversion, pointer conversion,
1168 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001169 // For overloading in C, this can also be a "compatible-type"
1170 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001171 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001172 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001173 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001174 // The unqualified versions of the types are the same: there's no
1175 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001176 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001177 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001178 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001179 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001180 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001181 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001182 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001183 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001184 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001185 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001186 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001187 SCS.Second = ICK_Complex_Promotion;
1188 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001189 } else if (ToType->isBooleanType() &&
1190 (FromType->isArithmeticType() ||
1191 FromType->isAnyPointerType() ||
1192 FromType->isBlockPointerType() ||
1193 FromType->isMemberPointerType() ||
1194 FromType->isNullPtrType())) {
1195 // Boolean conversions (C++ 4.12).
1196 SCS.Second = ICK_Boolean_Conversion;
1197 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001198 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001199 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001200 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001201 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001202 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001203 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001204 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001205 SCS.Second = ICK_Complex_Conversion;
1206 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001207 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1208 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001209 // Complex-real conversions (C99 6.3.1.7)
1210 SCS.Second = ICK_Complex_Real;
1211 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001212 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001213 // Floating point conversions (C++ 4.8).
1214 SCS.Second = ICK_Floating_Conversion;
1215 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001216 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001217 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001218 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001219 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001220 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001221 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001222 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001223 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001224 SCS.Second = ICK_Block_Pointer_Conversion;
1225 } else if (AllowObjCWritebackConversion &&
1226 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1227 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001228 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1229 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001230 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001231 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001232 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001233 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001234 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001235 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001236 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001237 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001238 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001239 SCS.Second = SecondICK;
1240 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001241 } else if (!S.getLangOptions().CPlusPlus &&
1242 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001243 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001244 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001245 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001246 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001247 // Treat a conversion that strips "noreturn" as an identity conversion.
1248 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001249 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1250 InOverloadResolution,
1251 SCS, CStyle)) {
1252 SCS.Second = ICK_TransparentUnionConversion;
1253 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001254 } else {
1255 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001256 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001257 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001258 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001259
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001260 QualType CanonFrom;
1261 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001262 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001263 bool ObjCLifetimeConversion;
1264 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1265 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001266 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001267 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001268 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001269 CanonFrom = S.Context.getCanonicalType(FromType);
1270 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001271 } else {
1272 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001273 SCS.Third = ICK_Identity;
1274
Mike Stump11289f42009-09-09 15:08:12 +00001275 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001276 // [...] Any difference in top-level cv-qualification is
1277 // subsumed by the initialization itself and does not constitute
1278 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001279 CanonFrom = S.Context.getCanonicalType(FromType);
1280 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001281 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001282 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001283 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001284 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1285 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001286 FromType = ToType;
1287 CanonFrom = CanonTo;
1288 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001289 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001290 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001291
1292 // If we have not converted the argument type to the parameter type,
1293 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001294 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001295 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001296
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001297 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001298}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001299
1300static bool
1301IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1302 QualType &ToType,
1303 bool InOverloadResolution,
1304 StandardConversionSequence &SCS,
1305 bool CStyle) {
1306
1307 const RecordType *UT = ToType->getAsUnionType();
1308 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1309 return false;
1310 // The field to initialize within the transparent union.
1311 RecordDecl *UD = UT->getDecl();
1312 // It's compatible if the expression matches any of the fields.
1313 for (RecordDecl::field_iterator it = UD->field_begin(),
1314 itend = UD->field_end();
1315 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001316 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1317 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001318 ToType = it->getType();
1319 return true;
1320 }
1321 }
1322 return false;
1323}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001324
1325/// IsIntegralPromotion - Determines whether the conversion from the
1326/// expression From (whose potentially-adjusted type is FromType) to
1327/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1328/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001329bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001330 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001331 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001332 if (!To) {
1333 return false;
1334 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001335
1336 // An rvalue of type char, signed char, unsigned char, short int, or
1337 // unsigned short int can be converted to an rvalue of type int if
1338 // int can represent all the values of the source type; otherwise,
1339 // the source rvalue can be converted to an rvalue of type unsigned
1340 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001341 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1342 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001343 if (// We can promote any signed, promotable integer type to an int
1344 (FromType->isSignedIntegerType() ||
1345 // We can promote any unsigned integer type whose size is
1346 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001347 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001348 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001349 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001350 }
1351
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001352 return To->getKind() == BuiltinType::UInt;
1353 }
1354
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001355 // C++0x [conv.prom]p3:
1356 // A prvalue of an unscoped enumeration type whose underlying type is not
1357 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1358 // following types that can represent all the values of the enumeration
1359 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1360 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001361 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001362 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001363 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001364 // with lowest integer conversion rank (4.13) greater than the rank of long
1365 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001366 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001367 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1368 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1369 // provided for a scoped enumeration.
1370 if (FromEnumType->getDecl()->isScoped())
1371 return false;
1372
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001373 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001374 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001375 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001376 return Context.hasSameUnqualifiedType(ToType,
1377 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001378 }
John McCall56774992009-12-09 09:09:27 +00001379
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001380 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001381 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1382 // to an rvalue a prvalue of the first of the following types that can
1383 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001384 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001385 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001386 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001388 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001389 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001390 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001391 // Determine whether the type we're converting from is signed or
1392 // unsigned.
1393 bool FromIsSigned;
1394 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001395
John McCall56774992009-12-09 09:09:27 +00001396 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1397 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001398
1399 // The types we'll try to promote to, in the appropriate
1400 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001401 QualType PromoteTypes[6] = {
1402 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001403 Context.LongTy, Context.UnsignedLongTy ,
1404 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001405 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001406 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001407 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1408 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001409 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001410 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1411 // We found the type that we can promote to. If this is the
1412 // type we wanted, we have a promotion. Otherwise, no
1413 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001414 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001415 }
1416 }
1417 }
1418
1419 // An rvalue for an integral bit-field (9.6) can be converted to an
1420 // rvalue of type int if int can represent all the values of the
1421 // bit-field; otherwise, it can be converted to unsigned int if
1422 // unsigned int can represent all the values of the bit-field. If
1423 // the bit-field is larger yet, no integral promotion applies to
1424 // it. If the bit-field has an enumerated type, it is treated as any
1425 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001426 // FIXME: We should delay checking of bit-fields until we actually perform the
1427 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001428 using llvm::APSInt;
1429 if (From)
1430 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001431 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001432 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001433 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1434 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1435 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001436
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001437 // Are we promoting to an int from a bitfield that fits in an int?
1438 if (BitWidth < ToSize ||
1439 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1440 return To->getKind() == BuiltinType::Int;
1441 }
Mike Stump11289f42009-09-09 15:08:12 +00001442
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001443 // Are we promoting to an unsigned int from an unsigned bitfield
1444 // that fits into an unsigned int?
1445 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1446 return To->getKind() == BuiltinType::UInt;
1447 }
Mike Stump11289f42009-09-09 15:08:12 +00001448
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001449 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001450 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001451 }
Mike Stump11289f42009-09-09 15:08:12 +00001452
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001453 // An rvalue of type bool can be converted to an rvalue of type int,
1454 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001455 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001456 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001457 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001458
1459 return false;
1460}
1461
1462/// IsFloatingPointPromotion - Determines whether the conversion from
1463/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1464/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001465bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001466 /// An rvalue of type float can be converted to an rvalue of type
1467 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001468 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1469 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001470 if (FromBuiltin->getKind() == BuiltinType::Float &&
1471 ToBuiltin->getKind() == BuiltinType::Double)
1472 return true;
1473
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001474 // C99 6.3.1.5p1:
1475 // When a float is promoted to double or long double, or a
1476 // double is promoted to long double [...].
1477 if (!getLangOptions().CPlusPlus &&
1478 (FromBuiltin->getKind() == BuiltinType::Float ||
1479 FromBuiltin->getKind() == BuiltinType::Double) &&
1480 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1481 return true;
1482 }
1483
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001484 return false;
1485}
1486
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001487/// \brief Determine if a conversion is a complex promotion.
1488///
1489/// A complex promotion is defined as a complex -> complex conversion
1490/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001491/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001492bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001493 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001494 if (!FromComplex)
1495 return false;
1496
John McCall9dd450b2009-09-21 23:43:11 +00001497 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001498 if (!ToComplex)
1499 return false;
1500
1501 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001502 ToComplex->getElementType()) ||
1503 IsIntegralPromotion(0, FromComplex->getElementType(),
1504 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001505}
1506
Douglas Gregor237f96c2008-11-26 23:31:11 +00001507/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1508/// the pointer type FromPtr to a pointer to type ToPointee, with the
1509/// same type qualifiers as FromPtr has on its pointee type. ToType,
1510/// if non-empty, will be a pointer to ToType that may or may not have
1511/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001512///
Mike Stump11289f42009-09-09 15:08:12 +00001513static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001514BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001515 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001516 ASTContext &Context,
1517 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001518 assert((FromPtr->getTypeClass() == Type::Pointer ||
1519 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1520 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001521
John McCall31168b02011-06-15 23:02:42 +00001522 /// Conversions to 'id' subsume cv-qualifier conversions.
1523 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001524 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001525
1526 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001527 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001528 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001529 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001530
John McCall31168b02011-06-15 23:02:42 +00001531 if (StripObjCLifetime)
1532 Quals.removeObjCLifetime();
1533
Mike Stump11289f42009-09-09 15:08:12 +00001534 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001535 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001536 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001537 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001538 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001539
1540 // Build a pointer to ToPointee. It has the right qualifiers
1541 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001542 if (isa<ObjCObjectPointerType>(ToType))
1543 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001544 return Context.getPointerType(ToPointee);
1545 }
1546
1547 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001548 QualType QualifiedCanonToPointee
1549 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001550
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001551 if (isa<ObjCObjectPointerType>(ToType))
1552 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1553 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001554}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001555
Mike Stump11289f42009-09-09 15:08:12 +00001556static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001557 bool InOverloadResolution,
1558 ASTContext &Context) {
1559 // Handle value-dependent integral null pointer constants correctly.
1560 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1561 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001562 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001563 return !InOverloadResolution;
1564
Douglas Gregor56751b52009-09-25 04:25:58 +00001565 return Expr->isNullPointerConstant(Context,
1566 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1567 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001568}
Mike Stump11289f42009-09-09 15:08:12 +00001569
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001570/// IsPointerConversion - Determines whether the conversion of the
1571/// expression From, which has the (possibly adjusted) type FromType,
1572/// can be converted to the type ToType via a pointer conversion (C++
1573/// 4.10). If so, returns true and places the converted type (that
1574/// might differ from ToType in its cv-qualifiers at some level) into
1575/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001576///
Douglas Gregora29dc052008-11-27 01:19:21 +00001577/// This routine also supports conversions to and from block pointers
1578/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1579/// pointers to interfaces. FIXME: Once we've determined the
1580/// appropriate overloading rules for Objective-C, we may want to
1581/// split the Objective-C checks into a different routine; however,
1582/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001583/// conversions, so for now they live here. IncompatibleObjC will be
1584/// set if the conversion is an allowed Objective-C conversion that
1585/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001586bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001587 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001588 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001589 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001590 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001591 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1592 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001593 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001594
Mike Stump11289f42009-09-09 15:08:12 +00001595 // Conversion from a null pointer constant to any Objective-C pointer type.
1596 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001597 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001598 ConvertedType = ToType;
1599 return true;
1600 }
1601
Douglas Gregor231d1c62008-11-27 00:15:41 +00001602 // Blocks: Block pointers can be converted to void*.
1603 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001604 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001605 ConvertedType = ToType;
1606 return true;
1607 }
1608 // Blocks: A null pointer constant can be converted to a block
1609 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001610 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001611 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001612 ConvertedType = ToType;
1613 return true;
1614 }
1615
Sebastian Redl576fd422009-05-10 18:38:11 +00001616 // If the left-hand-side is nullptr_t, the right side can be a null
1617 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001618 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001619 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001620 ConvertedType = ToType;
1621 return true;
1622 }
1623
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001624 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001625 if (!ToTypePtr)
1626 return false;
1627
1628 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001629 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001630 ConvertedType = ToType;
1631 return true;
1632 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001633
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001634 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001635 // , including objective-c pointers.
1636 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001637 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1638 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001639 ConvertedType = BuildSimilarlyQualifiedPointerType(
1640 FromType->getAs<ObjCObjectPointerType>(),
1641 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001642 ToType, Context);
1643 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001644 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001645 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001646 if (!FromTypePtr)
1647 return false;
1648
1649 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001650
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001651 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001652 // pointer conversion, so don't do all of the work below.
1653 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1654 return false;
1655
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001656 // An rvalue of type "pointer to cv T," where T is an object type,
1657 // can be converted to an rvalue of type "pointer to cv void" (C++
1658 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001659 if (FromPointeeType->isIncompleteOrObjectType() &&
1660 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001661 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001662 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001663 ToType, Context,
1664 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001665 return true;
1666 }
1667
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001668 // MSVC allows implicit function to void* type conversion.
1669 if (getLangOptions().Microsoft && FromPointeeType->isFunctionType() &&
1670 ToPointeeType->isVoidType()) {
1671 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1672 ToPointeeType,
1673 ToType, Context);
1674 return true;
1675 }
1676
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001677 // When we're overloading in C, we allow a special kind of pointer
1678 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001679 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001680 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001681 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001682 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001683 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001684 return true;
1685 }
1686
Douglas Gregor5c407d92008-10-23 00:40:37 +00001687 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001688 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001689 // An rvalue of type "pointer to cv D," where D is a class type,
1690 // can be converted to an rvalue of type "pointer to cv B," where
1691 // B is a base class (clause 10) of D. If B is an inaccessible
1692 // (clause 11) or ambiguous (10.2) base class of D, a program that
1693 // necessitates this conversion is ill-formed. The result of the
1694 // conversion is a pointer to the base class sub-object of the
1695 // derived class object. The null pointer value is converted to
1696 // the null pointer value of the destination type.
1697 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001698 // Note that we do not check for ambiguity or inaccessibility
1699 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001700 if (getLangOptions().CPlusPlus &&
1701 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001702 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001703 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001704 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001705 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001706 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001707 ToType, Context);
1708 return true;
1709 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001710
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001711 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1712 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1713 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1714 ToPointeeType,
1715 ToType, Context);
1716 return true;
1717 }
1718
Douglas Gregora119f102008-12-19 19:13:09 +00001719 return false;
1720}
Douglas Gregoraec25842011-04-26 23:16:46 +00001721
1722/// \brief Adopt the given qualifiers for the given type.
1723static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1724 Qualifiers TQs = T.getQualifiers();
1725
1726 // Check whether qualifiers already match.
1727 if (TQs == Qs)
1728 return T;
1729
1730 if (Qs.compatiblyIncludes(TQs))
1731 return Context.getQualifiedType(T, Qs);
1732
1733 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1734}
Douglas Gregora119f102008-12-19 19:13:09 +00001735
1736/// isObjCPointerConversion - Determines whether this is an
1737/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1738/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001739bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001740 QualType& ConvertedType,
1741 bool &IncompatibleObjC) {
1742 if (!getLangOptions().ObjC1)
1743 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001744
Douglas Gregoraec25842011-04-26 23:16:46 +00001745 // The set of qualifiers on the type we're converting from.
1746 Qualifiers FromQualifiers = FromType.getQualifiers();
1747
Steve Naroff7cae42b2009-07-10 23:34:53 +00001748 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001749 const ObjCObjectPointerType* ToObjCPtr =
1750 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001751 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001752 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001753
Steve Naroff7cae42b2009-07-10 23:34:53 +00001754 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001755 // If the pointee types are the same (ignoring qualifications),
1756 // then this is not a pointer conversion.
1757 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1758 FromObjCPtr->getPointeeType()))
1759 return false;
1760
Douglas Gregoraec25842011-04-26 23:16:46 +00001761 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00001762 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001763 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001764 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001765 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001766 return true;
1767 }
1768 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001769 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001770 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001771 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001772 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001773 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001774 return true;
1775 }
1776 // Objective C++: We're able to convert from a pointer to an
1777 // interface to a pointer to a different interface.
1778 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001779 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1780 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1781 if (getLangOptions().CPlusPlus && LHS && RHS &&
1782 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1783 FromObjCPtr->getPointeeType()))
1784 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001785 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001786 ToObjCPtr->getPointeeType(),
1787 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001788 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001789 return true;
1790 }
1791
1792 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1793 // Okay: this is some kind of implicit downcast of Objective-C
1794 // interfaces, which is permitted. However, we're going to
1795 // complain about it.
1796 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001797 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001798 ToObjCPtr->getPointeeType(),
1799 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001800 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001801 return true;
1802 }
Mike Stump11289f42009-09-09 15:08:12 +00001803 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001804 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001805 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001806 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001807 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001808 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001809 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001810 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001811 // to a block pointer type.
1812 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001813 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001814 return true;
1815 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001816 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001818 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001819 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001820 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001821 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00001822 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001823 return true;
1824 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001825 else
Douglas Gregora119f102008-12-19 19:13:09 +00001826 return false;
1827
Douglas Gregor033f56d2008-12-23 00:53:59 +00001828 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001829 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001830 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001831 else if (const BlockPointerType *FromBlockPtr =
1832 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001833 FromPointeeType = FromBlockPtr->getPointeeType();
1834 else
Douglas Gregora119f102008-12-19 19:13:09 +00001835 return false;
1836
Douglas Gregora119f102008-12-19 19:13:09 +00001837 // If we have pointers to pointers, recursively check whether this
1838 // is an Objective-C conversion.
1839 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1840 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1841 IncompatibleObjC)) {
1842 // We always complain about this conversion.
1843 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001844 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001845 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001846 return true;
1847 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001848 // Allow conversion of pointee being objective-c pointer to another one;
1849 // as in I* to id.
1850 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1851 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1852 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1853 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00001854
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001855 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001856 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001857 return true;
1858 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001859
Douglas Gregor033f56d2008-12-23 00:53:59 +00001860 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001861 // differences in the argument and result types are in Objective-C
1862 // pointer conversions. If so, we permit the conversion (but
1863 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001864 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001865 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001866 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001867 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001868 if (FromFunctionType && ToFunctionType) {
1869 // If the function types are exactly the same, this isn't an
1870 // Objective-C pointer conversion.
1871 if (Context.getCanonicalType(FromPointeeType)
1872 == Context.getCanonicalType(ToPointeeType))
1873 return false;
1874
1875 // Perform the quick checks that will tell us whether these
1876 // function types are obviously different.
1877 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1878 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1879 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1880 return false;
1881
1882 bool HasObjCConversion = false;
1883 if (Context.getCanonicalType(FromFunctionType->getResultType())
1884 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1885 // Okay, the types match exactly. Nothing to do.
1886 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1887 ToFunctionType->getResultType(),
1888 ConvertedType, IncompatibleObjC)) {
1889 // Okay, we have an Objective-C pointer conversion.
1890 HasObjCConversion = true;
1891 } else {
1892 // Function types are too different. Abort.
1893 return false;
1894 }
Mike Stump11289f42009-09-09 15:08:12 +00001895
Douglas Gregora119f102008-12-19 19:13:09 +00001896 // Check argument types.
1897 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1898 ArgIdx != NumArgs; ++ArgIdx) {
1899 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1900 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1901 if (Context.getCanonicalType(FromArgType)
1902 == Context.getCanonicalType(ToArgType)) {
1903 // Okay, the types match exactly. Nothing to do.
1904 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1905 ConvertedType, IncompatibleObjC)) {
1906 // Okay, we have an Objective-C pointer conversion.
1907 HasObjCConversion = true;
1908 } else {
1909 // Argument types are too different. Abort.
1910 return false;
1911 }
1912 }
1913
1914 if (HasObjCConversion) {
1915 // We had an Objective-C conversion. Allow this pointer
1916 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00001917 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001918 IncompatibleObjC = true;
1919 return true;
1920 }
1921 }
1922
Sebastian Redl72b597d2009-01-25 19:43:20 +00001923 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001924}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001925
John McCall31168b02011-06-15 23:02:42 +00001926/// \brief Determine whether this is an Objective-C writeback conversion,
1927/// used for parameter passing when performing automatic reference counting.
1928///
1929/// \param FromType The type we're converting form.
1930///
1931/// \param ToType The type we're converting to.
1932///
1933/// \param ConvertedType The type that will be produced after applying
1934/// this conversion.
1935bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
1936 QualType &ConvertedType) {
1937 if (!getLangOptions().ObjCAutoRefCount ||
1938 Context.hasSameUnqualifiedType(FromType, ToType))
1939 return false;
1940
1941 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
1942 QualType ToPointee;
1943 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
1944 ToPointee = ToPointer->getPointeeType();
1945 else
1946 return false;
1947
1948 Qualifiers ToQuals = ToPointee.getQualifiers();
1949 if (!ToPointee->isObjCLifetimeType() ||
1950 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
1951 !ToQuals.withoutObjCGLifetime().empty())
1952 return false;
1953
1954 // Argument must be a pointer to __strong to __weak.
1955 QualType FromPointee;
1956 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
1957 FromPointee = FromPointer->getPointeeType();
1958 else
1959 return false;
1960
1961 Qualifiers FromQuals = FromPointee.getQualifiers();
1962 if (!FromPointee->isObjCLifetimeType() ||
1963 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
1964 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
1965 return false;
1966
1967 // Make sure that we have compatible qualifiers.
1968 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
1969 if (!ToQuals.compatiblyIncludes(FromQuals))
1970 return false;
1971
1972 // Remove qualifiers from the pointee type we're converting from; they
1973 // aren't used in the compatibility check belong, and we'll be adding back
1974 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
1975 FromPointee = FromPointee.getUnqualifiedType();
1976
1977 // The unqualified form of the pointee types must be compatible.
1978 ToPointee = ToPointee.getUnqualifiedType();
1979 bool IncompatibleObjC;
1980 if (Context.typesAreCompatible(FromPointee, ToPointee))
1981 FromPointee = ToPointee;
1982 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
1983 IncompatibleObjC))
1984 return false;
1985
1986 /// \brief Construct the type we're converting to, which is a pointer to
1987 /// __autoreleasing pointee.
1988 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
1989 ConvertedType = Context.getPointerType(FromPointee);
1990 return true;
1991}
1992
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001993bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1994 QualType& ConvertedType) {
1995 QualType ToPointeeType;
1996 if (const BlockPointerType *ToBlockPtr =
1997 ToType->getAs<BlockPointerType>())
1998 ToPointeeType = ToBlockPtr->getPointeeType();
1999 else
2000 return false;
2001
2002 QualType FromPointeeType;
2003 if (const BlockPointerType *FromBlockPtr =
2004 FromType->getAs<BlockPointerType>())
2005 FromPointeeType = FromBlockPtr->getPointeeType();
2006 else
2007 return false;
2008 // We have pointer to blocks, check whether the only
2009 // differences in the argument and result types are in Objective-C
2010 // pointer conversions. If so, we permit the conversion.
2011
2012 const FunctionProtoType *FromFunctionType
2013 = FromPointeeType->getAs<FunctionProtoType>();
2014 const FunctionProtoType *ToFunctionType
2015 = ToPointeeType->getAs<FunctionProtoType>();
2016
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002017 if (!FromFunctionType || !ToFunctionType)
2018 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002019
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002020 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002021 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002022
2023 // Perform the quick checks that will tell us whether these
2024 // function types are obviously different.
2025 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2026 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2027 return false;
2028
2029 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2030 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2031 if (FromEInfo != ToEInfo)
2032 return false;
2033
2034 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002035 if (Context.hasSameType(FromFunctionType->getResultType(),
2036 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002037 // Okay, the types match exactly. Nothing to do.
2038 } else {
2039 QualType RHS = FromFunctionType->getResultType();
2040 QualType LHS = ToFunctionType->getResultType();
2041 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2042 !RHS.hasQualifiers() && LHS.hasQualifiers())
2043 LHS = LHS.getUnqualifiedType();
2044
2045 if (Context.hasSameType(RHS,LHS)) {
2046 // OK exact match.
2047 } else if (isObjCPointerConversion(RHS, LHS,
2048 ConvertedType, IncompatibleObjC)) {
2049 if (IncompatibleObjC)
2050 return false;
2051 // Okay, we have an Objective-C pointer conversion.
2052 }
2053 else
2054 return false;
2055 }
2056
2057 // Check argument types.
2058 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2059 ArgIdx != NumArgs; ++ArgIdx) {
2060 IncompatibleObjC = false;
2061 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2062 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2063 if (Context.hasSameType(FromArgType, ToArgType)) {
2064 // Okay, the types match exactly. Nothing to do.
2065 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2066 ConvertedType, IncompatibleObjC)) {
2067 if (IncompatibleObjC)
2068 return false;
2069 // Okay, we have an Objective-C pointer conversion.
2070 } else
2071 // Argument types are too different. Abort.
2072 return false;
2073 }
2074 ConvertedType = ToType;
2075 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002076}
2077
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002078/// FunctionArgTypesAreEqual - This routine checks two function proto types
2079/// for equlity of their argument types. Caller has already checked that
2080/// they have same number of arguments. This routine assumes that Objective-C
2081/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002082bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00002083 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002084 if (!getLangOptions().ObjC1)
2085 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
2086 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002087
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002088 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2089 N = NewType->arg_type_begin(),
2090 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2091 QualType ToType = (*O);
2092 QualType FromType = (*N);
2093 if (ToType != FromType) {
2094 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2095 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002096 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2097 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2098 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2099 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002100 continue;
2101 }
John McCall8b07ec22010-05-15 11:32:37 +00002102 else if (const ObjCObjectPointerType *PTTo =
2103 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002104 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002105 FromType->getAs<ObjCObjectPointerType>())
2106 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2107 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002108 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002109 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002110 }
2111 }
2112 return true;
2113}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002114
Douglas Gregor39c16d42008-10-24 04:54:22 +00002115/// CheckPointerConversion - Check the pointer conversion from the
2116/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002117/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002118/// conversions for which IsPointerConversion has already returned
2119/// true. It returns true and produces a diagnostic if there was an
2120/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002121bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002122 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002123 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002124 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002125 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002126 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002127
John McCall8cb679e2010-11-15 09:13:47 +00002128 Kind = CK_BitCast;
2129
Chandler Carruthffab8732011-04-09 07:32:05 +00002130 if (!IsCStyleOrFunctionalCast &&
2131 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2132 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2133 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002134 PDiag(diag::warn_impcast_bool_to_null_pointer)
2135 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002136
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002137 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
2138 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002139 QualType FromPointeeType = FromPtrType->getPointeeType(),
2140 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002141
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002142 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2143 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002144 // We must have a derived-to-base conversion. Check an
2145 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002146 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2147 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002148 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002149 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002150 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002151
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002152 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002153 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002154 }
2155 }
Mike Stump11289f42009-09-09 15:08:12 +00002156 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00002157 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002158 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00002159 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002160 // Objective-C++ conversions are always okay.
2161 // FIXME: We should have a different class of conversions for the
2162 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002163 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002164 return false;
John McCall8cb679e2010-11-15 09:13:47 +00002165 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002166 }
John McCall8cb679e2010-11-15 09:13:47 +00002167
2168 // We shouldn't fall into this case unless it's valid for other
2169 // reasons.
2170 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2171 Kind = CK_NullToPointer;
2172
Douglas Gregor39c16d42008-10-24 04:54:22 +00002173 return false;
2174}
2175
Sebastian Redl72b597d2009-01-25 19:43:20 +00002176/// IsMemberPointerConversion - Determines whether the conversion of the
2177/// expression From, which has the (possibly adjusted) type FromType, can be
2178/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2179/// If so, returns true and places the converted type (that might differ from
2180/// ToType in its cv-qualifiers at some level) into ConvertedType.
2181bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002182 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002183 bool InOverloadResolution,
2184 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002185 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002186 if (!ToTypePtr)
2187 return false;
2188
2189 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002190 if (From->isNullPointerConstant(Context,
2191 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2192 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002193 ConvertedType = ToType;
2194 return true;
2195 }
2196
2197 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002198 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002199 if (!FromTypePtr)
2200 return false;
2201
2202 // A pointer to member of B can be converted to a pointer to member of D,
2203 // where D is derived from B (C++ 4.11p2).
2204 QualType FromClass(FromTypePtr->getClass(), 0);
2205 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002206
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002207 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2208 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2209 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002210 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2211 ToClass.getTypePtr());
2212 return true;
2213 }
2214
2215 return false;
2216}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002217
Sebastian Redl72b597d2009-01-25 19:43:20 +00002218/// CheckMemberPointerConversion - Check the member pointer conversion from the
2219/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002220/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002221/// for which IsMemberPointerConversion has already returned true. It returns
2222/// true and produces a diagnostic if there was an error, or returns false
2223/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002224bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002225 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002226 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002227 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002228 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002229 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002230 if (!FromPtrType) {
2231 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002232 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002233 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002234 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002235 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002236 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002237 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002238
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002239 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002240 assert(ToPtrType && "No member pointer cast has a target type "
2241 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002242
Sebastian Redled8f2002009-01-28 18:33:18 +00002243 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2244 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002245
Sebastian Redled8f2002009-01-28 18:33:18 +00002246 // FIXME: What about dependent types?
2247 assert(FromClass->isRecordType() && "Pointer into non-class.");
2248 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002249
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002250 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002251 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002252 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2253 assert(DerivationOkay &&
2254 "Should not have been called if derivation isn't OK.");
2255 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002256
Sebastian Redled8f2002009-01-28 18:33:18 +00002257 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2258 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002259 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2260 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2261 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2262 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002263 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002264
Douglas Gregor89ee6822009-02-28 01:32:25 +00002265 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002266 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2267 << FromClass << ToClass << QualType(VBase, 0)
2268 << From->getSourceRange();
2269 return true;
2270 }
2271
John McCall5b0829a2010-02-10 09:31:12 +00002272 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002273 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2274 Paths.front(),
2275 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002276
Anders Carlssond7923c62009-08-22 23:33:40 +00002277 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002278 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002279 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002280 return false;
2281}
2282
Douglas Gregor9a657932008-10-21 23:43:52 +00002283/// IsQualificationConversion - Determines whether the conversion from
2284/// an rvalue of type FromType to ToType is a qualification conversion
2285/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002286///
2287/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2288/// when the qualification conversion involves a change in the Objective-C
2289/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002290bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002291Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002292 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002293 FromType = Context.getCanonicalType(FromType);
2294 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002295 ObjCLifetimeConversion = false;
2296
Douglas Gregor9a657932008-10-21 23:43:52 +00002297 // If FromType and ToType are the same type, this is not a
2298 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002299 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002300 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002301
Douglas Gregor9a657932008-10-21 23:43:52 +00002302 // (C++ 4.4p4):
2303 // A conversion can add cv-qualifiers at levels other than the first
2304 // in multi-level pointers, subject to the following rules: [...]
2305 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002306 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002307 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002308 // Within each iteration of the loop, we check the qualifiers to
2309 // determine if this still looks like a qualification
2310 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002311 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002312 // until there are no more pointers or pointers-to-members left to
2313 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002314 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002315
Douglas Gregor90609aa2011-04-25 18:40:17 +00002316 Qualifiers FromQuals = FromType.getQualifiers();
2317 Qualifiers ToQuals = ToType.getQualifiers();
2318
John McCall31168b02011-06-15 23:02:42 +00002319 // Objective-C ARC:
2320 // Check Objective-C lifetime conversions.
2321 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2322 UnwrappedAnyPointer) {
2323 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2324 ObjCLifetimeConversion = true;
2325 FromQuals.removeObjCLifetime();
2326 ToQuals.removeObjCLifetime();
2327 } else {
2328 // Qualification conversions cannot cast between different
2329 // Objective-C lifetime qualifiers.
2330 return false;
2331 }
2332 }
2333
Douglas Gregorf30053d2011-05-08 06:09:53 +00002334 // Allow addition/removal of GC attributes but not changing GC attributes.
2335 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2336 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2337 FromQuals.removeObjCGCAttr();
2338 ToQuals.removeObjCGCAttr();
2339 }
2340
Douglas Gregor9a657932008-10-21 23:43:52 +00002341 // -- for every j > 0, if const is in cv 1,j then const is in cv
2342 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002343 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002344 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002345
Douglas Gregor9a657932008-10-21 23:43:52 +00002346 // -- if the cv 1,j and cv 2,j are different, then const is in
2347 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002348 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002349 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002350 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002351
Douglas Gregor9a657932008-10-21 23:43:52 +00002352 // Keep track of whether all prior cv-qualifiers in the "to" type
2353 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002354 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002355 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002356 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002357
2358 // We are left with FromType and ToType being the pointee types
2359 // after unwrapping the original FromType and ToType the same number
2360 // of types. If we unwrapped any pointers, and if FromType and
2361 // ToType have the same unqualified type (since we checked
2362 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002363 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002364}
2365
Douglas Gregor576e98c2009-01-30 23:27:23 +00002366/// Determines whether there is a user-defined conversion sequence
2367/// (C++ [over.ics.user]) that converts expression From to the type
2368/// ToType. If such a conversion exists, User will contain the
2369/// user-defined conversion sequence that performs such a conversion
2370/// and this routine will return true. Otherwise, this routine returns
2371/// false and User is unspecified.
2372///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002373/// \param AllowExplicit true if the conversion should consider C++0x
2374/// "explicit" conversion functions as well as non-explicit conversion
2375/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002376static OverloadingResult
2377IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2378 UserDefinedConversionSequence& User,
2379 OverloadCandidateSet& CandidateSet,
2380 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002381 // Whether we will only visit constructors.
2382 bool ConstructorsOnly = false;
2383
2384 // If the type we are conversion to is a class type, enumerate its
2385 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002386 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002387 // C++ [over.match.ctor]p1:
2388 // When objects of class type are direct-initialized (8.5), or
2389 // copy-initialized from an expression of the same or a
2390 // derived class type (8.5), overload resolution selects the
2391 // constructor. [...] For copy-initialization, the candidate
2392 // functions are all the converting constructors (12.3.1) of
2393 // that class. The argument list is the expression-list within
2394 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002395 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002396 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002397 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002398 ConstructorsOnly = true;
2399
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002400 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2401 // RequireCompleteType may have returned true due to some invalid decl
2402 // during template instantiation, but ToType may be complete enough now
2403 // to try to recover.
2404 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002405 // We're not going to find any constructors.
2406 } else if (CXXRecordDecl *ToRecordDecl
2407 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002408 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002409 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002410 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002411 NamedDecl *D = *Con;
2412 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2413
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002414 // Find the constructor (which may be a template).
2415 CXXConstructorDecl *Constructor = 0;
2416 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002417 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002418 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002419 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002420 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2421 else
John McCalla0296f72010-03-19 07:35:19 +00002422 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002423
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002424 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002425 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002426 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002427 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2428 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002429 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002430 /*SuppressUserConversions=*/
2431 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002432 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002433 // Allow one user-defined conversion when user specifies a
2434 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002435 S.AddOverloadCandidate(Constructor, FoundDecl,
2436 &From, 1, CandidateSet,
2437 /*SuppressUserConversions=*/
2438 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002439 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002440 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002441 }
2442 }
2443
Douglas Gregor5ab11652010-04-17 22:01:05 +00002444 // Enumerate conversion functions, if we're allowed to.
2445 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002446 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2447 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002448 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002449 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002450 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002451 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002452 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2453 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002454 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002455 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002456 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002457 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002458 DeclAccessPair FoundDecl = I.getPair();
2459 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002460 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2461 if (isa<UsingShadowDecl>(D))
2462 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2463
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002464 CXXConversionDecl *Conv;
2465 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002466 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2467 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002468 else
John McCallda4458e2010-03-31 01:36:47 +00002469 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002470
2471 if (AllowExplicit || !Conv->isExplicit()) {
2472 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002473 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2474 ActingContext, From, ToType,
2475 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002476 else
John McCall5c32be02010-08-24 20:38:10 +00002477 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2478 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002479 }
2480 }
2481 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002482 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002483
2484 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002485 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002486 case OR_Success:
2487 // Record the standard conversion we used and the conversion function.
2488 if (CXXConstructorDecl *Constructor
2489 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002490 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2491
John McCall5c32be02010-08-24 20:38:10 +00002492 // C++ [over.ics.user]p1:
2493 // If the user-defined conversion is specified by a
2494 // constructor (12.3.1), the initial standard conversion
2495 // sequence converts the source type to the type required by
2496 // the argument of the constructor.
2497 //
2498 QualType ThisType = Constructor->getThisType(S.Context);
2499 if (Best->Conversions[0].isEllipsis())
2500 User.EllipsisConversion = true;
2501 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002502 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002503 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002504 }
John McCall5c32be02010-08-24 20:38:10 +00002505 User.ConversionFunction = Constructor;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002506 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002507 User.After.setAsIdentityConversion();
2508 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2509 User.After.setAllToTypes(ToType);
2510 return OR_Success;
2511 } else if (CXXConversionDecl *Conversion
2512 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002513 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2514
John McCall5c32be02010-08-24 20:38:10 +00002515 // C++ [over.ics.user]p1:
2516 //
2517 // [...] If the user-defined conversion is specified by a
2518 // conversion function (12.3.2), the initial standard
2519 // conversion sequence converts the source type to the
2520 // implicit object parameter of the conversion function.
2521 User.Before = Best->Conversions[0].Standard;
2522 User.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002523 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002524 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002525
John McCall5c32be02010-08-24 20:38:10 +00002526 // C++ [over.ics.user]p2:
2527 // The second standard conversion sequence converts the
2528 // result of the user-defined conversion to the target type
2529 // for the sequence. Since an implicit conversion sequence
2530 // is an initialization, the special rules for
2531 // initialization by user-defined conversion apply when
2532 // selecting the best user-defined conversion for a
2533 // user-defined conversion sequence (see 13.3.3 and
2534 // 13.3.3.1).
2535 User.After = Best->FinalConversion;
2536 return OR_Success;
2537 } else {
2538 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002539 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002540 }
2541
John McCall5c32be02010-08-24 20:38:10 +00002542 case OR_No_Viable_Function:
2543 return OR_No_Viable_Function;
2544 case OR_Deleted:
2545 // No conversion here! We're done.
2546 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002547
John McCall5c32be02010-08-24 20:38:10 +00002548 case OR_Ambiguous:
2549 return OR_Ambiguous;
2550 }
2551
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002552 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002553}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002554
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002555bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002556Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002557 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002558 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002559 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002560 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002561 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002562 if (OvResult == OR_Ambiguous)
2563 Diag(From->getSourceRange().getBegin(),
2564 diag::err_typecheck_ambiguous_condition)
2565 << From->getType() << ToType << From->getSourceRange();
2566 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2567 Diag(From->getSourceRange().getBegin(),
2568 diag::err_typecheck_nonviable_condition)
2569 << From->getType() << ToType << From->getSourceRange();
2570 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002571 return false;
John McCall5c32be02010-08-24 20:38:10 +00002572 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002573 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002574}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002575
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002576/// CompareImplicitConversionSequences - Compare two implicit
2577/// conversion sequences to determine whether one is better than the
2578/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002579static ImplicitConversionSequence::CompareKind
2580CompareImplicitConversionSequences(Sema &S,
2581 const ImplicitConversionSequence& ICS1,
2582 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002583{
2584 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2585 // conversion sequences (as defined in 13.3.3.1)
2586 // -- a standard conversion sequence (13.3.3.1.1) is a better
2587 // conversion sequence than a user-defined conversion sequence or
2588 // an ellipsis conversion sequence, and
2589 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2590 // conversion sequence than an ellipsis conversion sequence
2591 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002592 //
John McCall0d1da222010-01-12 00:44:57 +00002593 // C++0x [over.best.ics]p10:
2594 // For the purpose of ranking implicit conversion sequences as
2595 // described in 13.3.3.2, the ambiguous conversion sequence is
2596 // treated as a user-defined sequence that is indistinguishable
2597 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002598 if (ICS1.getKindRank() < ICS2.getKindRank())
2599 return ImplicitConversionSequence::Better;
2600 else if (ICS2.getKindRank() < ICS1.getKindRank())
2601 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002602
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002603 // The following checks require both conversion sequences to be of
2604 // the same kind.
2605 if (ICS1.getKind() != ICS2.getKind())
2606 return ImplicitConversionSequence::Indistinguishable;
2607
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002608 // Two implicit conversion sequences of the same form are
2609 // indistinguishable conversion sequences unless one of the
2610 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002611 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002612 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002613 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002614 // User-defined conversion sequence U1 is a better conversion
2615 // sequence than another user-defined conversion sequence U2 if
2616 // they contain the same user-defined conversion function or
2617 // constructor and if the second standard conversion sequence of
2618 // U1 is better than the second standard conversion sequence of
2619 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002620 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002621 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002622 return CompareStandardConversionSequences(S,
2623 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002624 ICS2.UserDefined.After);
2625 }
2626
2627 return ImplicitConversionSequence::Indistinguishable;
2628}
2629
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002630static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2631 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2632 Qualifiers Quals;
2633 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002634 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002635 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002636
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002637 return Context.hasSameUnqualifiedType(T1, T2);
2638}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002639
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002640// Per 13.3.3.2p3, compare the given standard conversion sequences to
2641// determine if one is a proper subset of the other.
2642static ImplicitConversionSequence::CompareKind
2643compareStandardConversionSubsets(ASTContext &Context,
2644 const StandardConversionSequence& SCS1,
2645 const StandardConversionSequence& SCS2) {
2646 ImplicitConversionSequence::CompareKind Result
2647 = ImplicitConversionSequence::Indistinguishable;
2648
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002649 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002650 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00002651 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2652 return ImplicitConversionSequence::Better;
2653 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2654 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002655
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002656 if (SCS1.Second != SCS2.Second) {
2657 if (SCS1.Second == ICK_Identity)
2658 Result = ImplicitConversionSequence::Better;
2659 else if (SCS2.Second == ICK_Identity)
2660 Result = ImplicitConversionSequence::Worse;
2661 else
2662 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002663 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002664 return ImplicitConversionSequence::Indistinguishable;
2665
2666 if (SCS1.Third == SCS2.Third) {
2667 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2668 : ImplicitConversionSequence::Indistinguishable;
2669 }
2670
2671 if (SCS1.Third == ICK_Identity)
2672 return Result == ImplicitConversionSequence::Worse
2673 ? ImplicitConversionSequence::Indistinguishable
2674 : ImplicitConversionSequence::Better;
2675
2676 if (SCS2.Third == ICK_Identity)
2677 return Result == ImplicitConversionSequence::Better
2678 ? ImplicitConversionSequence::Indistinguishable
2679 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002680
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002681 return ImplicitConversionSequence::Indistinguishable;
2682}
2683
Douglas Gregore696ebb2011-01-26 14:52:12 +00002684/// \brief Determine whether one of the given reference bindings is better
2685/// than the other based on what kind of bindings they are.
2686static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2687 const StandardConversionSequence &SCS2) {
2688 // C++0x [over.ics.rank]p3b4:
2689 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2690 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002691 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002692 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002693 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002694 // reference*.
2695 //
2696 // FIXME: Rvalue references. We're going rogue with the above edits,
2697 // because the semantics in the current C++0x working paper (N3225 at the
2698 // time of this writing) break the standard definition of std::forward
2699 // and std::reference_wrapper when dealing with references to functions.
2700 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002701 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2702 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2703 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002704
Douglas Gregore696ebb2011-01-26 14:52:12 +00002705 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2706 SCS2.IsLvalueReference) ||
2707 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2708 !SCS2.IsLvalueReference);
2709}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002710
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002711/// CompareStandardConversionSequences - Compare two standard
2712/// conversion sequences to determine whether one is better than the
2713/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002714static ImplicitConversionSequence::CompareKind
2715CompareStandardConversionSequences(Sema &S,
2716 const StandardConversionSequence& SCS1,
2717 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002718{
2719 // Standard conversion sequence S1 is a better conversion sequence
2720 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2721
2722 // -- S1 is a proper subsequence of S2 (comparing the conversion
2723 // sequences in the canonical form defined by 13.3.3.1.1,
2724 // excluding any Lvalue Transformation; the identity conversion
2725 // sequence is considered to be a subsequence of any
2726 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002727 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002728 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002729 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002730
2731 // -- the rank of S1 is better than the rank of S2 (by the rules
2732 // defined below), or, if not that,
2733 ImplicitConversionRank Rank1 = SCS1.getRank();
2734 ImplicitConversionRank Rank2 = SCS2.getRank();
2735 if (Rank1 < Rank2)
2736 return ImplicitConversionSequence::Better;
2737 else if (Rank2 < Rank1)
2738 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002739
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002740 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2741 // are indistinguishable unless one of the following rules
2742 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002743
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002744 // A conversion that is not a conversion of a pointer, or
2745 // pointer to member, to bool is better than another conversion
2746 // that is such a conversion.
2747 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2748 return SCS2.isPointerConversionToBool()
2749 ? ImplicitConversionSequence::Better
2750 : ImplicitConversionSequence::Worse;
2751
Douglas Gregor5c407d92008-10-23 00:40:37 +00002752 // C++ [over.ics.rank]p4b2:
2753 //
2754 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002755 // conversion of B* to A* is better than conversion of B* to
2756 // void*, and conversion of A* to void* is better than conversion
2757 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002758 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002759 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002760 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002761 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002762 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2763 // Exactly one of the conversion sequences is a conversion to
2764 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002765 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2766 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002767 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2768 // Neither conversion sequence converts to a void pointer; compare
2769 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002770 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002771 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002772 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002773 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2774 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002775 // Both conversion sequences are conversions to void
2776 // pointers. Compare the source types to determine if there's an
2777 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002778 QualType FromType1 = SCS1.getFromType();
2779 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002780
2781 // Adjust the types we're converting from via the array-to-pointer
2782 // conversion, if we need to.
2783 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002784 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002785 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002786 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002787
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002788 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2789 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002790
John McCall5c32be02010-08-24 20:38:10 +00002791 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002792 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002793 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002794 return ImplicitConversionSequence::Worse;
2795
2796 // Objective-C++: If one interface is more specific than the
2797 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002798 const ObjCObjectPointerType* FromObjCPtr1
2799 = FromType1->getAs<ObjCObjectPointerType>();
2800 const ObjCObjectPointerType* FromObjCPtr2
2801 = FromType2->getAs<ObjCObjectPointerType>();
2802 if (FromObjCPtr1 && FromObjCPtr2) {
2803 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2804 FromObjCPtr2);
2805 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2806 FromObjCPtr1);
2807 if (AssignLeft != AssignRight) {
2808 return AssignLeft? ImplicitConversionSequence::Better
2809 : ImplicitConversionSequence::Worse;
2810 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002811 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002812 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002813
2814 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2815 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002816 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002817 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002818 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002819
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002820 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002821 // Check for a better reference binding based on the kind of bindings.
2822 if (isBetterReferenceBindingKind(SCS1, SCS2))
2823 return ImplicitConversionSequence::Better;
2824 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2825 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002826
Sebastian Redlb28b4072009-03-22 23:49:27 +00002827 // C++ [over.ics.rank]p3b4:
2828 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2829 // which the references refer are the same type except for
2830 // top-level cv-qualifiers, and the type to which the reference
2831 // initialized by S2 refers is more cv-qualified than the type
2832 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002833 QualType T1 = SCS1.getToType(2);
2834 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002835 T1 = S.Context.getCanonicalType(T1);
2836 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002837 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002838 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2839 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002840 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00002841 // Objective-C++ ARC: If the references refer to objects with different
2842 // lifetimes, prefer bindings that don't change lifetime.
2843 if (SCS1.ObjCLifetimeConversionBinding !=
2844 SCS2.ObjCLifetimeConversionBinding) {
2845 return SCS1.ObjCLifetimeConversionBinding
2846 ? ImplicitConversionSequence::Worse
2847 : ImplicitConversionSequence::Better;
2848 }
2849
Chandler Carruth8e543b32010-12-12 08:17:55 +00002850 // If the type is an array type, promote the element qualifiers to the
2851 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002852 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002853 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002854 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002855 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002856 if (T2.isMoreQualifiedThan(T1))
2857 return ImplicitConversionSequence::Better;
2858 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00002859 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002860 }
2861 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002862
2863 return ImplicitConversionSequence::Indistinguishable;
2864}
2865
2866/// CompareQualificationConversions - Compares two standard conversion
2867/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002868/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2869ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002870CompareQualificationConversions(Sema &S,
2871 const StandardConversionSequence& SCS1,
2872 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002873 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002874 // -- S1 and S2 differ only in their qualification conversion and
2875 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2876 // cv-qualification signature of type T1 is a proper subset of
2877 // the cv-qualification signature of type T2, and S1 is not the
2878 // deprecated string literal array-to-pointer conversion (4.2).
2879 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2880 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2881 return ImplicitConversionSequence::Indistinguishable;
2882
2883 // FIXME: the example in the standard doesn't use a qualification
2884 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002885 QualType T1 = SCS1.getToType(2);
2886 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002887 T1 = S.Context.getCanonicalType(T1);
2888 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002889 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002890 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2891 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002892
2893 // If the types are the same, we won't learn anything by unwrapped
2894 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002895 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002896 return ImplicitConversionSequence::Indistinguishable;
2897
Chandler Carruth607f38e2009-12-29 07:16:59 +00002898 // If the type is an array type, promote the element qualifiers to the type
2899 // for comparison.
2900 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002901 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002902 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002903 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002904
Mike Stump11289f42009-09-09 15:08:12 +00002905 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002906 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00002907
2908 // Objective-C++ ARC:
2909 // Prefer qualification conversions not involving a change in lifetime
2910 // to qualification conversions that do not change lifetime.
2911 if (SCS1.QualificationIncludesObjCLifetime !=
2912 SCS2.QualificationIncludesObjCLifetime) {
2913 Result = SCS1.QualificationIncludesObjCLifetime
2914 ? ImplicitConversionSequence::Worse
2915 : ImplicitConversionSequence::Better;
2916 }
2917
John McCall5c32be02010-08-24 20:38:10 +00002918 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002919 // Within each iteration of the loop, we check the qualifiers to
2920 // determine if this still looks like a qualification
2921 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002922 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002923 // until there are no more pointers or pointers-to-members left
2924 // to unwrap. This essentially mimics what
2925 // IsQualificationConversion does, but here we're checking for a
2926 // strict subset of qualifiers.
2927 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2928 // The qualifiers are the same, so this doesn't tell us anything
2929 // about how the sequences rank.
2930 ;
2931 else if (T2.isMoreQualifiedThan(T1)) {
2932 // T1 has fewer qualifiers, so it could be the better sequence.
2933 if (Result == ImplicitConversionSequence::Worse)
2934 // Neither has qualifiers that are a subset of the other's
2935 // qualifiers.
2936 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002937
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002938 Result = ImplicitConversionSequence::Better;
2939 } else if (T1.isMoreQualifiedThan(T2)) {
2940 // T2 has fewer qualifiers, so it could be the better sequence.
2941 if (Result == ImplicitConversionSequence::Better)
2942 // Neither has qualifiers that are a subset of the other's
2943 // qualifiers.
2944 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002945
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002946 Result = ImplicitConversionSequence::Worse;
2947 } else {
2948 // Qualifiers are disjoint.
2949 return ImplicitConversionSequence::Indistinguishable;
2950 }
2951
2952 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002953 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002954 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002955 }
2956
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002957 // Check that the winning standard conversion sequence isn't using
2958 // the deprecated string literal array to pointer conversion.
2959 switch (Result) {
2960 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002961 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002962 Result = ImplicitConversionSequence::Indistinguishable;
2963 break;
2964
2965 case ImplicitConversionSequence::Indistinguishable:
2966 break;
2967
2968 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002969 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002970 Result = ImplicitConversionSequence::Indistinguishable;
2971 break;
2972 }
2973
2974 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002975}
2976
Douglas Gregor5c407d92008-10-23 00:40:37 +00002977/// CompareDerivedToBaseConversions - Compares two standard conversion
2978/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002979/// various kinds of derived-to-base conversions (C++
2980/// [over.ics.rank]p4b3). As part of these checks, we also look at
2981/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002982ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002983CompareDerivedToBaseConversions(Sema &S,
2984 const StandardConversionSequence& SCS1,
2985 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002986 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002987 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002988 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002989 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002990
2991 // Adjust the types we're converting from via the array-to-pointer
2992 // conversion, if we need to.
2993 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002994 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002995 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002996 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002997
2998 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002999 FromType1 = S.Context.getCanonicalType(FromType1);
3000 ToType1 = S.Context.getCanonicalType(ToType1);
3001 FromType2 = S.Context.getCanonicalType(FromType2);
3002 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003003
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003004 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003005 //
3006 // If class B is derived directly or indirectly from class A and
3007 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003008 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003009 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003010 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003011 SCS2.Second == ICK_Pointer_Conversion &&
3012 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3013 FromType1->isPointerType() && FromType2->isPointerType() &&
3014 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003015 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003016 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003017 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003018 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003019 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003020 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003021 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003022 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003023
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003024 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003025 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003026 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003027 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003028 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003029 return ImplicitConversionSequence::Worse;
3030 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003031
3032 // -- conversion of B* to A* is better than conversion of C* to A*,
3033 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003034 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003035 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003036 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003037 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003038 }
3039 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3040 SCS2.Second == ICK_Pointer_Conversion) {
3041 const ObjCObjectPointerType *FromPtr1
3042 = FromType1->getAs<ObjCObjectPointerType>();
3043 const ObjCObjectPointerType *FromPtr2
3044 = FromType2->getAs<ObjCObjectPointerType>();
3045 const ObjCObjectPointerType *ToPtr1
3046 = ToType1->getAs<ObjCObjectPointerType>();
3047 const ObjCObjectPointerType *ToPtr2
3048 = ToType2->getAs<ObjCObjectPointerType>();
3049
3050 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3051 // Apply the same conversion ranking rules for Objective-C pointer types
3052 // that we do for C++ pointers to class types. However, we employ the
3053 // Objective-C pseudo-subtyping relationship used for assignment of
3054 // Objective-C pointer types.
3055 bool FromAssignLeft
3056 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3057 bool FromAssignRight
3058 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3059 bool ToAssignLeft
3060 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3061 bool ToAssignRight
3062 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3063
3064 // A conversion to an a non-id object pointer type or qualified 'id'
3065 // type is better than a conversion to 'id'.
3066 if (ToPtr1->isObjCIdType() &&
3067 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3068 return ImplicitConversionSequence::Worse;
3069 if (ToPtr2->isObjCIdType() &&
3070 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3071 return ImplicitConversionSequence::Better;
3072
3073 // A conversion to a non-id object pointer type is better than a
3074 // conversion to a qualified 'id' type
3075 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3076 return ImplicitConversionSequence::Worse;
3077 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3078 return ImplicitConversionSequence::Better;
3079
3080 // A conversion to an a non-Class object pointer type or qualified 'Class'
3081 // type is better than a conversion to 'Class'.
3082 if (ToPtr1->isObjCClassType() &&
3083 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3084 return ImplicitConversionSequence::Worse;
3085 if (ToPtr2->isObjCClassType() &&
3086 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3087 return ImplicitConversionSequence::Better;
3088
3089 // A conversion to a non-Class object pointer type is better than a
3090 // conversion to a qualified 'Class' type.
3091 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3092 return ImplicitConversionSequence::Worse;
3093 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3094 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003095
Douglas Gregor058d3de2011-01-31 18:51:41 +00003096 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3097 if (S.Context.hasSameType(FromType1, FromType2) &&
3098 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3099 (ToAssignLeft != ToAssignRight))
3100 return ToAssignLeft? ImplicitConversionSequence::Worse
3101 : ImplicitConversionSequence::Better;
3102
3103 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3104 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3105 (FromAssignLeft != FromAssignRight))
3106 return FromAssignLeft? ImplicitConversionSequence::Better
3107 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003108 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003109 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003110
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003111 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003112 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3113 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3114 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003115 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003116 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003117 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003118 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003119 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003120 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003121 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003122 ToType2->getAs<MemberPointerType>();
3123 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3124 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3125 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3126 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3127 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3128 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3129 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3130 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003131 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003132 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003133 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003134 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003135 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003136 return ImplicitConversionSequence::Better;
3137 }
3138 // conversion of B::* to C::* is better than conversion of A::* to C::*
3139 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003140 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003141 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003142 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003143 return ImplicitConversionSequence::Worse;
3144 }
3145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003146
Douglas Gregor5ab11652010-04-17 22:01:05 +00003147 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003148 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003149 // -- binding of an expression of type C to a reference of type
3150 // B& is better than binding an expression of type C to a
3151 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003152 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3153 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3154 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003155 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003156 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003157 return ImplicitConversionSequence::Worse;
3158 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003159
Douglas Gregor2fe98832008-11-03 19:09:14 +00003160 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003161 // -- binding of an expression of type B to a reference of type
3162 // A& is better than binding an expression of type C to a
3163 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003164 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3165 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3166 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003167 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003168 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003169 return ImplicitConversionSequence::Worse;
3170 }
3171 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003172
Douglas Gregor5c407d92008-10-23 00:40:37 +00003173 return ImplicitConversionSequence::Indistinguishable;
3174}
3175
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003176/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3177/// determine whether they are reference-related,
3178/// reference-compatible, reference-compatible with added
3179/// qualification, or incompatible, for use in C++ initialization by
3180/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3181/// type, and the first type (T1) is the pointee type of the reference
3182/// type being initialized.
3183Sema::ReferenceCompareResult
3184Sema::CompareReferenceRelationship(SourceLocation Loc,
3185 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003186 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003187 bool &ObjCConversion,
3188 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003189 assert(!OrigT1->isReferenceType() &&
3190 "T1 must be the pointee type of the reference type");
3191 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3192
3193 QualType T1 = Context.getCanonicalType(OrigT1);
3194 QualType T2 = Context.getCanonicalType(OrigT2);
3195 Qualifiers T1Quals, T2Quals;
3196 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3197 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3198
3199 // C++ [dcl.init.ref]p4:
3200 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3201 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3202 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003203 DerivedToBase = false;
3204 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003205 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003206 if (UnqualT1 == UnqualT2) {
3207 // Nothing to do.
3208 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003209 IsDerivedFrom(UnqualT2, UnqualT1))
3210 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003211 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3212 UnqualT2->isObjCObjectOrInterfaceType() &&
3213 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3214 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003215 else
3216 return Ref_Incompatible;
3217
3218 // At this point, we know that T1 and T2 are reference-related (at
3219 // least).
3220
3221 // If the type is an array type, promote the element qualifiers to the type
3222 // for comparison.
3223 if (isa<ArrayType>(T1) && T1Quals)
3224 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3225 if (isa<ArrayType>(T2) && T2Quals)
3226 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3227
3228 // C++ [dcl.init.ref]p4:
3229 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3230 // reference-related to T2 and cv1 is the same cv-qualification
3231 // as, or greater cv-qualification than, cv2. For purposes of
3232 // overload resolution, cases for which cv1 is greater
3233 // cv-qualification than cv2 are identified as
3234 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003235 //
3236 // Note that we also require equivalence of Objective-C GC and address-space
3237 // qualifiers when performing these computations, so that e.g., an int in
3238 // address space 1 is not reference-compatible with an int in address
3239 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003240 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3241 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3242 T1Quals.removeObjCLifetime();
3243 T2Quals.removeObjCLifetime();
3244 ObjCLifetimeConversion = true;
3245 }
3246
Douglas Gregord517d552011-04-28 17:56:11 +00003247 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003248 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003249 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003250 return Ref_Compatible_With_Added_Qualification;
3251 else
3252 return Ref_Related;
3253}
3254
Douglas Gregor836a7e82010-08-11 02:15:33 +00003255/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003256/// with DeclType. Return true if something definite is found.
3257static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003258FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3259 QualType DeclType, SourceLocation DeclLoc,
3260 Expr *Init, QualType T2, bool AllowRvalues,
3261 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003262 assert(T2->isRecordType() && "Can only find conversions of record types.");
3263 CXXRecordDecl *T2RecordDecl
3264 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3265
3266 OverloadCandidateSet CandidateSet(DeclLoc);
3267 const UnresolvedSetImpl *Conversions
3268 = T2RecordDecl->getVisibleConversionFunctions();
3269 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3270 E = Conversions->end(); I != E; ++I) {
3271 NamedDecl *D = *I;
3272 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3273 if (isa<UsingShadowDecl>(D))
3274 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3275
3276 FunctionTemplateDecl *ConvTemplate
3277 = dyn_cast<FunctionTemplateDecl>(D);
3278 CXXConversionDecl *Conv;
3279 if (ConvTemplate)
3280 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3281 else
3282 Conv = cast<CXXConversionDecl>(D);
3283
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003284 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003285 // explicit conversions, skip it.
3286 if (!AllowExplicit && Conv->isExplicit())
3287 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003288
Douglas Gregor836a7e82010-08-11 02:15:33 +00003289 if (AllowRvalues) {
3290 bool DerivedToBase = false;
3291 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003292 bool ObjCLifetimeConversion = false;
Douglas Gregor836a7e82010-08-11 02:15:33 +00003293 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003294 S.CompareReferenceRelationship(
3295 DeclLoc,
3296 Conv->getConversionType().getNonReferenceType()
3297 .getUnqualifiedType(),
3298 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003299 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003300 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003301 continue;
3302 } else {
3303 // If the conversion function doesn't return a reference type,
3304 // it can't be considered for this conversion. An rvalue reference
3305 // is only acceptable if its referencee is a function type.
3306
3307 const ReferenceType *RefType =
3308 Conv->getConversionType()->getAs<ReferenceType>();
3309 if (!RefType ||
3310 (!RefType->isLValueReferenceType() &&
3311 !RefType->getPointeeType()->isFunctionType()))
3312 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003313 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003314
Douglas Gregor836a7e82010-08-11 02:15:33 +00003315 if (ConvTemplate)
3316 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003317 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003318 else
3319 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003320 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003321 }
3322
3323 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003324 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003325 case OR_Success:
3326 // C++ [over.ics.ref]p1:
3327 //
3328 // [...] If the parameter binds directly to the result of
3329 // applying a conversion function to the argument
3330 // expression, the implicit conversion sequence is a
3331 // user-defined conversion sequence (13.3.3.1.2), with the
3332 // second standard conversion sequence either an identity
3333 // conversion or, if the conversion function returns an
3334 // entity of a type that is a derived class of the parameter
3335 // type, a derived-to-base Conversion.
3336 if (!Best->FinalConversion.DirectBinding)
3337 return false;
3338
Chandler Carruth30141632011-02-25 19:41:05 +00003339 if (Best->Function)
3340 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003341 ICS.setUserDefined();
3342 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3343 ICS.UserDefined.After = Best->FinalConversion;
3344 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003345 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redld92badf2010-06-30 18:13:39 +00003346 ICS.UserDefined.EllipsisConversion = false;
3347 assert(ICS.UserDefined.After.ReferenceBinding &&
3348 ICS.UserDefined.After.DirectBinding &&
3349 "Expected a direct reference binding!");
3350 return true;
3351
3352 case OR_Ambiguous:
3353 ICS.setAmbiguous();
3354 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3355 Cand != CandidateSet.end(); ++Cand)
3356 if (Cand->Viable)
3357 ICS.Ambiguous.addConversion(Cand->Function);
3358 return true;
3359
3360 case OR_No_Viable_Function:
3361 case OR_Deleted:
3362 // There was no suitable conversion, or we found a deleted
3363 // conversion; continue with other checks.
3364 return false;
3365 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003366
Eric Christopheraba9fb22010-06-30 18:36:32 +00003367 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003368}
3369
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003370/// \brief Compute an implicit conversion sequence for reference
3371/// initialization.
3372static ImplicitConversionSequence
3373TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3374 SourceLocation DeclLoc,
3375 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003376 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003377 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3378
3379 // Most paths end in a failed conversion.
3380 ImplicitConversionSequence ICS;
3381 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3382
3383 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3384 QualType T2 = Init->getType();
3385
3386 // If the initializer is the address of an overloaded function, try
3387 // to resolve the overloaded function. If all goes well, T2 is the
3388 // type of the resulting function.
3389 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3390 DeclAccessPair Found;
3391 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3392 false, Found))
3393 T2 = Fn->getType();
3394 }
3395
3396 // Compute some basic properties of the types and the initializer.
3397 bool isRValRef = DeclType->isRValueReferenceType();
3398 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003399 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003400 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003401 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003402 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003403 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003404 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003405
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003406
Sebastian Redld92badf2010-06-30 18:13:39 +00003407 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003408 // A reference to type "cv1 T1" is initialized by an expression
3409 // of type "cv2 T2" as follows:
3410
Sebastian Redld92badf2010-06-30 18:13:39 +00003411 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003412 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003413 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3414 // reference-compatible with "cv2 T2," or
3415 //
3416 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3417 if (InitCategory.isLValue() &&
3418 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003419 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003420 // When a parameter of reference type binds directly (8.5.3)
3421 // to an argument expression, the implicit conversion sequence
3422 // is the identity conversion, unless the argument expression
3423 // has a type that is a derived class of the parameter type,
3424 // in which case the implicit conversion sequence is a
3425 // derived-to-base Conversion (13.3.3.1).
3426 ICS.setStandard();
3427 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003428 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3429 : ObjCConversion? ICK_Compatible_Conversion
3430 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003431 ICS.Standard.Third = ICK_Identity;
3432 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3433 ICS.Standard.setToType(0, T2);
3434 ICS.Standard.setToType(1, T1);
3435 ICS.Standard.setToType(2, T1);
3436 ICS.Standard.ReferenceBinding = true;
3437 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003438 ICS.Standard.IsLvalueReference = !isRValRef;
3439 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3440 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003441 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003442 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003443 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003444
Sebastian Redld92badf2010-06-30 18:13:39 +00003445 // Nothing more to do: the inaccessibility/ambiguity check for
3446 // derived-to-base conversions is suppressed when we're
3447 // computing the implicit conversion sequence (C++
3448 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003449 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003450 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003451
Sebastian Redld92badf2010-06-30 18:13:39 +00003452 // -- has a class type (i.e., T2 is a class type), where T1 is
3453 // not reference-related to T2, and can be implicitly
3454 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3455 // is reference-compatible with "cv3 T3" 92) (this
3456 // conversion is selected by enumerating the applicable
3457 // conversion functions (13.3.1.6) and choosing the best
3458 // one through overload resolution (13.3)),
3459 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003460 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003461 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003462 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3463 Init, T2, /*AllowRvalues=*/false,
3464 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003465 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003466 }
3467 }
3468
Sebastian Redld92badf2010-06-30 18:13:39 +00003469 // -- Otherwise, the reference shall be an lvalue reference to a
3470 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003471 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003472 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003473 // We actually handle one oddity of C++ [over.ics.ref] at this
3474 // point, which is that, due to p2 (which short-circuits reference
3475 // binding by only attempting a simple conversion for non-direct
3476 // bindings) and p3's strange wording, we allow a const volatile
3477 // reference to bind to an rvalue. Hence the check for the presence
3478 // of "const" rather than checking for "const" being the only
3479 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003480 // This is also the point where rvalue references and lvalue inits no longer
3481 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003482 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003483 return ICS;
3484
Douglas Gregorf143cd52011-01-24 16:14:37 +00003485 // -- If the initializer expression
3486 //
3487 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003488 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003489 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3490 (InitCategory.isXValue() ||
3491 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3492 (InitCategory.isLValue() && T2->isFunctionType()))) {
3493 ICS.setStandard();
3494 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003495 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003496 : ObjCConversion? ICK_Compatible_Conversion
3497 : ICK_Identity;
3498 ICS.Standard.Third = ICK_Identity;
3499 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3500 ICS.Standard.setToType(0, T2);
3501 ICS.Standard.setToType(1, T1);
3502 ICS.Standard.setToType(2, T1);
3503 ICS.Standard.ReferenceBinding = true;
3504 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3505 // binding unless we're binding to a class prvalue.
3506 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3507 // allow the use of rvalue references in C++98/03 for the benefit of
3508 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003509 ICS.Standard.DirectBinding =
3510 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003511 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003512 ICS.Standard.IsLvalueReference = !isRValRef;
3513 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003514 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003515 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003516 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003517 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003518 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003519 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003520
Douglas Gregorf143cd52011-01-24 16:14:37 +00003521 // -- has a class type (i.e., T2 is a class type), where T1 is not
3522 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003523 // an xvalue, class prvalue, or function lvalue of type
3524 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003525 // "cv3 T3",
3526 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003527 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003528 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003529 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003530 // class subobject).
3531 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003532 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003533 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3534 Init, T2, /*AllowRvalues=*/true,
3535 AllowExplicit)) {
3536 // In the second case, if the reference is an rvalue reference
3537 // and the second standard conversion sequence of the
3538 // user-defined conversion sequence includes an lvalue-to-rvalue
3539 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003540 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003541 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3542 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3543
Douglas Gregor95273c32011-01-21 16:36:05 +00003544 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003545 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003546
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003547 // -- Otherwise, a temporary of type "cv1 T1" is created and
3548 // initialized from the initializer expression using the
3549 // rules for a non-reference copy initialization (8.5). The
3550 // reference is then bound to the temporary. If T1 is
3551 // reference-related to T2, cv1 must be the same
3552 // cv-qualification as, or greater cv-qualification than,
3553 // cv2; otherwise, the program is ill-formed.
3554 if (RefRelationship == Sema::Ref_Related) {
3555 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3556 // we would be reference-compatible or reference-compatible with
3557 // added qualification. But that wasn't the case, so the reference
3558 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00003559 //
3560 // Note that we only want to check address spaces and cvr-qualifiers here.
3561 // ObjC GC and lifetime qualifiers aren't important.
3562 Qualifiers T1Quals = T1.getQualifiers();
3563 Qualifiers T2Quals = T2.getQualifiers();
3564 T1Quals.removeObjCGCAttr();
3565 T1Quals.removeObjCLifetime();
3566 T2Quals.removeObjCGCAttr();
3567 T2Quals.removeObjCLifetime();
3568 if (!T1Quals.compatiblyIncludes(T2Quals))
3569 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003570 }
3571
3572 // If at least one of the types is a class type, the types are not
3573 // related, and we aren't allowed any user conversions, the
3574 // reference binding fails. This case is important for breaking
3575 // recursion, since TryImplicitConversion below will attempt to
3576 // create a temporary through the use of a copy constructor.
3577 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3578 (T1->isRecordType() || T2->isRecordType()))
3579 return ICS;
3580
Douglas Gregorcba72b12011-01-21 05:18:22 +00003581 // If T1 is reference-related to T2 and the reference is an rvalue
3582 // reference, the initializer expression shall not be an lvalue.
3583 if (RefRelationship >= Sema::Ref_Related &&
3584 isRValRef && Init->Classify(S.Context).isLValue())
3585 return ICS;
3586
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003587 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003588 // When a parameter of reference type is not bound directly to
3589 // an argument expression, the conversion sequence is the one
3590 // required to convert the argument expression to the
3591 // underlying type of the reference according to
3592 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3593 // to copy-initializing a temporary of the underlying type with
3594 // the argument expression. Any difference in top-level
3595 // cv-qualification is subsumed by the initialization itself
3596 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003597 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3598 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003599 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003600 /*CStyle=*/false,
3601 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003602
3603 // Of course, that's still a reference binding.
3604 if (ICS.isStandard()) {
3605 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003606 ICS.Standard.IsLvalueReference = !isRValRef;
3607 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3608 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003609 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003610 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003611 } else if (ICS.isUserDefined()) {
3612 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003613 ICS.Standard.IsLvalueReference = !isRValRef;
3614 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3615 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003616 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003617 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003618 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003619
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003620 return ICS;
3621}
3622
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003623/// TryCopyInitialization - Try to copy-initialize a value of type
3624/// ToType from the expression From. Return the implicit conversion
3625/// sequence required to pass this argument, which may be a bad
3626/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003627/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003628/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003629static ImplicitConversionSequence
3630TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003631 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00003632 bool InOverloadResolution,
3633 bool AllowObjCWritebackConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003634 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003635 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003636 /*FIXME:*/From->getLocStart(),
3637 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003638 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003639
John McCall5c32be02010-08-24 20:38:10 +00003640 return TryImplicitConversion(S, From, ToType,
3641 SuppressUserConversions,
3642 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003643 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00003644 /*CStyle=*/false,
3645 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003646}
3647
Douglas Gregor436424c2008-11-18 23:14:02 +00003648/// TryObjectArgumentInitialization - Try to initialize the object
3649/// parameter of the given member function (@c Method) from the
3650/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003651static ImplicitConversionSequence
3652TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003653 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003654 CXXMethodDecl *Method,
3655 CXXRecordDecl *ActingContext) {
3656 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003657 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3658 // const volatile object.
3659 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3660 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003661 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003662
3663 // Set up the conversion sequence as a "bad" conversion, to allow us
3664 // to exit early.
3665 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003666
3667 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003668 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003669 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003670 FromType = PT->getPointeeType();
3671
Douglas Gregor02824322011-01-26 19:30:28 +00003672 // When we had a pointer, it's implicitly dereferenced, so we
3673 // better have an lvalue.
3674 assert(FromClassification.isLValue());
3675 }
3676
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003677 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003678
Douglas Gregor02824322011-01-26 19:30:28 +00003679 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003680 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003681 // parameter is
3682 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003683 // - "lvalue reference to cv X" for functions declared without a
3684 // ref-qualifier or with the & ref-qualifier
3685 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003686 // ref-qualifier
3687 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003688 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003689 // cv-qualification on the member function declaration.
3690 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003691 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003692 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003693 // (C++ [over.match.funcs]p5). We perform a simplified version of
3694 // reference binding here, that allows class rvalues to bind to
3695 // non-constant references.
3696
Douglas Gregor02824322011-01-26 19:30:28 +00003697 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003698 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003699 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003700 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003701 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003702 ICS.setBad(BadConversionSequence::bad_qualifiers,
3703 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003704 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003705 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003706
3707 // Check that we have either the same type or a derived type. It
3708 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003709 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003710 ImplicitConversionKind SecondKind;
3711 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3712 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003713 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003714 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003715 else {
John McCall65eb8792010-02-25 01:37:24 +00003716 ICS.setBad(BadConversionSequence::unrelated_class,
3717 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003718 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003719 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003720
Douglas Gregor02824322011-01-26 19:30:28 +00003721 // Check the ref-qualifier.
3722 switch (Method->getRefQualifier()) {
3723 case RQ_None:
3724 // Do nothing; we don't care about lvalueness or rvalueness.
3725 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003726
Douglas Gregor02824322011-01-26 19:30:28 +00003727 case RQ_LValue:
3728 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3729 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003730 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003731 ImplicitParamType);
3732 return ICS;
3733 }
3734 break;
3735
3736 case RQ_RValue:
3737 if (!FromClassification.isRValue()) {
3738 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003739 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003740 ImplicitParamType);
3741 return ICS;
3742 }
3743 break;
3744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003745
Douglas Gregor436424c2008-11-18 23:14:02 +00003746 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003747 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003748 ICS.Standard.setAsIdentityConversion();
3749 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003750 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003751 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003752 ICS.Standard.ReferenceBinding = true;
3753 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003754 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003755 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003756 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3757 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3758 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00003759 return ICS;
3760}
3761
3762/// PerformObjectArgumentInitialization - Perform initialization of
3763/// the implicit object parameter for the given Method with the given
3764/// expression.
John Wiegley01296292011-04-08 18:41:53 +00003765ExprResult
3766Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003767 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003768 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003769 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003770 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003771 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003772 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003773
Douglas Gregor02824322011-01-26 19:30:28 +00003774 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003775 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003776 FromRecordType = PT->getPointeeType();
3777 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003778 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003779 } else {
3780 FromRecordType = From->getType();
3781 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003782 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003783 }
3784
John McCall6e9f8f62009-12-03 04:06:58 +00003785 // Note that we always use the true parent context when performing
3786 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003787 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003788 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3789 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003790 if (ICS.isBad()) {
3791 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3792 Qualifiers FromQs = FromRecordType.getQualifiers();
3793 Qualifiers ToQs = DestType.getQualifiers();
3794 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3795 if (CVR) {
3796 Diag(From->getSourceRange().getBegin(),
3797 diag::err_member_function_call_bad_cvr)
3798 << Method->getDeclName() << FromRecordType << (CVR - 1)
3799 << From->getSourceRange();
3800 Diag(Method->getLocation(), diag::note_previous_decl)
3801 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00003802 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003803 }
3804 }
3805
Douglas Gregor436424c2008-11-18 23:14:02 +00003806 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003807 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003808 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003809 }
Mike Stump11289f42009-09-09 15:08:12 +00003810
John Wiegley01296292011-04-08 18:41:53 +00003811 if (ICS.Standard.Second == ICK_Derived_To_Base) {
3812 ExprResult FromRes =
3813 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3814 if (FromRes.isInvalid())
3815 return ExprError();
3816 From = FromRes.take();
3817 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003818
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003819 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00003820 From = ImpCastExprToType(From, DestType, CK_NoOp,
3821 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3822 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00003823}
3824
Douglas Gregor5fb53972009-01-14 15:45:31 +00003825/// TryContextuallyConvertToBool - Attempt to contextually convert the
3826/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003827static ImplicitConversionSequence
3828TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003829 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003830 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003831 // FIXME: Are these flags correct?
3832 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003833 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003834 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003835 /*CStyle=*/false,
3836 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003837}
3838
3839/// PerformContextuallyConvertToBool - Perform a contextual conversion
3840/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00003841ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00003842 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003843 if (!ICS.isBad())
3844 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003845
Fariborz Jahanian76197412009-11-18 18:26:29 +00003846 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00003847 return Diag(From->getSourceRange().getBegin(),
3848 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003849 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003850 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00003851}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003852
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003853/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3854/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003855static ImplicitConversionSequence
3856TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3857 QualType Ty = S.Context.getObjCIdType();
3858 return TryImplicitConversion(S, From, Ty,
3859 // FIXME: Are these flags correct?
3860 /*SuppressUserConversions=*/false,
3861 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003862 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003863 /*CStyle=*/false,
3864 /*AllowObjCWritebackConversion=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003865}
John McCall5c32be02010-08-24 20:38:10 +00003866
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003867/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3868/// of the expression From to 'id'.
John Wiegley01296292011-04-08 18:41:53 +00003869ExprResult Sema::PerformContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003870 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003871 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003872 if (!ICS.isBad())
3873 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00003874 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003875}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003876
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003877/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003878/// enumeration type.
3879///
3880/// This routine will attempt to convert an expression of class type to an
3881/// integral or enumeration type, if that class type only has a single
3882/// conversion to an integral or enumeration type.
3883///
Douglas Gregor4799d032010-06-30 00:20:43 +00003884/// \param Loc The source location of the construct that requires the
3885/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003886///
Douglas Gregor4799d032010-06-30 00:20:43 +00003887/// \param FromE The expression we're converting from.
3888///
3889/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3890/// have integral or enumeration type.
3891///
3892/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3893/// incomplete class type.
3894///
3895/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3896/// explicit conversion function (because no implicit conversion functions
3897/// were available). This is a recovery mode.
3898///
3899/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3900/// showing which conversion was picked.
3901///
3902/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3903/// conversion function that could convert to integral or enumeration type.
3904///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003905/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00003906/// usable conversion function.
3907///
3908/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3909/// function, which may be an extension in this case.
3910///
3911/// \returns The expression, converted to an integral or enumeration type if
3912/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003913ExprResult
John McCallb268a282010-08-23 23:25:46 +00003914Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003915 const PartialDiagnostic &NotIntDiag,
3916 const PartialDiagnostic &IncompleteDiag,
3917 const PartialDiagnostic &ExplicitConvDiag,
3918 const PartialDiagnostic &ExplicitConvNote,
3919 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003920 const PartialDiagnostic &AmbigNote,
3921 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003922 // We can't perform any more checking for type-dependent expressions.
3923 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003924 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003925
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003926 // If the expression already has integral or enumeration type, we're golden.
3927 QualType T = From->getType();
3928 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003929 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003930
3931 // FIXME: Check for missing '()' if T is a function type?
3932
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003933 // If we don't have a class type in C++, there's no way we can get an
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003934 // expression of integral or enumeration type.
3935 const RecordType *RecordTy = T->getAs<RecordType>();
3936 if (!RecordTy || !getLangOptions().CPlusPlus) {
3937 Diag(Loc, NotIntDiag)
3938 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003939 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003940 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003941
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003942 // We must have a complete class type.
3943 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003944 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003945
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003946 // Look for a conversion to an integral or enumeration type.
3947 UnresolvedSet<4> ViableConversions;
3948 UnresolvedSet<4> ExplicitConversions;
3949 const UnresolvedSetImpl *Conversions
3950 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003951
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003952 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003953 E = Conversions->end();
3954 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003955 ++I) {
3956 if (CXXConversionDecl *Conversion
3957 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3958 if (Conversion->getConversionType().getNonReferenceType()
3959 ->isIntegralOrEnumerationType()) {
3960 if (Conversion->isExplicit())
3961 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3962 else
3963 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3964 }
3965 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003966
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003967 switch (ViableConversions.size()) {
3968 case 0:
3969 if (ExplicitConversions.size() == 1) {
3970 DeclAccessPair Found = ExplicitConversions[0];
3971 CXXConversionDecl *Conversion
3972 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003973
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003974 // The user probably meant to invoke the given explicit
3975 // conversion; use it.
3976 QualType ConvTy
3977 = Conversion->getConversionType().getNonReferenceType();
3978 std::string TypeStr;
3979 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003980
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003981 Diag(Loc, ExplicitConvDiag)
3982 << T << ConvTy
3983 << FixItHint::CreateInsertion(From->getLocStart(),
3984 "static_cast<" + TypeStr + ">(")
3985 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3986 ")");
3987 Diag(Conversion->getLocation(), ExplicitConvNote)
3988 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003989
3990 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003991 // explicit conversion function.
3992 if (isSFINAEContext())
3993 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003994
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003995 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00003996 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3997 if (Result.isInvalid())
3998 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003999
Douglas Gregor668443e2011-01-20 00:18:04 +00004000 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004002
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004003 // We'll complain below about a non-integral condition type.
4004 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004005
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004006 case 1: {
4007 // Apply this conversion.
4008 DeclAccessPair Found = ViableConversions[0];
4009 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004010
Douglas Gregor4799d032010-06-30 00:20:43 +00004011 CXXConversionDecl *Conversion
4012 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4013 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004014 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004015 if (ConvDiag.getDiagID()) {
4016 if (isSFINAEContext())
4017 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004018
Douglas Gregor4799d032010-06-30 00:20:43 +00004019 Diag(Loc, ConvDiag)
4020 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4021 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004022
Douglas Gregor668443e2011-01-20 00:18:04 +00004023 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004024 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00004025 if (Result.isInvalid())
4026 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004027
Douglas Gregor668443e2011-01-20 00:18:04 +00004028 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004029 break;
4030 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004031
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004032 default:
4033 Diag(Loc, AmbigDiag)
4034 << T << From->getSourceRange();
4035 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4036 CXXConversionDecl *Conv
4037 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4038 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4039 Diag(Conv->getLocation(), AmbigNote)
4040 << ConvTy->isEnumeralType() << ConvTy;
4041 }
John McCallb268a282010-08-23 23:25:46 +00004042 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004044
Douglas Gregor5823da32010-06-29 23:25:20 +00004045 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004046 Diag(Loc, NotIntDiag)
4047 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004048
John McCallb268a282010-08-23 23:25:46 +00004049 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004050}
4051
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004052/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004053/// candidate functions, using the given function call arguments. If
4054/// @p SuppressUserConversions, then don't allow user-defined
4055/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004056///
4057/// \para PartialOverloading true if we are performing "partial" overloading
4058/// based on an incomplete set of function arguments. This feature is used by
4059/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004060void
4061Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004062 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004063 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004064 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004065 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004066 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004067 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004068 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004069 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004070 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004071 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004072
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004073 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004074 if (!isa<CXXConstructorDecl>(Method)) {
4075 // If we get here, it's because we're calling a member function
4076 // that is named without a member access expression (e.g.,
4077 // "this->f") that was either written explicitly or created
4078 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004079 // function, e.g., X::f(). We use an empty type for the implied
4080 // object argument (C++ [over.call.func]p3), and the acting context
4081 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004082 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004083 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004084 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004085 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004086 return;
4087 }
4088 // We treat a constructor like a non-member function, since its object
4089 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004090 }
4091
Douglas Gregorff7028a2009-11-13 23:59:09 +00004092 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004093 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004094
Douglas Gregor27381f32009-11-23 12:27:39 +00004095 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004096 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004097
Douglas Gregorffe14e32009-11-14 01:20:54 +00004098 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4099 // C++ [class.copy]p3:
4100 // A member function template is never instantiated to perform the copy
4101 // of a class object to an object of its class type.
4102 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004103 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004104 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004105 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4106 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004107 return;
4108 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004109
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004110 // Add this candidate
4111 CandidateSet.push_back(OverloadCandidate());
4112 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004113 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004114 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004115 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004116 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004117 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004118 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004119
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004120 unsigned NumArgsInProto = Proto->getNumArgs();
4121
4122 // (C++ 13.3.2p2): A candidate function having fewer than m
4123 // parameters is viable only if it has an ellipsis in its parameter
4124 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004125 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004126 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004127 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004128 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004129 return;
4130 }
4131
4132 // (C++ 13.3.2p2): A candidate function having more than m parameters
4133 // is viable only if the (m+1)st parameter has a default argument
4134 // (8.3.6). For the purposes of overload resolution, the
4135 // parameter list is truncated on the right, so that there are
4136 // exactly m parameters.
4137 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004138 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004139 // Not enough arguments.
4140 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004141 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004142 return;
4143 }
4144
4145 // Determine the implicit conversion sequences for each of the
4146 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004147 Candidate.Conversions.resize(NumArgs);
4148 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4149 if (ArgIdx < NumArgsInProto) {
4150 // (C++ 13.3.2p3): for F to be a viable function, there shall
4151 // exist for each argument an implicit conversion sequence
4152 // (13.3.3.1) that converts that argument to the corresponding
4153 // parameter of F.
4154 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004155 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004156 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004157 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004158 /*InOverloadResolution=*/true,
4159 /*AllowObjCWritebackConversion=*/
4160 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004161 if (Candidate.Conversions[ArgIdx].isBad()) {
4162 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004163 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004164 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004165 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004166 } else {
4167 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4168 // argument for which there is no corresponding parameter is
4169 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004170 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004171 }
4172 }
4173}
4174
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004175/// \brief Add all of the function declarations in the given function set to
4176/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004177void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004178 Expr **Args, unsigned NumArgs,
4179 OverloadCandidateSet& CandidateSet,
4180 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004181 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004182 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4183 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004184 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004185 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004186 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004187 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004188 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004189 CandidateSet, SuppressUserConversions);
4190 else
John McCalla0296f72010-03-19 07:35:19 +00004191 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004192 SuppressUserConversions);
4193 } else {
John McCalla0296f72010-03-19 07:35:19 +00004194 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004195 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4196 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004197 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004198 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004199 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004200 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004201 Args[0]->Classify(Context),
4202 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004203 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004204 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004205 else
John McCalla0296f72010-03-19 07:35:19 +00004206 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004207 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004208 Args, NumArgs, CandidateSet,
4209 SuppressUserConversions);
4210 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004211 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004212}
4213
John McCallf0f1cf02009-11-17 07:50:12 +00004214/// AddMethodCandidate - Adds a named decl (which is some kind of
4215/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004216void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004217 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004218 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004219 Expr **Args, unsigned NumArgs,
4220 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004221 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004222 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004223 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004224
4225 if (isa<UsingShadowDecl>(Decl))
4226 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004227
John McCallf0f1cf02009-11-17 07:50:12 +00004228 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4229 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4230 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004231 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4232 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004233 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004234 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004235 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004236 } else {
John McCalla0296f72010-03-19 07:35:19 +00004237 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004238 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004239 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004240 }
4241}
4242
Douglas Gregor436424c2008-11-18 23:14:02 +00004243/// AddMethodCandidate - Adds the given C++ member function to the set
4244/// of candidate functions, using the given function call arguments
4245/// and the object argument (@c Object). For example, in a call
4246/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4247/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4248/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004249/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004250void
John McCalla0296f72010-03-19 07:35:19 +00004251Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004252 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004253 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004254 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004255 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004256 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004257 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004258 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004259 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004260 assert(!isa<CXXConstructorDecl>(Method) &&
4261 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004262
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004263 if (!CandidateSet.isNewCandidate(Method))
4264 return;
4265
Douglas Gregor27381f32009-11-23 12:27:39 +00004266 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004267 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004268
Douglas Gregor436424c2008-11-18 23:14:02 +00004269 // Add this candidate
4270 CandidateSet.push_back(OverloadCandidate());
4271 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004272 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004273 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004274 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004275 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004276 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004277
4278 unsigned NumArgsInProto = Proto->getNumArgs();
4279
4280 // (C++ 13.3.2p2): A candidate function having fewer than m
4281 // parameters is viable only if it has an ellipsis in its parameter
4282 // list (8.3.5).
4283 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4284 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004285 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004286 return;
4287 }
4288
4289 // (C++ 13.3.2p2): A candidate function having more than m parameters
4290 // is viable only if the (m+1)st parameter has a default argument
4291 // (8.3.6). For the purposes of overload resolution, the
4292 // parameter list is truncated on the right, so that there are
4293 // exactly m parameters.
4294 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4295 if (NumArgs < MinRequiredArgs) {
4296 // Not enough arguments.
4297 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004298 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004299 return;
4300 }
4301
4302 Candidate.Viable = true;
4303 Candidate.Conversions.resize(NumArgs + 1);
4304
John McCall6e9f8f62009-12-03 04:06:58 +00004305 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004306 // The implicit object argument is ignored.
4307 Candidate.IgnoreObjectArgument = true;
4308 else {
4309 // Determine the implicit conversion sequence for the object
4310 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004311 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004312 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4313 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004314 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004315 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004316 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004317 return;
4318 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004319 }
4320
4321 // Determine the implicit conversion sequences for each of the
4322 // arguments.
4323 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4324 if (ArgIdx < NumArgsInProto) {
4325 // (C++ 13.3.2p3): for F to be a viable function, there shall
4326 // exist for each argument an implicit conversion sequence
4327 // (13.3.3.1) that converts that argument to the corresponding
4328 // parameter of F.
4329 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004330 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004331 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004332 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004333 /*InOverloadResolution=*/true,
4334 /*AllowObjCWritebackConversion=*/
4335 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004336 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004337 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004338 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004339 break;
4340 }
4341 } else {
4342 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4343 // argument for which there is no corresponding parameter is
4344 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004345 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004346 }
4347 }
4348}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004349
Douglas Gregor97628d62009-08-21 00:16:32 +00004350/// \brief Add a C++ member function template as a candidate to the candidate
4351/// set, using template argument deduction to produce an appropriate member
4352/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004353void
Douglas Gregor97628d62009-08-21 00:16:32 +00004354Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004355 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004356 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004357 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004358 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004359 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004360 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004361 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004362 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004363 if (!CandidateSet.isNewCandidate(MethodTmpl))
4364 return;
4365
Douglas Gregor97628d62009-08-21 00:16:32 +00004366 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004367 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004368 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004369 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004370 // candidate functions in the usual way.113) A given name can refer to one
4371 // or more function templates and also to a set of overloaded non-template
4372 // functions. In such a case, the candidate functions generated from each
4373 // function template are combined with the set of non-template candidate
4374 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004375 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004376 FunctionDecl *Specialization = 0;
4377 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004378 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004379 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004380 CandidateSet.push_back(OverloadCandidate());
4381 OverloadCandidate &Candidate = CandidateSet.back();
4382 Candidate.FoundDecl = FoundDecl;
4383 Candidate.Function = MethodTmpl->getTemplatedDecl();
4384 Candidate.Viable = false;
4385 Candidate.FailureKind = ovl_fail_bad_deduction;
4386 Candidate.IsSurrogate = false;
4387 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004388 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004389 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004390 Info);
4391 return;
4392 }
Mike Stump11289f42009-09-09 15:08:12 +00004393
Douglas Gregor97628d62009-08-21 00:16:32 +00004394 // Add the function template specialization produced by template argument
4395 // deduction as a candidate.
4396 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004397 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004398 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004399 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004400 ActingContext, ObjectType, ObjectClassification,
4401 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004402}
4403
Douglas Gregor05155d82009-08-21 23:19:43 +00004404/// \brief Add a C++ function template specialization as a candidate
4405/// in the candidate set, using template argument deduction to produce
4406/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004407void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004408Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004409 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004410 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004411 Expr **Args, unsigned NumArgs,
4412 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004413 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004414 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4415 return;
4416
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004417 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004418 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004419 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004420 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004421 // candidate functions in the usual way.113) A given name can refer to one
4422 // or more function templates and also to a set of overloaded non-template
4423 // functions. In such a case, the candidate functions generated from each
4424 // function template are combined with the set of non-template candidate
4425 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004426 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004427 FunctionDecl *Specialization = 0;
4428 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004429 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004430 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004431 CandidateSet.push_back(OverloadCandidate());
4432 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004433 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004434 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4435 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004436 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004437 Candidate.IsSurrogate = false;
4438 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004439 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004440 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004441 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004442 return;
4443 }
Mike Stump11289f42009-09-09 15:08:12 +00004444
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004445 // Add the function template specialization produced by template argument
4446 // deduction as a candidate.
4447 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004448 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004449 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004450}
Mike Stump11289f42009-09-09 15:08:12 +00004451
Douglas Gregora1f013e2008-11-07 22:36:19 +00004452/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004453/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004454/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004455/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004456/// (which may or may not be the same type as the type that the
4457/// conversion function produces).
4458void
4459Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004460 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004461 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004462 Expr *From, QualType ToType,
4463 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004464 assert(!Conversion->getDescribedFunctionTemplate() &&
4465 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004466 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004467 if (!CandidateSet.isNewCandidate(Conversion))
4468 return;
4469
Douglas Gregor27381f32009-11-23 12:27:39 +00004470 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004471 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004472
Douglas Gregora1f013e2008-11-07 22:36:19 +00004473 // Add this candidate
4474 CandidateSet.push_back(OverloadCandidate());
4475 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004476 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004477 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004478 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004479 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004480 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004481 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004482 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004483 Candidate.Viable = true;
4484 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004485 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004486
Douglas Gregor6affc782010-08-19 15:37:02 +00004487 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004488 // For conversion functions, the function is considered to be a member of
4489 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004490 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004491 //
4492 // Determine the implicit conversion sequence for the implicit
4493 // object parameter.
4494 QualType ImplicitParamType = From->getType();
4495 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4496 ImplicitParamType = FromPtrType->getPointeeType();
4497 CXXRecordDecl *ConversionContext
4498 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004499
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004500 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004501 = TryObjectArgumentInitialization(*this, From->getType(),
4502 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004503 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004504
John McCall0d1da222010-01-12 00:44:57 +00004505 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004506 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004507 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004508 return;
4509 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004510
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004511 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004512 // derived to base as such conversions are given Conversion Rank. They only
4513 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4514 QualType FromCanon
4515 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4516 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4517 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4518 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004519 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004520 return;
4521 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004522
Douglas Gregora1f013e2008-11-07 22:36:19 +00004523 // To determine what the conversion from the result of calling the
4524 // conversion function to the type we're eventually trying to
4525 // convert to (ToType), we need to synthesize a call to the
4526 // conversion function and attempt copy initialization from it. This
4527 // makes sure that we get the right semantics with respect to
4528 // lvalues/rvalues and the type. Fortunately, we can allocate this
4529 // call on the stack and we don't need its arguments to be
4530 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004531 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004532 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004533 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4534 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004535 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004536 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004537
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004538 QualType CallResultType
4539 = Conversion->getConversionType().getNonLValueExprType(Context);
4540 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4541 Candidate.Viable = false;
4542 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4543 return;
4544 }
4545
John McCall7decc9e2010-11-18 06:31:45 +00004546 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4547
Mike Stump11289f42009-09-09 15:08:12 +00004548 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004549 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4550 // allocator).
John McCall7decc9e2010-11-18 06:31:45 +00004551 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004552 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004553 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004554 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004555 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00004556 /*InOverloadResolution=*/false,
4557 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004558
John McCall0d1da222010-01-12 00:44:57 +00004559 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004560 case ImplicitConversionSequence::StandardConversion:
4561 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004562
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004563 // C++ [over.ics.user]p3:
4564 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004565 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004566 // shall have exact match rank.
4567 if (Conversion->getPrimaryTemplate() &&
4568 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4569 Candidate.Viable = false;
4570 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4571 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004572
Douglas Gregorcba72b12011-01-21 05:18:22 +00004573 // C++0x [dcl.init.ref]p5:
4574 // In the second case, if the reference is an rvalue reference and
4575 // the second standard conversion sequence of the user-defined
4576 // conversion sequence includes an lvalue-to-rvalue conversion, the
4577 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004578 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004579 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4580 Candidate.Viable = false;
4581 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4582 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004583 break;
4584
4585 case ImplicitConversionSequence::BadConversion:
4586 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004587 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004588 break;
4589
4590 default:
Mike Stump11289f42009-09-09 15:08:12 +00004591 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004592 "Can only end up with a standard conversion sequence or failure");
4593 }
4594}
4595
Douglas Gregor05155d82009-08-21 23:19:43 +00004596/// \brief Adds a conversion function template specialization
4597/// candidate to the overload set, using template argument deduction
4598/// to deduce the template arguments of the conversion function
4599/// template from the type that we are converting to (C++
4600/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004601void
Douglas Gregor05155d82009-08-21 23:19:43 +00004602Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004603 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004604 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004605 Expr *From, QualType ToType,
4606 OverloadCandidateSet &CandidateSet) {
4607 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4608 "Only conversion function templates permitted here");
4609
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004610 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4611 return;
4612
John McCallbc077cf2010-02-08 23:07:23 +00004613 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004614 CXXConversionDecl *Specialization = 0;
4615 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004616 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004617 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004618 CandidateSet.push_back(OverloadCandidate());
4619 OverloadCandidate &Candidate = CandidateSet.back();
4620 Candidate.FoundDecl = FoundDecl;
4621 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4622 Candidate.Viable = false;
4623 Candidate.FailureKind = ovl_fail_bad_deduction;
4624 Candidate.IsSurrogate = false;
4625 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004626 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004627 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004628 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004629 return;
4630 }
Mike Stump11289f42009-09-09 15:08:12 +00004631
Douglas Gregor05155d82009-08-21 23:19:43 +00004632 // Add the conversion function template specialization produced by
4633 // template argument deduction as a candidate.
4634 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004635 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004636 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004637}
4638
Douglas Gregorab7897a2008-11-19 22:57:39 +00004639/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4640/// converts the given @c Object to a function pointer via the
4641/// conversion function @c Conversion, and then attempts to call it
4642/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4643/// the type of function that we'll eventually be calling.
4644void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004645 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004646 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004647 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004648 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004649 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004650 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004651 if (!CandidateSet.isNewCandidate(Conversion))
4652 return;
4653
Douglas Gregor27381f32009-11-23 12:27:39 +00004654 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004655 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004656
Douglas Gregorab7897a2008-11-19 22:57:39 +00004657 CandidateSet.push_back(OverloadCandidate());
4658 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004659 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004660 Candidate.Function = 0;
4661 Candidate.Surrogate = Conversion;
4662 Candidate.Viable = true;
4663 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004664 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004665 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004666 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004667
4668 // Determine the implicit conversion sequence for the implicit
4669 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004670 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004671 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004672 Object->Classify(Context),
4673 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004674 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004675 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004676 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004677 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004678 return;
4679 }
4680
4681 // The first conversion is actually a user-defined conversion whose
4682 // first conversion is ObjectInit's standard conversion (which is
4683 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004684 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004685 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004686 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004687 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004688 Candidate.Conversions[0].UserDefined.FoundConversionFunction
Douglas Gregor2bbfba02011-01-20 01:32:05 +00004689 = FoundDecl.getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004690 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004691 = Candidate.Conversions[0].UserDefined.Before;
4692 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4693
Mike Stump11289f42009-09-09 15:08:12 +00004694 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004695 unsigned NumArgsInProto = Proto->getNumArgs();
4696
4697 // (C++ 13.3.2p2): A candidate function having fewer than m
4698 // parameters is viable only if it has an ellipsis in its parameter
4699 // list (8.3.5).
4700 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4701 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004702 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004703 return;
4704 }
4705
4706 // Function types don't have any default arguments, so just check if
4707 // we have enough arguments.
4708 if (NumArgs < NumArgsInProto) {
4709 // Not enough arguments.
4710 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004711 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004712 return;
4713 }
4714
4715 // Determine the implicit conversion sequences for each of the
4716 // arguments.
4717 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4718 if (ArgIdx < NumArgsInProto) {
4719 // (C++ 13.3.2p3): for F to be a viable function, there shall
4720 // exist for each argument an implicit conversion sequence
4721 // (13.3.3.1) that converts that argument to the corresponding
4722 // parameter of F.
4723 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004724 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004725 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004726 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00004727 /*InOverloadResolution=*/false,
4728 /*AllowObjCWritebackConversion=*/
4729 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004730 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004731 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004732 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004733 break;
4734 }
4735 } else {
4736 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4737 // argument for which there is no corresponding parameter is
4738 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004739 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004740 }
4741 }
4742}
4743
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004744/// \brief Add overload candidates for overloaded operators that are
4745/// member functions.
4746///
4747/// Add the overloaded operator candidates that are member functions
4748/// for the operator Op that was used in an operator expression such
4749/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4750/// CandidateSet will store the added overload candidates. (C++
4751/// [over.match.oper]).
4752void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4753 SourceLocation OpLoc,
4754 Expr **Args, unsigned NumArgs,
4755 OverloadCandidateSet& CandidateSet,
4756 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004757 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4758
4759 // C++ [over.match.oper]p3:
4760 // For a unary operator @ with an operand of a type whose
4761 // cv-unqualified version is T1, and for a binary operator @ with
4762 // a left operand of a type whose cv-unqualified version is T1 and
4763 // a right operand of a type whose cv-unqualified version is T2,
4764 // three sets of candidate functions, designated member
4765 // candidates, non-member candidates and built-in candidates, are
4766 // constructed as follows:
4767 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004768
4769 // -- If T1 is a class type, the set of member candidates is the
4770 // result of the qualified lookup of T1::operator@
4771 // (13.3.1.1.1); otherwise, the set of member candidates is
4772 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004773 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004774 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004775 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004776 return;
Mike Stump11289f42009-09-09 15:08:12 +00004777
John McCall27b18f82009-11-17 02:14:36 +00004778 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4779 LookupQualifiedName(Operators, T1Rec->getDecl());
4780 Operators.suppressDiagnostics();
4781
Mike Stump11289f42009-09-09 15:08:12 +00004782 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004783 OperEnd = Operators.end();
4784 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004785 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004786 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004787 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00004788 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004789 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004790 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004791}
4792
Douglas Gregora11693b2008-11-12 17:17:38 +00004793/// AddBuiltinCandidate - Add a candidate for a built-in
4794/// operator. ResultTy and ParamTys are the result and parameter types
4795/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004796/// arguments being passed to the candidate. IsAssignmentOperator
4797/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004798/// operator. NumContextualBoolArguments is the number of arguments
4799/// (at the beginning of the argument list) that will be contextually
4800/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004801void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004802 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004803 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004804 bool IsAssignmentOperator,
4805 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004806 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004807 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004808
Douglas Gregora11693b2008-11-12 17:17:38 +00004809 // Add this candidate
4810 CandidateSet.push_back(OverloadCandidate());
4811 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004812 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004813 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004814 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004815 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004816 Candidate.BuiltinTypes.ResultTy = ResultTy;
4817 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4818 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4819
4820 // Determine the implicit conversion sequences for each of the
4821 // arguments.
4822 Candidate.Viable = true;
4823 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004824 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004825 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004826 // C++ [over.match.oper]p4:
4827 // For the built-in assignment operators, conversions of the
4828 // left operand are restricted as follows:
4829 // -- no temporaries are introduced to hold the left operand, and
4830 // -- no user-defined conversions are applied to the left
4831 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004832 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004833 //
4834 // We block these conversions by turning off user-defined
4835 // conversions, since that is the only way that initialization of
4836 // a reference to a non-class type can occur from something that
4837 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004838 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004839 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004840 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004841 Candidate.Conversions[ArgIdx]
4842 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004843 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004844 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004845 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004846 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00004847 /*InOverloadResolution=*/false,
4848 /*AllowObjCWritebackConversion=*/
4849 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004850 }
John McCall0d1da222010-01-12 00:44:57 +00004851 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004852 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004853 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004854 break;
4855 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004856 }
4857}
4858
4859/// BuiltinCandidateTypeSet - A set of types that will be used for the
4860/// candidate operator functions for built-in operators (C++
4861/// [over.built]). The types are separated into pointer types and
4862/// enumeration types.
4863class BuiltinCandidateTypeSet {
4864 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004865 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004866
4867 /// PointerTypes - The set of pointer types that will be used in the
4868 /// built-in candidates.
4869 TypeSet PointerTypes;
4870
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004871 /// MemberPointerTypes - The set of member pointer types that will be
4872 /// used in the built-in candidates.
4873 TypeSet MemberPointerTypes;
4874
Douglas Gregora11693b2008-11-12 17:17:38 +00004875 /// EnumerationTypes - The set of enumeration types that will be
4876 /// used in the built-in candidates.
4877 TypeSet EnumerationTypes;
4878
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004879 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004880 /// candidates.
4881 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004882
4883 /// \brief A flag indicating non-record types are viable candidates
4884 bool HasNonRecordTypes;
4885
4886 /// \brief A flag indicating whether either arithmetic or enumeration types
4887 /// were present in the candidate set.
4888 bool HasArithmeticOrEnumeralTypes;
4889
Douglas Gregor80af3132011-05-21 23:15:46 +00004890 /// \brief A flag indicating whether the nullptr type was present in the
4891 /// candidate set.
4892 bool HasNullPtrType;
4893
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004894 /// Sema - The semantic analysis instance where we are building the
4895 /// candidate type set.
4896 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004897
Douglas Gregora11693b2008-11-12 17:17:38 +00004898 /// Context - The AST context in which we will build the type sets.
4899 ASTContext &Context;
4900
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004901 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4902 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004903 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004904
4905public:
4906 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004907 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004908
Mike Stump11289f42009-09-09 15:08:12 +00004909 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004910 : HasNonRecordTypes(false),
4911 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00004912 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00004913 SemaRef(SemaRef),
4914 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004915
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004916 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004917 SourceLocation Loc,
4918 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004919 bool AllowExplicitConversions,
4920 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004921
4922 /// pointer_begin - First pointer type found;
4923 iterator pointer_begin() { return PointerTypes.begin(); }
4924
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004925 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004926 iterator pointer_end() { return PointerTypes.end(); }
4927
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004928 /// member_pointer_begin - First member pointer type found;
4929 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4930
4931 /// member_pointer_end - Past the last member pointer type found;
4932 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4933
Douglas Gregora11693b2008-11-12 17:17:38 +00004934 /// enumeration_begin - First enumeration type found;
4935 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4936
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004937 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004938 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004939
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004940 iterator vector_begin() { return VectorTypes.begin(); }
4941 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00004942
4943 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4944 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00004945 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00004946};
4947
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004948/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004949/// the set of pointer types along with any more-qualified variants of
4950/// that type. For example, if @p Ty is "int const *", this routine
4951/// will add "int const *", "int const volatile *", "int const
4952/// restrict *", and "int const volatile restrict *" to the set of
4953/// pointer types. Returns true if the add of @p Ty itself succeeded,
4954/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004955///
4956/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004957bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004958BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4959 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004960
Douglas Gregora11693b2008-11-12 17:17:38 +00004961 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004962 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004963 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004964
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004965 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004966 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004967 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004968 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004969 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004970 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004971 buildObjCPtr = true;
4972 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004973 else
4974 assert(false && "type was not a pointer type!");
4975 }
4976 else
4977 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004978
Sebastian Redl4990a632009-11-18 20:39:26 +00004979 // Don't add qualified variants of arrays. For one, they're not allowed
4980 // (the qualifier would sink to the element type), and for another, the
4981 // only overload situation where it matters is subscript or pointer +- int,
4982 // and those shouldn't have qualifier variants anyway.
4983 if (PointeeTy->isArrayType())
4984 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004985 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004986 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004987 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004988 bool hasVolatile = VisibleQuals.hasVolatile();
4989 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004990
John McCall8ccfcb52009-09-24 19:53:00 +00004991 // Iterate through all strict supersets of BaseCVR.
4992 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4993 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004994 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4995 // in the types.
4996 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4997 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004998 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004999 if (!buildObjCPtr)
5000 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5001 else
5002 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005003 }
5004
5005 return true;
5006}
5007
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005008/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5009/// to the set of pointer types along with any more-qualified variants of
5010/// that type. For example, if @p Ty is "int const *", this routine
5011/// will add "int const *", "int const volatile *", "int const
5012/// restrict *", and "int const volatile restrict *" to the set of
5013/// pointer types. Returns true if the add of @p Ty itself succeeded,
5014/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005015///
5016/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005017bool
5018BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5019 QualType Ty) {
5020 // Insert this type.
5021 if (!MemberPointerTypes.insert(Ty))
5022 return false;
5023
John McCall8ccfcb52009-09-24 19:53:00 +00005024 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5025 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005026
John McCall8ccfcb52009-09-24 19:53:00 +00005027 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005028 // Don't add qualified variants of arrays. For one, they're not allowed
5029 // (the qualifier would sink to the element type), and for another, the
5030 // only overload situation where it matters is subscript or pointer +- int,
5031 // and those shouldn't have qualifier variants anyway.
5032 if (PointeeTy->isArrayType())
5033 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005034 const Type *ClassTy = PointerTy->getClass();
5035
5036 // Iterate through all strict supersets of the pointee type's CVR
5037 // qualifiers.
5038 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5039 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5040 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005041
John McCall8ccfcb52009-09-24 19:53:00 +00005042 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005043 MemberPointerTypes.insert(
5044 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005045 }
5046
5047 return true;
5048}
5049
Douglas Gregora11693b2008-11-12 17:17:38 +00005050/// AddTypesConvertedFrom - Add each of the types to which the type @p
5051/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005052/// primarily interested in pointer types and enumeration types. We also
5053/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005054/// AllowUserConversions is true if we should look at the conversion
5055/// functions of a class type, and AllowExplicitConversions if we
5056/// should also include the explicit conversion functions of a class
5057/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005058void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005059BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005060 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005061 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005062 bool AllowExplicitConversions,
5063 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005064 // Only deal with canonical types.
5065 Ty = Context.getCanonicalType(Ty);
5066
5067 // Look through reference types; they aren't part of the type of an
5068 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005069 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005070 Ty = RefTy->getPointeeType();
5071
John McCall33ddac02011-01-19 10:06:00 +00005072 // If we're dealing with an array type, decay to the pointer.
5073 if (Ty->isArrayType())
5074 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5075
5076 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005077 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005078
Chandler Carruth00a38332010-12-13 01:44:01 +00005079 // Flag if we ever add a non-record type.
5080 const RecordType *TyRec = Ty->getAs<RecordType>();
5081 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5082
Chandler Carruth00a38332010-12-13 01:44:01 +00005083 // Flag if we encounter an arithmetic type.
5084 HasArithmeticOrEnumeralTypes =
5085 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5086
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005087 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5088 PointerTypes.insert(Ty);
5089 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005090 // Insert our type, and its more-qualified variants, into the set
5091 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005092 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005093 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005094 } else if (Ty->isMemberPointerType()) {
5095 // Member pointers are far easier, since the pointee can't be converted.
5096 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5097 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005098 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005099 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005100 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005101 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005102 // We treat vector types as arithmetic types in many contexts as an
5103 // extension.
5104 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005105 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005106 } else if (Ty->isNullPtrType()) {
5107 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005108 } else if (AllowUserConversions && TyRec) {
5109 // No conversion functions in incomplete types.
5110 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5111 return;
Mike Stump11289f42009-09-09 15:08:12 +00005112
Chandler Carruth00a38332010-12-13 01:44:01 +00005113 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5114 const UnresolvedSetImpl *Conversions
5115 = ClassDecl->getVisibleConversionFunctions();
5116 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5117 E = Conversions->end(); I != E; ++I) {
5118 NamedDecl *D = I.getDecl();
5119 if (isa<UsingShadowDecl>(D))
5120 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005121
Chandler Carruth00a38332010-12-13 01:44:01 +00005122 // Skip conversion function templates; they don't tell us anything
5123 // about which builtin types we can convert to.
5124 if (isa<FunctionTemplateDecl>(D))
5125 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005126
Chandler Carruth00a38332010-12-13 01:44:01 +00005127 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5128 if (AllowExplicitConversions || !Conv->isExplicit()) {
5129 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5130 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005131 }
5132 }
5133 }
5134}
5135
Douglas Gregor84605ae2009-08-24 13:43:27 +00005136/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5137/// the volatile- and non-volatile-qualified assignment operators for the
5138/// given type to the candidate set.
5139static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5140 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005141 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005142 unsigned NumArgs,
5143 OverloadCandidateSet &CandidateSet) {
5144 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005145
Douglas Gregor84605ae2009-08-24 13:43:27 +00005146 // T& operator=(T&, T)
5147 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5148 ParamTypes[1] = T;
5149 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5150 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005151
Douglas Gregor84605ae2009-08-24 13:43:27 +00005152 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5153 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005154 ParamTypes[0]
5155 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005156 ParamTypes[1] = T;
5157 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005158 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005159 }
5160}
Mike Stump11289f42009-09-09 15:08:12 +00005161
Sebastian Redl1054fae2009-10-25 17:03:50 +00005162/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5163/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005164static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5165 Qualifiers VRQuals;
5166 const RecordType *TyRec;
5167 if (const MemberPointerType *RHSMPType =
5168 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005169 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005170 else
5171 TyRec = ArgExpr->getType()->getAs<RecordType>();
5172 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005173 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005174 VRQuals.addVolatile();
5175 VRQuals.addRestrict();
5176 return VRQuals;
5177 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005178
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005179 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005180 if (!ClassDecl->hasDefinition())
5181 return VRQuals;
5182
John McCallad371252010-01-20 00:46:10 +00005183 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005184 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005185
John McCallad371252010-01-20 00:46:10 +00005186 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005187 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005188 NamedDecl *D = I.getDecl();
5189 if (isa<UsingShadowDecl>(D))
5190 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5191 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005192 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5193 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5194 CanTy = ResTypeRef->getPointeeType();
5195 // Need to go down the pointer/mempointer chain and add qualifiers
5196 // as see them.
5197 bool done = false;
5198 while (!done) {
5199 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5200 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005201 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005202 CanTy->getAs<MemberPointerType>())
5203 CanTy = ResTypeMPtr->getPointeeType();
5204 else
5205 done = true;
5206 if (CanTy.isVolatileQualified())
5207 VRQuals.addVolatile();
5208 if (CanTy.isRestrictQualified())
5209 VRQuals.addRestrict();
5210 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5211 return VRQuals;
5212 }
5213 }
5214 }
5215 return VRQuals;
5216}
John McCall52872982010-11-13 05:51:15 +00005217
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005218namespace {
John McCall52872982010-11-13 05:51:15 +00005219
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005220/// \brief Helper class to manage the addition of builtin operator overload
5221/// candidates. It provides shared state and utility methods used throughout
5222/// the process, as well as a helper method to add each group of builtin
5223/// operator overloads from the standard to a candidate set.
5224class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005225 // Common instance state available to all overload candidate addition methods.
5226 Sema &S;
5227 Expr **Args;
5228 unsigned NumArgs;
5229 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005230 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005231 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
5232 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005233
Chandler Carruthc6586e52010-12-12 10:35:00 +00005234 // Define some constants used to index and iterate over the arithemetic types
5235 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005236 // The "promoted arithmetic types" are the arithmetic
5237 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005238 static const unsigned FirstIntegralType = 3;
5239 static const unsigned LastIntegralType = 18;
5240 static const unsigned FirstPromotedIntegralType = 3,
5241 LastPromotedIntegralType = 9;
5242 static const unsigned FirstPromotedArithmeticType = 0,
5243 LastPromotedArithmeticType = 9;
5244 static const unsigned NumArithmeticTypes = 18;
5245
Chandler Carruthc6586e52010-12-12 10:35:00 +00005246 /// \brief Get the canonical type for a given arithmetic type index.
5247 CanQualType getArithmeticType(unsigned index) {
5248 assert(index < NumArithmeticTypes);
5249 static CanQualType ASTContext::* const
5250 ArithmeticTypes[NumArithmeticTypes] = {
5251 // Start of promoted types.
5252 &ASTContext::FloatTy,
5253 &ASTContext::DoubleTy,
5254 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005255
Chandler Carruthc6586e52010-12-12 10:35:00 +00005256 // Start of integral types.
5257 &ASTContext::IntTy,
5258 &ASTContext::LongTy,
5259 &ASTContext::LongLongTy,
5260 &ASTContext::UnsignedIntTy,
5261 &ASTContext::UnsignedLongTy,
5262 &ASTContext::UnsignedLongLongTy,
5263 // End of promoted types.
5264
5265 &ASTContext::BoolTy,
5266 &ASTContext::CharTy,
5267 &ASTContext::WCharTy,
5268 &ASTContext::Char16Ty,
5269 &ASTContext::Char32Ty,
5270 &ASTContext::SignedCharTy,
5271 &ASTContext::ShortTy,
5272 &ASTContext::UnsignedCharTy,
5273 &ASTContext::UnsignedShortTy,
5274 // End of integral types.
5275 // FIXME: What about complex?
5276 };
5277 return S.Context.*ArithmeticTypes[index];
5278 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005279
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005280 /// \brief Gets the canonical type resulting from the usual arithemetic
5281 /// converions for the given arithmetic types.
5282 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5283 // Accelerator table for performing the usual arithmetic conversions.
5284 // The rules are basically:
5285 // - if either is floating-point, use the wider floating-point
5286 // - if same signedness, use the higher rank
5287 // - if same size, use unsigned of the higher rank
5288 // - use the larger type
5289 // These rules, together with the axiom that higher ranks are
5290 // never smaller, are sufficient to precompute all of these results
5291 // *except* when dealing with signed types of higher rank.
5292 // (we could precompute SLL x UI for all known platforms, but it's
5293 // better not to make any assumptions).
5294 enum PromotedType {
5295 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5296 };
5297 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5298 [LastPromotedArithmeticType] = {
5299 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5300 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5301 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5302 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5303 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5304 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5305 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5306 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5307 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5308 };
5309
5310 assert(L < LastPromotedArithmeticType);
5311 assert(R < LastPromotedArithmeticType);
5312 int Idx = ConversionsTable[L][R];
5313
5314 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005315 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005316
5317 // Slow path: we need to compare widths.
5318 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005319 CanQualType LT = getArithmeticType(L),
5320 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005321 unsigned LW = S.Context.getIntWidth(LT),
5322 RW = S.Context.getIntWidth(RT);
5323
5324 // If they're different widths, use the signed type.
5325 if (LW > RW) return LT;
5326 else if (LW < RW) return RT;
5327
5328 // Otherwise, use the unsigned type of the signed type's rank.
5329 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5330 assert(L == SLL || R == SLL);
5331 return S.Context.UnsignedLongLongTy;
5332 }
5333
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005334 /// \brief Helper method to factor out the common pattern of adding overloads
5335 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005336 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5337 bool HasVolatile) {
5338 QualType ParamTypes[2] = {
5339 S.Context.getLValueReferenceType(CandidateTy),
5340 S.Context.IntTy
5341 };
5342
5343 // Non-volatile version.
5344 if (NumArgs == 1)
5345 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5346 else
5347 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5348
5349 // Use a heuristic to reduce number of builtin candidates in the set:
5350 // add volatile version only if there are conversions to a volatile type.
5351 if (HasVolatile) {
5352 ParamTypes[0] =
5353 S.Context.getLValueReferenceType(
5354 S.Context.getVolatileType(CandidateTy));
5355 if (NumArgs == 1)
5356 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5357 else
5358 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5359 }
5360 }
5361
5362public:
5363 BuiltinOperatorOverloadBuilder(
5364 Sema &S, Expr **Args, unsigned NumArgs,
5365 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005366 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005367 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
5368 OverloadCandidateSet &CandidateSet)
5369 : S(S), Args(Args), NumArgs(NumArgs),
5370 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005371 HasArithmeticOrEnumeralCandidateType(
5372 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005373 CandidateTypes(CandidateTypes),
5374 CandidateSet(CandidateSet) {
5375 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005376 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005377 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005378 assert(getArithmeticType(LastPromotedIntegralType - 1)
5379 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005380 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005381 assert(getArithmeticType(FirstPromotedArithmeticType)
5382 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005383 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005384 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5385 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005386 "Invalid last promoted arithmetic type");
5387 }
5388
5389 // C++ [over.built]p3:
5390 //
5391 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5392 // is either volatile or empty, there exist candidate operator
5393 // functions of the form
5394 //
5395 // VQ T& operator++(VQ T&);
5396 // T operator++(VQ T&, int);
5397 //
5398 // C++ [over.built]p4:
5399 //
5400 // For every pair (T, VQ), where T is an arithmetic type other
5401 // than bool, and VQ is either volatile or empty, there exist
5402 // candidate operator functions of the form
5403 //
5404 // VQ T& operator--(VQ T&);
5405 // T operator--(VQ T&, int);
5406 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005407 if (!HasArithmeticOrEnumeralCandidateType)
5408 return;
5409
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005410 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5411 Arith < NumArithmeticTypes; ++Arith) {
5412 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005413 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005414 VisibleTypeConversionsQuals.hasVolatile());
5415 }
5416 }
5417
5418 // C++ [over.built]p5:
5419 //
5420 // For every pair (T, VQ), where T is a cv-qualified or
5421 // cv-unqualified object type, and VQ is either volatile or
5422 // empty, there exist candidate operator functions of the form
5423 //
5424 // T*VQ& operator++(T*VQ&);
5425 // T*VQ& operator--(T*VQ&);
5426 // T* operator++(T*VQ&, int);
5427 // T* operator--(T*VQ&, int);
5428 void addPlusPlusMinusMinusPointerOverloads() {
5429 for (BuiltinCandidateTypeSet::iterator
5430 Ptr = CandidateTypes[0].pointer_begin(),
5431 PtrEnd = CandidateTypes[0].pointer_end();
5432 Ptr != PtrEnd; ++Ptr) {
5433 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005434 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005435 continue;
5436
5437 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5438 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5439 VisibleTypeConversionsQuals.hasVolatile()));
5440 }
5441 }
5442
5443 // C++ [over.built]p6:
5444 // For every cv-qualified or cv-unqualified object type T, there
5445 // exist candidate operator functions of the form
5446 //
5447 // T& operator*(T*);
5448 //
5449 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005450 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005451 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005452 // T& operator*(T*);
5453 void addUnaryStarPointerOverloads() {
5454 for (BuiltinCandidateTypeSet::iterator
5455 Ptr = CandidateTypes[0].pointer_begin(),
5456 PtrEnd = CandidateTypes[0].pointer_end();
5457 Ptr != PtrEnd; ++Ptr) {
5458 QualType ParamTy = *Ptr;
5459 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005460 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5461 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005462
Douglas Gregor02824322011-01-26 19:30:28 +00005463 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5464 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5465 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005466
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005467 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5468 &ParamTy, Args, 1, CandidateSet);
5469 }
5470 }
5471
5472 // C++ [over.built]p9:
5473 // For every promoted arithmetic type T, there exist candidate
5474 // operator functions of the form
5475 //
5476 // T operator+(T);
5477 // T operator-(T);
5478 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005479 if (!HasArithmeticOrEnumeralCandidateType)
5480 return;
5481
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005482 for (unsigned Arith = FirstPromotedArithmeticType;
5483 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005484 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005485 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5486 }
5487
5488 // Extension: We also add these operators for vector types.
5489 for (BuiltinCandidateTypeSet::iterator
5490 Vec = CandidateTypes[0].vector_begin(),
5491 VecEnd = CandidateTypes[0].vector_end();
5492 Vec != VecEnd; ++Vec) {
5493 QualType VecTy = *Vec;
5494 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5495 }
5496 }
5497
5498 // C++ [over.built]p8:
5499 // For every type T, there exist candidate operator functions of
5500 // the form
5501 //
5502 // T* operator+(T*);
5503 void addUnaryPlusPointerOverloads() {
5504 for (BuiltinCandidateTypeSet::iterator
5505 Ptr = CandidateTypes[0].pointer_begin(),
5506 PtrEnd = CandidateTypes[0].pointer_end();
5507 Ptr != PtrEnd; ++Ptr) {
5508 QualType ParamTy = *Ptr;
5509 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5510 }
5511 }
5512
5513 // C++ [over.built]p10:
5514 // For every promoted integral type T, there exist candidate
5515 // operator functions of the form
5516 //
5517 // T operator~(T);
5518 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005519 if (!HasArithmeticOrEnumeralCandidateType)
5520 return;
5521
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005522 for (unsigned Int = FirstPromotedIntegralType;
5523 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005524 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005525 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5526 }
5527
5528 // Extension: We also add this operator for vector types.
5529 for (BuiltinCandidateTypeSet::iterator
5530 Vec = CandidateTypes[0].vector_begin(),
5531 VecEnd = CandidateTypes[0].vector_end();
5532 Vec != VecEnd; ++Vec) {
5533 QualType VecTy = *Vec;
5534 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5535 }
5536 }
5537
5538 // C++ [over.match.oper]p16:
5539 // For every pointer to member type T, there exist candidate operator
5540 // functions of the form
5541 //
5542 // bool operator==(T,T);
5543 // bool operator!=(T,T);
5544 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5545 /// Set of (canonical) types that we've already handled.
5546 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5547
5548 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5549 for (BuiltinCandidateTypeSet::iterator
5550 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5551 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5552 MemPtr != MemPtrEnd;
5553 ++MemPtr) {
5554 // Don't add the same builtin candidate twice.
5555 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5556 continue;
5557
5558 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5559 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5560 CandidateSet);
5561 }
5562 }
5563 }
5564
5565 // C++ [over.built]p15:
5566 //
Douglas Gregor80af3132011-05-21 23:15:46 +00005567 // For every T, where T is an enumeration type, a pointer type, or
5568 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005569 //
5570 // bool operator<(T, T);
5571 // bool operator>(T, T);
5572 // bool operator<=(T, T);
5573 // bool operator>=(T, T);
5574 // bool operator==(T, T);
5575 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005576 void addRelationalPointerOrEnumeralOverloads() {
5577 // C++ [over.built]p1:
5578 // If there is a user-written candidate with the same name and parameter
5579 // types as a built-in candidate operator function, the built-in operator
5580 // function is hidden and is not included in the set of candidate
5581 // functions.
5582 //
5583 // The text is actually in a note, but if we don't implement it then we end
5584 // up with ambiguities when the user provides an overloaded operator for
5585 // an enumeration type. Note that only enumeration types have this problem,
5586 // so we track which enumeration types we've seen operators for. Also, the
5587 // only other overloaded operator with enumeration argumenst, operator=,
5588 // cannot be overloaded for enumeration types, so this is the only place
5589 // where we must suppress candidates like this.
5590 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5591 UserDefinedBinaryOperators;
5592
5593 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5594 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5595 CandidateTypes[ArgIdx].enumeration_end()) {
5596 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5597 CEnd = CandidateSet.end();
5598 C != CEnd; ++C) {
5599 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5600 continue;
5601
5602 QualType FirstParamType =
5603 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5604 QualType SecondParamType =
5605 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5606
5607 // Skip if either parameter isn't of enumeral type.
5608 if (!FirstParamType->isEnumeralType() ||
5609 !SecondParamType->isEnumeralType())
5610 continue;
5611
5612 // Add this operator to the set of known user-defined operators.
5613 UserDefinedBinaryOperators.insert(
5614 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5615 S.Context.getCanonicalType(SecondParamType)));
5616 }
5617 }
5618 }
5619
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005620 /// Set of (canonical) types that we've already handled.
5621 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5622
5623 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5624 for (BuiltinCandidateTypeSet::iterator
5625 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5626 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5627 Ptr != PtrEnd; ++Ptr) {
5628 // Don't add the same builtin candidate twice.
5629 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5630 continue;
5631
5632 QualType ParamTypes[2] = { *Ptr, *Ptr };
5633 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5634 CandidateSet);
5635 }
5636 for (BuiltinCandidateTypeSet::iterator
5637 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5638 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5639 Enum != EnumEnd; ++Enum) {
5640 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5641
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005642 // Don't add the same builtin candidate twice, or if a user defined
5643 // candidate exists.
5644 if (!AddedTypes.insert(CanonType) ||
5645 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5646 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005647 continue;
5648
5649 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005650 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5651 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005652 }
Douglas Gregor80af3132011-05-21 23:15:46 +00005653
5654 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5655 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5656 if (AddedTypes.insert(NullPtrTy) &&
5657 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
5658 NullPtrTy))) {
5659 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5660 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5661 CandidateSet);
5662 }
5663 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005664 }
5665 }
5666
5667 // C++ [over.built]p13:
5668 //
5669 // For every cv-qualified or cv-unqualified object type T
5670 // there exist candidate operator functions of the form
5671 //
5672 // T* operator+(T*, ptrdiff_t);
5673 // T& operator[](T*, ptrdiff_t); [BELOW]
5674 // T* operator-(T*, ptrdiff_t);
5675 // T* operator+(ptrdiff_t, T*);
5676 // T& operator[](ptrdiff_t, T*); [BELOW]
5677 //
5678 // C++ [over.built]p14:
5679 //
5680 // For every T, where T is a pointer to object type, there
5681 // exist candidate operator functions of the form
5682 //
5683 // ptrdiff_t operator-(T, T);
5684 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5685 /// Set of (canonical) types that we've already handled.
5686 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5687
5688 for (int Arg = 0; Arg < 2; ++Arg) {
5689 QualType AsymetricParamTypes[2] = {
5690 S.Context.getPointerDiffType(),
5691 S.Context.getPointerDiffType(),
5692 };
5693 for (BuiltinCandidateTypeSet::iterator
5694 Ptr = CandidateTypes[Arg].pointer_begin(),
5695 PtrEnd = CandidateTypes[Arg].pointer_end();
5696 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005697 QualType PointeeTy = (*Ptr)->getPointeeType();
5698 if (!PointeeTy->isObjectType())
5699 continue;
5700
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005701 AsymetricParamTypes[Arg] = *Ptr;
5702 if (Arg == 0 || Op == OO_Plus) {
5703 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5704 // T* operator+(ptrdiff_t, T*);
5705 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5706 CandidateSet);
5707 }
5708 if (Op == OO_Minus) {
5709 // ptrdiff_t operator-(T, T);
5710 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5711 continue;
5712
5713 QualType ParamTypes[2] = { *Ptr, *Ptr };
5714 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5715 Args, 2, CandidateSet);
5716 }
5717 }
5718 }
5719 }
5720
5721 // C++ [over.built]p12:
5722 //
5723 // For every pair of promoted arithmetic types L and R, there
5724 // exist candidate operator functions of the form
5725 //
5726 // LR operator*(L, R);
5727 // LR operator/(L, R);
5728 // LR operator+(L, R);
5729 // LR operator-(L, R);
5730 // bool operator<(L, R);
5731 // bool operator>(L, R);
5732 // bool operator<=(L, R);
5733 // bool operator>=(L, R);
5734 // bool operator==(L, R);
5735 // bool operator!=(L, R);
5736 //
5737 // where LR is the result of the usual arithmetic conversions
5738 // between types L and R.
5739 //
5740 // C++ [over.built]p24:
5741 //
5742 // For every pair of promoted arithmetic types L and R, there exist
5743 // candidate operator functions of the form
5744 //
5745 // LR operator?(bool, L, R);
5746 //
5747 // where LR is the result of the usual arithmetic conversions
5748 // between types L and R.
5749 // Our candidates ignore the first parameter.
5750 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005751 if (!HasArithmeticOrEnumeralCandidateType)
5752 return;
5753
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005754 for (unsigned Left = FirstPromotedArithmeticType;
5755 Left < LastPromotedArithmeticType; ++Left) {
5756 for (unsigned Right = FirstPromotedArithmeticType;
5757 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005758 QualType LandR[2] = { getArithmeticType(Left),
5759 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005760 QualType Result =
5761 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005762 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005763 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5764 }
5765 }
5766
5767 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5768 // conditional operator for vector types.
5769 for (BuiltinCandidateTypeSet::iterator
5770 Vec1 = CandidateTypes[0].vector_begin(),
5771 Vec1End = CandidateTypes[0].vector_end();
5772 Vec1 != Vec1End; ++Vec1) {
5773 for (BuiltinCandidateTypeSet::iterator
5774 Vec2 = CandidateTypes[1].vector_begin(),
5775 Vec2End = CandidateTypes[1].vector_end();
5776 Vec2 != Vec2End; ++Vec2) {
5777 QualType LandR[2] = { *Vec1, *Vec2 };
5778 QualType Result = S.Context.BoolTy;
5779 if (!isComparison) {
5780 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5781 Result = *Vec1;
5782 else
5783 Result = *Vec2;
5784 }
5785
5786 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5787 }
5788 }
5789 }
5790
5791 // C++ [over.built]p17:
5792 //
5793 // For every pair of promoted integral types L and R, there
5794 // exist candidate operator functions of the form
5795 //
5796 // LR operator%(L, R);
5797 // LR operator&(L, R);
5798 // LR operator^(L, R);
5799 // LR operator|(L, R);
5800 // L operator<<(L, R);
5801 // L operator>>(L, R);
5802 //
5803 // where LR is the result of the usual arithmetic conversions
5804 // between types L and R.
5805 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005806 if (!HasArithmeticOrEnumeralCandidateType)
5807 return;
5808
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005809 for (unsigned Left = FirstPromotedIntegralType;
5810 Left < LastPromotedIntegralType; ++Left) {
5811 for (unsigned Right = FirstPromotedIntegralType;
5812 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005813 QualType LandR[2] = { getArithmeticType(Left),
5814 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005815 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5816 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005817 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005818 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5819 }
5820 }
5821 }
5822
5823 // C++ [over.built]p20:
5824 //
5825 // For every pair (T, VQ), where T is an enumeration or
5826 // pointer to member type and VQ is either volatile or
5827 // empty, there exist candidate operator functions of the form
5828 //
5829 // VQ T& operator=(VQ T&, T);
5830 void addAssignmentMemberPointerOrEnumeralOverloads() {
5831 /// Set of (canonical) types that we've already handled.
5832 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5833
5834 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5835 for (BuiltinCandidateTypeSet::iterator
5836 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5837 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5838 Enum != EnumEnd; ++Enum) {
5839 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5840 continue;
5841
5842 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5843 CandidateSet);
5844 }
5845
5846 for (BuiltinCandidateTypeSet::iterator
5847 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5848 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5849 MemPtr != MemPtrEnd; ++MemPtr) {
5850 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5851 continue;
5852
5853 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5854 CandidateSet);
5855 }
5856 }
5857 }
5858
5859 // C++ [over.built]p19:
5860 //
5861 // For every pair (T, VQ), where T is any type and VQ is either
5862 // volatile or empty, there exist candidate operator functions
5863 // of the form
5864 //
5865 // T*VQ& operator=(T*VQ&, T*);
5866 //
5867 // C++ [over.built]p21:
5868 //
5869 // For every pair (T, VQ), where T is a cv-qualified or
5870 // cv-unqualified object type and VQ is either volatile or
5871 // empty, there exist candidate operator functions of the form
5872 //
5873 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5874 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5875 void addAssignmentPointerOverloads(bool isEqualOp) {
5876 /// Set of (canonical) types that we've already handled.
5877 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5878
5879 for (BuiltinCandidateTypeSet::iterator
5880 Ptr = CandidateTypes[0].pointer_begin(),
5881 PtrEnd = CandidateTypes[0].pointer_end();
5882 Ptr != PtrEnd; ++Ptr) {
5883 // If this is operator=, keep track of the builtin candidates we added.
5884 if (isEqualOp)
5885 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005886 else if (!(*Ptr)->getPointeeType()->isObjectType())
5887 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005888
5889 // non-volatile version
5890 QualType ParamTypes[2] = {
5891 S.Context.getLValueReferenceType(*Ptr),
5892 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5893 };
5894 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5895 /*IsAssigmentOperator=*/ isEqualOp);
5896
5897 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5898 VisibleTypeConversionsQuals.hasVolatile()) {
5899 // volatile version
5900 ParamTypes[0] =
5901 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5902 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5903 /*IsAssigmentOperator=*/isEqualOp);
5904 }
5905 }
5906
5907 if (isEqualOp) {
5908 for (BuiltinCandidateTypeSet::iterator
5909 Ptr = CandidateTypes[1].pointer_begin(),
5910 PtrEnd = CandidateTypes[1].pointer_end();
5911 Ptr != PtrEnd; ++Ptr) {
5912 // Make sure we don't add the same candidate twice.
5913 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5914 continue;
5915
Chandler Carruth8e543b32010-12-12 08:17:55 +00005916 QualType ParamTypes[2] = {
5917 S.Context.getLValueReferenceType(*Ptr),
5918 *Ptr,
5919 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005920
5921 // non-volatile version
5922 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5923 /*IsAssigmentOperator=*/true);
5924
5925 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5926 VisibleTypeConversionsQuals.hasVolatile()) {
5927 // volatile version
5928 ParamTypes[0] =
5929 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00005930 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5931 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005932 }
5933 }
5934 }
5935 }
5936
5937 // C++ [over.built]p18:
5938 //
5939 // For every triple (L, VQ, R), where L is an arithmetic type,
5940 // VQ is either volatile or empty, and R is a promoted
5941 // arithmetic type, there exist candidate operator functions of
5942 // the form
5943 //
5944 // VQ L& operator=(VQ L&, R);
5945 // VQ L& operator*=(VQ L&, R);
5946 // VQ L& operator/=(VQ L&, R);
5947 // VQ L& operator+=(VQ L&, R);
5948 // VQ L& operator-=(VQ L&, R);
5949 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005950 if (!HasArithmeticOrEnumeralCandidateType)
5951 return;
5952
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005953 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5954 for (unsigned Right = FirstPromotedArithmeticType;
5955 Right < LastPromotedArithmeticType; ++Right) {
5956 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005957 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005958
5959 // Add this built-in operator as a candidate (VQ is empty).
5960 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005961 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005962 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5963 /*IsAssigmentOperator=*/isEqualOp);
5964
5965 // Add this built-in operator as a candidate (VQ is 'volatile').
5966 if (VisibleTypeConversionsQuals.hasVolatile()) {
5967 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005968 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005969 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005970 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5971 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005972 /*IsAssigmentOperator=*/isEqualOp);
5973 }
5974 }
5975 }
5976
5977 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5978 for (BuiltinCandidateTypeSet::iterator
5979 Vec1 = CandidateTypes[0].vector_begin(),
5980 Vec1End = CandidateTypes[0].vector_end();
5981 Vec1 != Vec1End; ++Vec1) {
5982 for (BuiltinCandidateTypeSet::iterator
5983 Vec2 = CandidateTypes[1].vector_begin(),
5984 Vec2End = CandidateTypes[1].vector_end();
5985 Vec2 != Vec2End; ++Vec2) {
5986 QualType ParamTypes[2];
5987 ParamTypes[1] = *Vec2;
5988 // Add this built-in operator as a candidate (VQ is empty).
5989 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5990 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5991 /*IsAssigmentOperator=*/isEqualOp);
5992
5993 // Add this built-in operator as a candidate (VQ is 'volatile').
5994 if (VisibleTypeConversionsQuals.hasVolatile()) {
5995 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5996 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005997 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5998 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005999 /*IsAssigmentOperator=*/isEqualOp);
6000 }
6001 }
6002 }
6003 }
6004
6005 // C++ [over.built]p22:
6006 //
6007 // For every triple (L, VQ, R), where L is an integral type, VQ
6008 // is either volatile or empty, and R is a promoted integral
6009 // type, there exist candidate operator functions of the form
6010 //
6011 // VQ L& operator%=(VQ L&, R);
6012 // VQ L& operator<<=(VQ L&, R);
6013 // VQ L& operator>>=(VQ L&, R);
6014 // VQ L& operator&=(VQ L&, R);
6015 // VQ L& operator^=(VQ L&, R);
6016 // VQ L& operator|=(VQ L&, R);
6017 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006018 if (!HasArithmeticOrEnumeralCandidateType)
6019 return;
6020
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006021 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6022 for (unsigned Right = FirstPromotedIntegralType;
6023 Right < LastPromotedIntegralType; ++Right) {
6024 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006025 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006026
6027 // Add this built-in operator as a candidate (VQ is empty).
6028 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006029 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006030 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6031 if (VisibleTypeConversionsQuals.hasVolatile()) {
6032 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006033 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006034 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6035 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6036 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6037 CandidateSet);
6038 }
6039 }
6040 }
6041 }
6042
6043 // C++ [over.operator]p23:
6044 //
6045 // There also exist candidate operator functions of the form
6046 //
6047 // bool operator!(bool);
6048 // bool operator&&(bool, bool);
6049 // bool operator||(bool, bool);
6050 void addExclaimOverload() {
6051 QualType ParamTy = S.Context.BoolTy;
6052 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6053 /*IsAssignmentOperator=*/false,
6054 /*NumContextualBoolArguments=*/1);
6055 }
6056 void addAmpAmpOrPipePipeOverload() {
6057 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6058 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6059 /*IsAssignmentOperator=*/false,
6060 /*NumContextualBoolArguments=*/2);
6061 }
6062
6063 // C++ [over.built]p13:
6064 //
6065 // For every cv-qualified or cv-unqualified object type T there
6066 // exist candidate operator functions of the form
6067 //
6068 // T* operator+(T*, ptrdiff_t); [ABOVE]
6069 // T& operator[](T*, ptrdiff_t);
6070 // T* operator-(T*, ptrdiff_t); [ABOVE]
6071 // T* operator+(ptrdiff_t, T*); [ABOVE]
6072 // T& operator[](ptrdiff_t, T*);
6073 void addSubscriptOverloads() {
6074 for (BuiltinCandidateTypeSet::iterator
6075 Ptr = CandidateTypes[0].pointer_begin(),
6076 PtrEnd = CandidateTypes[0].pointer_end();
6077 Ptr != PtrEnd; ++Ptr) {
6078 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6079 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006080 if (!PointeeType->isObjectType())
6081 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006082
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006083 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6084
6085 // T& operator[](T*, ptrdiff_t)
6086 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6087 }
6088
6089 for (BuiltinCandidateTypeSet::iterator
6090 Ptr = CandidateTypes[1].pointer_begin(),
6091 PtrEnd = CandidateTypes[1].pointer_end();
6092 Ptr != PtrEnd; ++Ptr) {
6093 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6094 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006095 if (!PointeeType->isObjectType())
6096 continue;
6097
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006098 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6099
6100 // T& operator[](ptrdiff_t, T*)
6101 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6102 }
6103 }
6104
6105 // C++ [over.built]p11:
6106 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6107 // C1 is the same type as C2 or is a derived class of C2, T is an object
6108 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6109 // there exist candidate operator functions of the form
6110 //
6111 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6112 //
6113 // where CV12 is the union of CV1 and CV2.
6114 void addArrowStarOverloads() {
6115 for (BuiltinCandidateTypeSet::iterator
6116 Ptr = CandidateTypes[0].pointer_begin(),
6117 PtrEnd = CandidateTypes[0].pointer_end();
6118 Ptr != PtrEnd; ++Ptr) {
6119 QualType C1Ty = (*Ptr);
6120 QualType C1;
6121 QualifierCollector Q1;
6122 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6123 if (!isa<RecordType>(C1))
6124 continue;
6125 // heuristic to reduce number of builtin candidates in the set.
6126 // Add volatile/restrict version only if there are conversions to a
6127 // volatile/restrict type.
6128 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6129 continue;
6130 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6131 continue;
6132 for (BuiltinCandidateTypeSet::iterator
6133 MemPtr = CandidateTypes[1].member_pointer_begin(),
6134 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6135 MemPtr != MemPtrEnd; ++MemPtr) {
6136 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6137 QualType C2 = QualType(mptr->getClass(), 0);
6138 C2 = C2.getUnqualifiedType();
6139 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6140 break;
6141 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6142 // build CV12 T&
6143 QualType T = mptr->getPointeeType();
6144 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6145 T.isVolatileQualified())
6146 continue;
6147 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6148 T.isRestrictQualified())
6149 continue;
6150 T = Q1.apply(S.Context, T);
6151 QualType ResultTy = S.Context.getLValueReferenceType(T);
6152 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6153 }
6154 }
6155 }
6156
6157 // Note that we don't consider the first argument, since it has been
6158 // contextually converted to bool long ago. The candidates below are
6159 // therefore added as binary.
6160 //
6161 // C++ [over.built]p25:
6162 // For every type T, where T is a pointer, pointer-to-member, or scoped
6163 // enumeration type, there exist candidate operator functions of the form
6164 //
6165 // T operator?(bool, T, T);
6166 //
6167 void addConditionalOperatorOverloads() {
6168 /// Set of (canonical) types that we've already handled.
6169 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6170
6171 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6172 for (BuiltinCandidateTypeSet::iterator
6173 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6174 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6175 Ptr != PtrEnd; ++Ptr) {
6176 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6177 continue;
6178
6179 QualType ParamTypes[2] = { *Ptr, *Ptr };
6180 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6181 }
6182
6183 for (BuiltinCandidateTypeSet::iterator
6184 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6185 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6186 MemPtr != MemPtrEnd; ++MemPtr) {
6187 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6188 continue;
6189
6190 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6191 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6192 }
6193
6194 if (S.getLangOptions().CPlusPlus0x) {
6195 for (BuiltinCandidateTypeSet::iterator
6196 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6197 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6198 Enum != EnumEnd; ++Enum) {
6199 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6200 continue;
6201
6202 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6203 continue;
6204
6205 QualType ParamTypes[2] = { *Enum, *Enum };
6206 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6207 }
6208 }
6209 }
6210 }
6211};
6212
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006213} // end anonymous namespace
6214
6215/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6216/// operator overloads to the candidate set (C++ [over.built]), based
6217/// on the operator @p Op and the arguments given. For example, if the
6218/// operator is a binary '+', this routine might add "int
6219/// operator+(int, int)" to cover integer addition.
6220void
6221Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6222 SourceLocation OpLoc,
6223 Expr **Args, unsigned NumArgs,
6224 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006225 // Find all of the types that the arguments can convert to, but only
6226 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006227 // that make use of these types. Also record whether we encounter non-record
6228 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006229 Qualifiers VisibleTypeConversionsQuals;
6230 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006231 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6232 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006233
6234 bool HasNonRecordCandidateType = false;
6235 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006236 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
6237 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6238 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6239 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6240 OpLoc,
6241 true,
6242 (Op == OO_Exclaim ||
6243 Op == OO_AmpAmp ||
6244 Op == OO_PipePipe),
6245 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006246 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6247 CandidateTypes[ArgIdx].hasNonRecordTypes();
6248 HasArithmeticOrEnumeralCandidateType =
6249 HasArithmeticOrEnumeralCandidateType ||
6250 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006251 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006252
Chandler Carruth00a38332010-12-13 01:44:01 +00006253 // Exit early when no non-record types have been added to the candidate set
6254 // for any of the arguments to the operator.
6255 if (!HasNonRecordCandidateType)
6256 return;
6257
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006258 // Setup an object to manage the common state for building overloads.
6259 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6260 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006261 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006262 CandidateTypes, CandidateSet);
6263
6264 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006265 switch (Op) {
6266 case OO_None:
6267 case NUM_OVERLOADED_OPERATORS:
6268 assert(false && "Expected an overloaded operator");
6269 break;
6270
Chandler Carruth5184de02010-12-12 08:51:33 +00006271 case OO_New:
6272 case OO_Delete:
6273 case OO_Array_New:
6274 case OO_Array_Delete:
6275 case OO_Call:
6276 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
6277 break;
6278
6279 case OO_Comma:
6280 case OO_Arrow:
6281 // C++ [over.match.oper]p3:
6282 // -- For the operator ',', the unary operator '&', or the
6283 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006284 break;
6285
6286 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006287 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006288 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006289 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006290
6291 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006292 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006293 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006294 } else {
6295 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6296 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6297 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006298 break;
6299
Chandler Carruth5184de02010-12-12 08:51:33 +00006300 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006301 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006302 OpBuilder.addUnaryStarPointerOverloads();
6303 else
6304 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6305 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006306
Chandler Carruth5184de02010-12-12 08:51:33 +00006307 case OO_Slash:
6308 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006309 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006310
6311 case OO_PlusPlus:
6312 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006313 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6314 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006315 break;
6316
Douglas Gregor84605ae2009-08-24 13:43:27 +00006317 case OO_EqualEqual:
6318 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006319 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006320 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006321
Douglas Gregora11693b2008-11-12 17:17:38 +00006322 case OO_Less:
6323 case OO_Greater:
6324 case OO_LessEqual:
6325 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006326 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006327 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6328 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006329
Douglas Gregora11693b2008-11-12 17:17:38 +00006330 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006331 case OO_Caret:
6332 case OO_Pipe:
6333 case OO_LessLess:
6334 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006335 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006336 break;
6337
Chandler Carruth5184de02010-12-12 08:51:33 +00006338 case OO_Amp: // '&' is either unary or binary
6339 if (NumArgs == 1)
6340 // C++ [over.match.oper]p3:
6341 // -- For the operator ',', the unary operator '&', or the
6342 // operator '->', the built-in candidates set is empty.
6343 break;
6344
6345 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6346 break;
6347
6348 case OO_Tilde:
6349 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6350 break;
6351
Douglas Gregora11693b2008-11-12 17:17:38 +00006352 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006353 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006354 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006355
6356 case OO_PlusEqual:
6357 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006358 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006359 // Fall through.
6360
6361 case OO_StarEqual:
6362 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006363 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006364 break;
6365
6366 case OO_PercentEqual:
6367 case OO_LessLessEqual:
6368 case OO_GreaterGreaterEqual:
6369 case OO_AmpEqual:
6370 case OO_CaretEqual:
6371 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006372 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006373 break;
6374
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006375 case OO_Exclaim:
6376 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006377 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006378
Douglas Gregora11693b2008-11-12 17:17:38 +00006379 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006380 case OO_PipePipe:
6381 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006382 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006383
6384 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006385 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006386 break;
6387
6388 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006389 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006390 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006391
6392 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006393 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006394 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6395 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006396 }
6397}
6398
Douglas Gregore254f902009-02-04 00:32:51 +00006399/// \brief Add function candidates found via argument-dependent lookup
6400/// to the set of overloading candidates.
6401///
6402/// This routine performs argument-dependent name lookup based on the
6403/// given function name (which may also be an operator name) and adds
6404/// all of the overload candidates found by ADL to the overload
6405/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006406void
Douglas Gregore254f902009-02-04 00:32:51 +00006407Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006408 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006409 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006410 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006411 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006412 bool PartialOverloading,
6413 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006414 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006415
John McCall91f61fc2010-01-26 06:04:06 +00006416 // FIXME: This approach for uniquing ADL results (and removing
6417 // redundant candidates from the set) relies on pointer-equality,
6418 // which means we need to key off the canonical decl. However,
6419 // always going back to the canonical decl might not get us the
6420 // right set of default arguments. What default arguments are
6421 // we supposed to consider on ADL candidates, anyway?
6422
Douglas Gregorcabea402009-09-22 15:41:20 +00006423 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006424 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6425 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006426
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006427 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006428 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6429 CandEnd = CandidateSet.end();
6430 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006431 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006432 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006433 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006434 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006435 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006436
6437 // For each of the ADL candidates we found, add it to the overload
6438 // set.
John McCall8fe68082010-01-26 07:16:45 +00006439 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006440 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006441 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006442 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006443 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006444
John McCalla0296f72010-03-19 07:35:19 +00006445 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006446 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006447 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006448 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006449 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006450 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006451 }
Douglas Gregore254f902009-02-04 00:32:51 +00006452}
6453
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006454/// isBetterOverloadCandidate - Determines whether the first overload
6455/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006456bool
John McCall5c32be02010-08-24 20:38:10 +00006457isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006458 const OverloadCandidate &Cand1,
6459 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006460 SourceLocation Loc,
6461 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006462 // Define viable functions to be better candidates than non-viable
6463 // functions.
6464 if (!Cand2.Viable)
6465 return Cand1.Viable;
6466 else if (!Cand1.Viable)
6467 return false;
6468
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006469 // C++ [over.match.best]p1:
6470 //
6471 // -- if F is a static member function, ICS1(F) is defined such
6472 // that ICS1(F) is neither better nor worse than ICS1(G) for
6473 // any function G, and, symmetrically, ICS1(G) is neither
6474 // better nor worse than ICS1(F).
6475 unsigned StartArg = 0;
6476 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6477 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006478
Douglas Gregord3cb3562009-07-07 23:38:56 +00006479 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006480 // A viable function F1 is defined to be a better function than another
6481 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006482 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006483 unsigned NumArgs = Cand1.Conversions.size();
6484 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6485 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006486 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006487 switch (CompareImplicitConversionSequences(S,
6488 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006489 Cand2.Conversions[ArgIdx])) {
6490 case ImplicitConversionSequence::Better:
6491 // Cand1 has a better conversion sequence.
6492 HasBetterConversion = true;
6493 break;
6494
6495 case ImplicitConversionSequence::Worse:
6496 // Cand1 can't be better than Cand2.
6497 return false;
6498
6499 case ImplicitConversionSequence::Indistinguishable:
6500 // Do nothing.
6501 break;
6502 }
6503 }
6504
Mike Stump11289f42009-09-09 15:08:12 +00006505 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006506 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006507 if (HasBetterConversion)
6508 return true;
6509
Mike Stump11289f42009-09-09 15:08:12 +00006510 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006511 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006512 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006513 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6514 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006515
6516 // -- F1 and F2 are function template specializations, and the function
6517 // template for F1 is more specialized than the template for F2
6518 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006519 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006520 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006521 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006522 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006523 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6524 Cand2.Function->getPrimaryTemplate(),
6525 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006526 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006527 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006528 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006529 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006530 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006531
Douglas Gregora1f013e2008-11-07 22:36:19 +00006532 // -- the context is an initialization by user-defined conversion
6533 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6534 // from the return type of F1 to the destination type (i.e.,
6535 // the type of the entity being initialized) is a better
6536 // conversion sequence than the standard conversion sequence
6537 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006538 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006539 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006540 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006541 switch (CompareStandardConversionSequences(S,
6542 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006543 Cand2.FinalConversion)) {
6544 case ImplicitConversionSequence::Better:
6545 // Cand1 has a better conversion sequence.
6546 return true;
6547
6548 case ImplicitConversionSequence::Worse:
6549 // Cand1 can't be better than Cand2.
6550 return false;
6551
6552 case ImplicitConversionSequence::Indistinguishable:
6553 // Do nothing
6554 break;
6555 }
6556 }
6557
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006558 return false;
6559}
6560
Mike Stump11289f42009-09-09 15:08:12 +00006561/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006562/// within an overload candidate set.
6563///
6564/// \param CandidateSet the set of candidate functions.
6565///
6566/// \param Loc the location of the function name (or operator symbol) for
6567/// which overload resolution occurs.
6568///
Mike Stump11289f42009-09-09 15:08:12 +00006569/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006570/// function, Best points to the candidate function found.
6571///
6572/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006573OverloadingResult
6574OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006575 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00006576 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006577 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006578 Best = end();
6579 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6580 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006581 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006582 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006583 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006584 }
6585
6586 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006587 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006588 return OR_No_Viable_Function;
6589
6590 // Make sure that this function is better than every other viable
6591 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006592 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006593 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006594 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006595 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006596 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006597 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006598 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006599 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006600 }
Mike Stump11289f42009-09-09 15:08:12 +00006601
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006602 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006603 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00006604 (Best->Function->isDeleted() ||
6605 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006606 return OR_Deleted;
6607
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006608 return OR_Success;
6609}
6610
John McCall53262c92010-01-12 02:15:36 +00006611namespace {
6612
6613enum OverloadCandidateKind {
6614 oc_function,
6615 oc_method,
6616 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006617 oc_function_template,
6618 oc_method_template,
6619 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006620 oc_implicit_default_constructor,
6621 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006622 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00006623 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006624 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00006625 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00006626};
6627
John McCalle1ac8d12010-01-13 00:25:19 +00006628OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6629 FunctionDecl *Fn,
6630 std::string &Description) {
6631 bool isTemplate = false;
6632
6633 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6634 isTemplate = true;
6635 Description = S.getTemplateArgumentBindingsText(
6636 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6637 }
John McCallfd0b2f82010-01-06 09:43:14 +00006638
6639 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006640 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006641 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006642
Sebastian Redl08905022011-02-05 19:23:19 +00006643 if (Ctor->getInheritedConstructor())
6644 return oc_implicit_inherited_constructor;
6645
Alexis Hunt119c10e2011-05-25 23:16:36 +00006646 if (Ctor->isDefaultConstructor())
6647 return oc_implicit_default_constructor;
6648
6649 if (Ctor->isMoveConstructor())
6650 return oc_implicit_move_constructor;
6651
6652 assert(Ctor->isCopyConstructor() &&
6653 "unexpected sort of implicit constructor");
6654 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006655 }
6656
6657 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6658 // This actually gets spelled 'candidate function' for now, but
6659 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006660 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006661 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006662
Alexis Hunt119c10e2011-05-25 23:16:36 +00006663 if (Meth->isMoveAssignmentOperator())
6664 return oc_implicit_move_assignment;
6665
Douglas Gregorec3bec02010-09-27 22:37:28 +00006666 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006667 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006668 return oc_implicit_copy_assignment;
6669 }
6670
John McCalle1ac8d12010-01-13 00:25:19 +00006671 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006672}
6673
Sebastian Redl08905022011-02-05 19:23:19 +00006674void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6675 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6676 if (!Ctor) return;
6677
6678 Ctor = Ctor->getInheritedConstructor();
6679 if (!Ctor) return;
6680
6681 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6682}
6683
John McCall53262c92010-01-12 02:15:36 +00006684} // end anonymous namespace
6685
6686// Notes the location of an overload candidate.
6687void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006688 std::string FnDesc;
6689 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6690 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6691 << (unsigned) K << FnDesc;
Sebastian Redl08905022011-02-05 19:23:19 +00006692 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00006693}
6694
Douglas Gregorb491ed32011-02-19 21:32:49 +00006695//Notes the location of all overload candidates designated through
6696// OverloadedExpr
6697void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6698 assert(OverloadedExpr->getType() == Context.OverloadTy);
6699
6700 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6701 OverloadExpr *OvlExpr = Ovl.Expression;
6702
6703 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6704 IEnd = OvlExpr->decls_end();
6705 I != IEnd; ++I) {
6706 if (FunctionTemplateDecl *FunTmpl =
6707 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6708 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6709 } else if (FunctionDecl *Fun
6710 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6711 NoteOverloadCandidate(Fun);
6712 }
6713 }
6714}
6715
John McCall0d1da222010-01-12 00:44:57 +00006716/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6717/// "lead" diagnostic; it will be given two arguments, the source and
6718/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006719void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6720 Sema &S,
6721 SourceLocation CaretLoc,
6722 const PartialDiagnostic &PDiag) const {
6723 S.Diag(CaretLoc, PDiag)
6724 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006725 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006726 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6727 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006728 }
John McCall12f97bc2010-01-08 04:41:39 +00006729}
6730
John McCall0d1da222010-01-12 00:44:57 +00006731namespace {
6732
John McCall6a61b522010-01-13 09:16:55 +00006733void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6734 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6735 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006736 assert(Cand->Function && "for now, candidate must be a function");
6737 FunctionDecl *Fn = Cand->Function;
6738
6739 // There's a conversion slot for the object argument if this is a
6740 // non-constructor method. Note that 'I' corresponds the
6741 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006742 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006743 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006744 if (I == 0)
6745 isObjectArgument = true;
6746 else
6747 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006748 }
6749
John McCalle1ac8d12010-01-13 00:25:19 +00006750 std::string FnDesc;
6751 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6752
John McCall6a61b522010-01-13 09:16:55 +00006753 Expr *FromExpr = Conv.Bad.FromExpr;
6754 QualType FromTy = Conv.Bad.getFromType();
6755 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006756
John McCallfb7ad0f2010-02-02 02:42:52 +00006757 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006758 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006759 Expr *E = FromExpr->IgnoreParens();
6760 if (isa<UnaryOperator>(E))
6761 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006762 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006763
6764 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6765 << (unsigned) FnKind << FnDesc
6766 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6767 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006768 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00006769 return;
6770 }
6771
John McCall6d174642010-01-23 08:10:49 +00006772 // Do some hand-waving analysis to see if the non-viability is due
6773 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006774 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6775 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6776 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6777 CToTy = RT->getPointeeType();
6778 else {
6779 // TODO: detect and diagnose the full richness of const mismatches.
6780 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6781 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6782 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6783 }
6784
6785 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6786 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6787 // It is dumb that we have to do this here.
6788 while (isa<ArrayType>(CFromTy))
6789 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6790 while (isa<ArrayType>(CToTy))
6791 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6792
6793 Qualifiers FromQs = CFromTy.getQualifiers();
6794 Qualifiers ToQs = CToTy.getQualifiers();
6795
6796 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6797 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6798 << (unsigned) FnKind << FnDesc
6799 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6800 << FromTy
6801 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6802 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006803 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006804 return;
6805 }
6806
John McCall31168b02011-06-15 23:02:42 +00006807 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00006808 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00006809 << (unsigned) FnKind << FnDesc
6810 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6811 << FromTy
6812 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
6813 << (unsigned) isObjectArgument << I+1;
6814 MaybeEmitInheritedConstructorNote(S, Fn);
6815 return;
6816 }
6817
Douglas Gregoraec25842011-04-26 23:16:46 +00006818 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
6819 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
6820 << (unsigned) FnKind << FnDesc
6821 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6822 << FromTy
6823 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
6824 << (unsigned) isObjectArgument << I+1;
6825 MaybeEmitInheritedConstructorNote(S, Fn);
6826 return;
6827 }
6828
John McCall47000992010-01-14 03:28:57 +00006829 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6830 assert(CVR && "unexpected qualifiers mismatch");
6831
6832 if (isObjectArgument) {
6833 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6834 << (unsigned) FnKind << FnDesc
6835 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6836 << FromTy << (CVR - 1);
6837 } else {
6838 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6839 << (unsigned) FnKind << FnDesc
6840 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6841 << FromTy << (CVR - 1) << I+1;
6842 }
Sebastian Redl08905022011-02-05 19:23:19 +00006843 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006844 return;
6845 }
6846
John McCall6d174642010-01-23 08:10:49 +00006847 // Diagnose references or pointers to incomplete types differently,
6848 // since it's far from impossible that the incompleteness triggered
6849 // the failure.
6850 QualType TempFromTy = FromTy.getNonReferenceType();
6851 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6852 TempFromTy = PTy->getPointeeType();
6853 if (TempFromTy->isIncompleteType()) {
6854 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6855 << (unsigned) FnKind << FnDesc
6856 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6857 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006858 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00006859 return;
6860 }
6861
Douglas Gregor56f2e342010-06-30 23:01:39 +00006862 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006863 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006864 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6865 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6866 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6867 FromPtrTy->getPointeeType()) &&
6868 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6869 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006870 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00006871 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006872 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006873 }
6874 } else if (const ObjCObjectPointerType *FromPtrTy
6875 = FromTy->getAs<ObjCObjectPointerType>()) {
6876 if (const ObjCObjectPointerType *ToPtrTy
6877 = ToTy->getAs<ObjCObjectPointerType>())
6878 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6879 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6880 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6881 FromPtrTy->getPointeeType()) &&
6882 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006883 BaseToDerivedConversion = 2;
6884 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6885 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6886 !FromTy->isIncompleteType() &&
6887 !ToRefTy->getPointeeType()->isIncompleteType() &&
6888 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6889 BaseToDerivedConversion = 3;
6890 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006891
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006892 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006893 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006894 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006895 << (unsigned) FnKind << FnDesc
6896 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006897 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006898 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006899 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00006900 return;
6901 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006902
John McCall47000992010-01-14 03:28:57 +00006903 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00006904 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6905 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006906 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006907 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006908 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00006909}
6910
6911void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6912 unsigned NumFormalArgs) {
6913 // TODO: treat calls to a missing default constructor as a special case
6914
6915 FunctionDecl *Fn = Cand->Function;
6916 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6917
6918 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006919
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00006920 // With invalid overloaded operators, it's possible that we think we
6921 // have an arity mismatch when it fact it looks like we have the
6922 // right number of arguments, because only overloaded operators have
6923 // the weird behavior of overloading member and non-member functions.
6924 // Just don't report anything.
6925 if (Fn->isInvalidDecl() &&
6926 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
6927 return;
6928
John McCall6a61b522010-01-13 09:16:55 +00006929 // at least / at most / exactly
6930 unsigned mode, modeCount;
6931 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006932 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6933 (Cand->FailureKind == ovl_fail_bad_deduction &&
6934 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006935 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00006936 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00006937 mode = 0; // "at least"
6938 else
6939 mode = 2; // "exactly"
6940 modeCount = MinParams;
6941 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006942 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6943 (Cand->FailureKind == ovl_fail_bad_deduction &&
6944 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006945 if (MinParams != FnTy->getNumArgs())
6946 mode = 1; // "at most"
6947 else
6948 mode = 2; // "exactly"
6949 modeCount = FnTy->getNumArgs();
6950 }
6951
6952 std::string Description;
6953 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6954
6955 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006956 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00006957 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00006958 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006959}
6960
John McCall8b9ed552010-02-01 18:53:26 +00006961/// Diagnose a failed template-argument deduction.
6962void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6963 Expr **Args, unsigned NumArgs) {
6964 FunctionDecl *Fn = Cand->Function; // pattern
6965
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006966 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006967 NamedDecl *ParamD;
6968 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6969 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6970 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006971 switch (Cand->DeductionFailure.Result) {
6972 case Sema::TDK_Success:
6973 llvm_unreachable("TDK_success while diagnosing bad deduction");
6974
6975 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006976 assert(ParamD && "no parameter found for incomplete deduction result");
6977 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6978 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00006979 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00006980 return;
6981 }
6982
John McCall42d7d192010-08-05 09:05:08 +00006983 case Sema::TDK_Underqualified: {
6984 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6985 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6986
6987 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6988
6989 // Param will have been canonicalized, but it should just be a
6990 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00006991 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00006992 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00006993 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00006994 assert(S.Context.hasSameType(Param, NonCanonParam));
6995
6996 // Arg has also been canonicalized, but there's nothing we can do
6997 // about that. It also doesn't matter as much, because it won't
6998 // have any template parameters in it (because deduction isn't
6999 // done on dependent types).
7000 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7001
7002 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7003 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007004 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007005 return;
7006 }
7007
7008 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007009 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007010 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007011 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007012 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007013 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007014 which = 1;
7015 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007016 which = 2;
7017 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007018
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007019 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007020 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007021 << *Cand->DeductionFailure.getFirstArg()
7022 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007023 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007024 return;
7025 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007026
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007027 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007028 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007029 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007030 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007031 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7032 << ParamD->getDeclName();
7033 else {
7034 int index = 0;
7035 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7036 index = TTP->getIndex();
7037 else if (NonTypeTemplateParmDecl *NTTP
7038 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7039 index = NTTP->getIndex();
7040 else
7041 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007042 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007043 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7044 << (index + 1);
7045 }
Sebastian Redl08905022011-02-05 19:23:19 +00007046 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007047 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007048
Douglas Gregor02eb4832010-05-08 18:13:28 +00007049 case Sema::TDK_TooManyArguments:
7050 case Sema::TDK_TooFewArguments:
7051 DiagnoseArityMismatch(S, Cand, NumArgs);
7052 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007053
7054 case Sema::TDK_InstantiationDepth:
7055 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007056 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007057 return;
7058
7059 case Sema::TDK_SubstitutionFailure: {
7060 std::string ArgString;
7061 if (TemplateArgumentList *Args
7062 = Cand->DeductionFailure.getTemplateArgumentList())
7063 ArgString = S.getTemplateArgumentBindingsText(
7064 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7065 *Args);
7066 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7067 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007068 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007069 return;
7070 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007071
John McCall8b9ed552010-02-01 18:53:26 +00007072 // TODO: diagnose these individually, then kill off
7073 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007074 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007075 case Sema::TDK_FailedOverloadResolution:
7076 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007077 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007078 return;
7079 }
7080}
7081
7082/// Generates a 'note' diagnostic for an overload candidate. We've
7083/// already generated a primary error at the call site.
7084///
7085/// It really does need to be a single diagnostic with its caret
7086/// pointed at the candidate declaration. Yes, this creates some
7087/// major challenges of technical writing. Yes, this makes pointing
7088/// out problems with specific arguments quite awkward. It's still
7089/// better than generating twenty screens of text for every failed
7090/// overload.
7091///
7092/// It would be great to be able to express per-candidate problems
7093/// more richly for those diagnostic clients that cared, but we'd
7094/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007095void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7096 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007097 FunctionDecl *Fn = Cand->Function;
7098
John McCall12f97bc2010-01-08 04:41:39 +00007099 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007100 if (Cand->Viable && (Fn->isDeleted() ||
7101 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007102 std::string FnDesc;
7103 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007104
7105 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007106 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007107 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007108 return;
John McCall12f97bc2010-01-08 04:41:39 +00007109 }
7110
John McCalle1ac8d12010-01-13 00:25:19 +00007111 // We don't really have anything else to say about viable candidates.
7112 if (Cand->Viable) {
7113 S.NoteOverloadCandidate(Fn);
7114 return;
7115 }
John McCall0d1da222010-01-12 00:44:57 +00007116
John McCall6a61b522010-01-13 09:16:55 +00007117 switch (Cand->FailureKind) {
7118 case ovl_fail_too_many_arguments:
7119 case ovl_fail_too_few_arguments:
7120 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007121
John McCall6a61b522010-01-13 09:16:55 +00007122 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007123 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7124
John McCallfe796dd2010-01-23 05:17:32 +00007125 case ovl_fail_trivial_conversion:
7126 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007127 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007128 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007129
John McCall65eb8792010-02-25 01:37:24 +00007130 case ovl_fail_bad_conversion: {
7131 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7132 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007133 if (Cand->Conversions[I].isBad())
7134 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007135
John McCall6a61b522010-01-13 09:16:55 +00007136 // FIXME: this currently happens when we're called from SemaInit
7137 // when user-conversion overload fails. Figure out how to handle
7138 // those conditions and diagnose them well.
7139 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007140 }
John McCall65eb8792010-02-25 01:37:24 +00007141 }
John McCalld3224162010-01-08 00:58:21 +00007142}
7143
7144void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7145 // Desugar the type of the surrogate down to a function type,
7146 // retaining as many typedefs as possible while still showing
7147 // the function type (and, therefore, its parameter types).
7148 QualType FnType = Cand->Surrogate->getConversionType();
7149 bool isLValueReference = false;
7150 bool isRValueReference = false;
7151 bool isPointer = false;
7152 if (const LValueReferenceType *FnTypeRef =
7153 FnType->getAs<LValueReferenceType>()) {
7154 FnType = FnTypeRef->getPointeeType();
7155 isLValueReference = true;
7156 } else if (const RValueReferenceType *FnTypeRef =
7157 FnType->getAs<RValueReferenceType>()) {
7158 FnType = FnTypeRef->getPointeeType();
7159 isRValueReference = true;
7160 }
7161 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7162 FnType = FnTypePtr->getPointeeType();
7163 isPointer = true;
7164 }
7165 // Desugar down to a function type.
7166 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7167 // Reconstruct the pointer/reference as appropriate.
7168 if (isPointer) FnType = S.Context.getPointerType(FnType);
7169 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7170 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7171
7172 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7173 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007174 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007175}
7176
7177void NoteBuiltinOperatorCandidate(Sema &S,
7178 const char *Opc,
7179 SourceLocation OpLoc,
7180 OverloadCandidate *Cand) {
7181 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7182 std::string TypeStr("operator");
7183 TypeStr += Opc;
7184 TypeStr += "(";
7185 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7186 if (Cand->Conversions.size() == 1) {
7187 TypeStr += ")";
7188 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7189 } else {
7190 TypeStr += ", ";
7191 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7192 TypeStr += ")";
7193 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7194 }
7195}
7196
7197void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7198 OverloadCandidate *Cand) {
7199 unsigned NoOperands = Cand->Conversions.size();
7200 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7201 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007202 if (ICS.isBad()) break; // all meaningless after first invalid
7203 if (!ICS.isAmbiguous()) continue;
7204
John McCall5c32be02010-08-24 20:38:10 +00007205 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007206 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007207 }
7208}
7209
John McCall3712d9e2010-01-15 23:32:50 +00007210SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7211 if (Cand->Function)
7212 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007213 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007214 return Cand->Surrogate->getLocation();
7215 return SourceLocation();
7216}
7217
John McCallad2587a2010-01-12 00:48:53 +00007218struct CompareOverloadCandidatesForDisplay {
7219 Sema &S;
7220 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007221
7222 bool operator()(const OverloadCandidate *L,
7223 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007224 // Fast-path this check.
7225 if (L == R) return false;
7226
John McCall12f97bc2010-01-08 04:41:39 +00007227 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007228 if (L->Viable) {
7229 if (!R->Viable) return true;
7230
7231 // TODO: introduce a tri-valued comparison for overload
7232 // candidates. Would be more worthwhile if we had a sort
7233 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007234 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7235 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007236 } else if (R->Viable)
7237 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007238
John McCall3712d9e2010-01-15 23:32:50 +00007239 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007240
John McCall3712d9e2010-01-15 23:32:50 +00007241 // Criteria by which we can sort non-viable candidates:
7242 if (!L->Viable) {
7243 // 1. Arity mismatches come after other candidates.
7244 if (L->FailureKind == ovl_fail_too_many_arguments ||
7245 L->FailureKind == ovl_fail_too_few_arguments)
7246 return false;
7247 if (R->FailureKind == ovl_fail_too_many_arguments ||
7248 R->FailureKind == ovl_fail_too_few_arguments)
7249 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007250
John McCallfe796dd2010-01-23 05:17:32 +00007251 // 2. Bad conversions come first and are ordered by the number
7252 // of bad conversions and quality of good conversions.
7253 if (L->FailureKind == ovl_fail_bad_conversion) {
7254 if (R->FailureKind != ovl_fail_bad_conversion)
7255 return true;
7256
7257 // If there's any ordering between the defined conversions...
7258 // FIXME: this might not be transitive.
7259 assert(L->Conversions.size() == R->Conversions.size());
7260
7261 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007262 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7263 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007264 switch (CompareImplicitConversionSequences(S,
7265 L->Conversions[I],
7266 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007267 case ImplicitConversionSequence::Better:
7268 leftBetter++;
7269 break;
7270
7271 case ImplicitConversionSequence::Worse:
7272 leftBetter--;
7273 break;
7274
7275 case ImplicitConversionSequence::Indistinguishable:
7276 break;
7277 }
7278 }
7279 if (leftBetter > 0) return true;
7280 if (leftBetter < 0) return false;
7281
7282 } else if (R->FailureKind == ovl_fail_bad_conversion)
7283 return false;
7284
John McCall3712d9e2010-01-15 23:32:50 +00007285 // TODO: others?
7286 }
7287
7288 // Sort everything else by location.
7289 SourceLocation LLoc = GetLocationForCandidate(L);
7290 SourceLocation RLoc = GetLocationForCandidate(R);
7291
7292 // Put candidates without locations (e.g. builtins) at the end.
7293 if (LLoc.isInvalid()) return false;
7294 if (RLoc.isInvalid()) return true;
7295
7296 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007297 }
7298};
7299
John McCallfe796dd2010-01-23 05:17:32 +00007300/// CompleteNonViableCandidate - Normally, overload resolution only
7301/// computes up to the first
7302void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7303 Expr **Args, unsigned NumArgs) {
7304 assert(!Cand->Viable);
7305
7306 // Don't do anything on failures other than bad conversion.
7307 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7308
7309 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007310 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00007311 unsigned ConvCount = Cand->Conversions.size();
7312 while (true) {
7313 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7314 ConvIdx++;
7315 if (Cand->Conversions[ConvIdx - 1].isBad())
7316 break;
7317 }
7318
7319 if (ConvIdx == ConvCount)
7320 return;
7321
John McCall65eb8792010-02-25 01:37:24 +00007322 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7323 "remaining conversion is initialized?");
7324
Douglas Gregoradc7a702010-04-16 17:45:54 +00007325 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007326 // operation somehow.
7327 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007328
7329 const FunctionProtoType* Proto;
7330 unsigned ArgIdx = ConvIdx;
7331
7332 if (Cand->IsSurrogate) {
7333 QualType ConvType
7334 = Cand->Surrogate->getConversionType().getNonReferenceType();
7335 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7336 ConvType = ConvPtrType->getPointeeType();
7337 Proto = ConvType->getAs<FunctionProtoType>();
7338 ArgIdx--;
7339 } else if (Cand->Function) {
7340 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7341 if (isa<CXXMethodDecl>(Cand->Function) &&
7342 !isa<CXXConstructorDecl>(Cand->Function))
7343 ArgIdx--;
7344 } else {
7345 // Builtin binary operator with a bad first conversion.
7346 assert(ConvCount <= 3);
7347 for (; ConvIdx != ConvCount; ++ConvIdx)
7348 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007349 = TryCopyInitialization(S, Args[ConvIdx],
7350 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007351 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007352 /*InOverloadResolution*/ true,
7353 /*AllowObjCWritebackConversion=*/
7354 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00007355 return;
7356 }
7357
7358 // Fill in the rest of the conversions.
7359 unsigned NumArgsInProto = Proto->getNumArgs();
7360 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
7361 if (ArgIdx < NumArgsInProto)
7362 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007363 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007364 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007365 /*InOverloadResolution=*/true,
7366 /*AllowObjCWritebackConversion=*/
7367 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00007368 else
7369 Cand->Conversions[ConvIdx].setEllipsis();
7370 }
7371}
7372
John McCalld3224162010-01-08 00:58:21 +00007373} // end anonymous namespace
7374
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007375/// PrintOverloadCandidates - When overload resolution fails, prints
7376/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007377/// set.
John McCall5c32be02010-08-24 20:38:10 +00007378void OverloadCandidateSet::NoteCandidates(Sema &S,
7379 OverloadCandidateDisplayKind OCD,
7380 Expr **Args, unsigned NumArgs,
7381 const char *Opc,
7382 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007383 // Sort the candidates by viability and position. Sorting directly would
7384 // be prohibitive, so we make a set of pointers and sort those.
7385 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007386 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7387 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007388 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007389 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007390 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007391 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007392 if (Cand->Function || Cand->IsSurrogate)
7393 Cands.push_back(Cand);
7394 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7395 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007396 }
7397 }
7398
John McCallad2587a2010-01-12 00:48:53 +00007399 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007400 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007401
John McCall0d1da222010-01-12 00:44:57 +00007402 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007403
John McCall12f97bc2010-01-08 04:41:39 +00007404 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00007405 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007406 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007407 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7408 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007409
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007410 // Set an arbitrary limit on the number of candidate functions we'll spam
7411 // the user with. FIXME: This limit should depend on details of the
7412 // candidate list.
7413 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
7414 break;
7415 }
7416 ++CandsShown;
7417
John McCalld3224162010-01-08 00:58:21 +00007418 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007419 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007420 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007421 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007422 else {
7423 assert(Cand->Viable &&
7424 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007425 // Generally we only see ambiguities including viable builtin
7426 // operators if overload resolution got screwed up by an
7427 // ambiguous user-defined conversion.
7428 //
7429 // FIXME: It's quite possible for different conversions to see
7430 // different ambiguities, though.
7431 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007432 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007433 ReportedAmbiguousConversions = true;
7434 }
John McCalld3224162010-01-08 00:58:21 +00007435
John McCall0d1da222010-01-12 00:44:57 +00007436 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007437 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007438 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007439 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007440
7441 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007442 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007443}
7444
Douglas Gregorb491ed32011-02-19 21:32:49 +00007445// [PossiblyAFunctionType] --> [Return]
7446// NonFunctionType --> NonFunctionType
7447// R (A) --> R(A)
7448// R (*)(A) --> R (A)
7449// R (&)(A) --> R (A)
7450// R (S::*)(A) --> R (A)
7451QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7452 QualType Ret = PossiblyAFunctionType;
7453 if (const PointerType *ToTypePtr =
7454 PossiblyAFunctionType->getAs<PointerType>())
7455 Ret = ToTypePtr->getPointeeType();
7456 else if (const ReferenceType *ToTypeRef =
7457 PossiblyAFunctionType->getAs<ReferenceType>())
7458 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007459 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007460 PossiblyAFunctionType->getAs<MemberPointerType>())
7461 Ret = MemTypePtr->getPointeeType();
7462 Ret =
7463 Context.getCanonicalType(Ret).getUnqualifiedType();
7464 return Ret;
7465}
Douglas Gregorcd695e52008-11-10 20:40:00 +00007466
Douglas Gregorb491ed32011-02-19 21:32:49 +00007467// A helper class to help with address of function resolution
7468// - allows us to avoid passing around all those ugly parameters
7469class AddressOfFunctionResolver
7470{
7471 Sema& S;
7472 Expr* SourceExpr;
7473 const QualType& TargetType;
7474 QualType TargetFunctionType; // Extracted function type from target type
7475
7476 bool Complain;
7477 //DeclAccessPair& ResultFunctionAccessPair;
7478 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007479
Douglas Gregorb491ed32011-02-19 21:32:49 +00007480 bool TargetTypeIsNonStaticMemberFunction;
7481 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007482
Douglas Gregorb491ed32011-02-19 21:32:49 +00007483 OverloadExpr::FindResult OvlExprInfo;
7484 OverloadExpr *OvlExpr;
7485 TemplateArgumentListInfo OvlExplicitTemplateArgs;
John McCalla0296f72010-03-19 07:35:19 +00007486 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007487
Douglas Gregorb491ed32011-02-19 21:32:49 +00007488public:
7489 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7490 const QualType& TargetType, bool Complain)
7491 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7492 Complain(Complain), Context(S.getASTContext()),
7493 TargetTypeIsNonStaticMemberFunction(
7494 !!TargetType->getAs<MemberPointerType>()),
7495 FoundNonTemplateFunction(false),
7496 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7497 OvlExpr(OvlExprInfo.Expression)
7498 {
7499 ExtractUnqualifiedFunctionTypeFromTargetType();
7500
7501 if (!TargetFunctionType->isFunctionType()) {
7502 if (OvlExpr->hasExplicitTemplateArgs()) {
7503 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00007504 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00007505 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00007506
7507 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7508 if (!Method->isStatic()) {
7509 // If the target type is a non-function type and the function
7510 // found is a non-static member function, pretend as if that was
7511 // the target, it's the only possible type to end up with.
7512 TargetTypeIsNonStaticMemberFunction = true;
7513
7514 // And skip adding the function if its not in the proper form.
7515 // We'll diagnose this due to an empty set of functions.
7516 if (!OvlExprInfo.HasFormOfMemberPointer)
7517 return;
7518 }
7519 }
7520
Douglas Gregorb491ed32011-02-19 21:32:49 +00007521 Matches.push_back(std::make_pair(dap,Fn));
7522 }
Douglas Gregor9b146582009-07-08 20:55:45 +00007523 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007524 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00007525 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007526
7527 if (OvlExpr->hasExplicitTemplateArgs())
7528 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00007529
Douglas Gregorb491ed32011-02-19 21:32:49 +00007530 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7531 // C++ [over.over]p4:
7532 // If more than one function is selected, [...]
7533 if (Matches.size() > 1) {
7534 if (FoundNonTemplateFunction)
7535 EliminateAllTemplateMatches();
7536 else
7537 EliminateAllExceptMostSpecializedTemplate();
7538 }
7539 }
7540 }
7541
7542private:
7543 bool isTargetTypeAFunction() const {
7544 return TargetFunctionType->isFunctionType();
7545 }
7546
7547 // [ToType] [Return]
7548
7549 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7550 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7551 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7552 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7553 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7554 }
7555
7556 // return true if any matching specializations were found
7557 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7558 const DeclAccessPair& CurAccessFunPair) {
7559 if (CXXMethodDecl *Method
7560 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7561 // Skip non-static function templates when converting to pointer, and
7562 // static when converting to member pointer.
7563 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7564 return false;
7565 }
7566 else if (TargetTypeIsNonStaticMemberFunction)
7567 return false;
7568
7569 // C++ [over.over]p2:
7570 // If the name is a function template, template argument deduction is
7571 // done (14.8.2.2), and if the argument deduction succeeds, the
7572 // resulting template argument list is used to generate a single
7573 // function template specialization, which is added to the set of
7574 // overloaded functions considered.
7575 FunctionDecl *Specialization = 0;
7576 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7577 if (Sema::TemplateDeductionResult Result
7578 = S.DeduceTemplateArguments(FunctionTemplate,
7579 &OvlExplicitTemplateArgs,
7580 TargetFunctionType, Specialization,
7581 Info)) {
7582 // FIXME: make a note of the failed deduction for diagnostics.
7583 (void)Result;
7584 return false;
7585 }
7586
7587 // Template argument deduction ensures that we have an exact match.
7588 // This function template specicalization works.
7589 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7590 assert(TargetFunctionType
7591 == Context.getCanonicalType(Specialization->getType()));
7592 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7593 return true;
7594 }
7595
7596 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7597 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007598 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007599 // Skip non-static functions when converting to pointer, and static
7600 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007601 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7602 return false;
7603 }
7604 else if (TargetTypeIsNonStaticMemberFunction)
7605 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007606
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007607 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007608 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007609 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7610 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00007611 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
7612 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007613 Matches.push_back(std::make_pair(CurAccessFunPair,
7614 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007615 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007616 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007617 }
Mike Stump11289f42009-09-09 15:08:12 +00007618 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007619
7620 return false;
7621 }
7622
7623 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7624 bool Ret = false;
7625
7626 // If the overload expression doesn't have the form of a pointer to
7627 // member, don't try to convert it to a pointer-to-member type.
7628 if (IsInvalidFormOfPointerToMemberFunction())
7629 return false;
7630
7631 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7632 E = OvlExpr->decls_end();
7633 I != E; ++I) {
7634 // Look through any using declarations to find the underlying function.
7635 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7636
7637 // C++ [over.over]p3:
7638 // Non-member functions and static member functions match
7639 // targets of type "pointer-to-function" or "reference-to-function."
7640 // Nonstatic member functions match targets of
7641 // type "pointer-to-member-function."
7642 // Note that according to DR 247, the containing class does not matter.
7643 if (FunctionTemplateDecl *FunctionTemplate
7644 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7645 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7646 Ret = true;
7647 }
7648 // If we have explicit template arguments supplied, skip non-templates.
7649 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7650 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7651 Ret = true;
7652 }
7653 assert(Ret || Matches.empty());
7654 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007655 }
7656
Douglas Gregorb491ed32011-02-19 21:32:49 +00007657 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00007658 // [...] and any given function template specialization F1 is
7659 // eliminated if the set contains a second function template
7660 // specialization whose function template is more specialized
7661 // than the function template of F1 according to the partial
7662 // ordering rules of 14.5.5.2.
7663
7664 // The algorithm specified above is quadratic. We instead use a
7665 // two-pass algorithm (similar to the one used to identify the
7666 // best viable function in an overload set) that identifies the
7667 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00007668
7669 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7670 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7671 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007672
John McCall58cc69d2010-01-27 01:50:18 +00007673 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007674 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7675 TPOC_Other, 0, SourceExpr->getLocStart(),
7676 S.PDiag(),
7677 S.PDiag(diag::err_addr_ovl_ambiguous)
7678 << Matches[0].second->getDeclName(),
7679 S.PDiag(diag::note_ovl_candidate)
7680 << (unsigned) oc_function_template,
7681 Complain);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007682
Douglas Gregorb491ed32011-02-19 21:32:49 +00007683 if (Result != MatchesCopy.end()) {
7684 // Make it the first and only element
7685 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7686 Matches[0].second = cast<FunctionDecl>(*Result);
7687 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00007688 }
7689 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007690
Douglas Gregorb491ed32011-02-19 21:32:49 +00007691 void EliminateAllTemplateMatches() {
7692 // [...] any function template specializations in the set are
7693 // eliminated if the set also contains a non-template function, [...]
7694 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7695 if (Matches[I].second->getPrimaryTemplate() == 0)
7696 ++I;
7697 else {
7698 Matches[I] = Matches[--N];
7699 Matches.set_size(N);
7700 }
7701 }
7702 }
7703
7704public:
7705 void ComplainNoMatchesFound() const {
7706 assert(Matches.empty());
7707 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7708 << OvlExpr->getName() << TargetFunctionType
7709 << OvlExpr->getSourceRange();
7710 S.NoteAllOverloadCandidates(OvlExpr);
7711 }
7712
7713 bool IsInvalidFormOfPointerToMemberFunction() const {
7714 return TargetTypeIsNonStaticMemberFunction &&
7715 !OvlExprInfo.HasFormOfMemberPointer;
7716 }
7717
7718 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7719 // TODO: Should we condition this on whether any functions might
7720 // have matched, or is it more appropriate to do that in callers?
7721 // TODO: a fixit wouldn't hurt.
7722 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7723 << TargetType << OvlExpr->getSourceRange();
7724 }
7725
7726 void ComplainOfInvalidConversion() const {
7727 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7728 << OvlExpr->getName() << TargetType;
7729 }
7730
7731 void ComplainMultipleMatchesFound() const {
7732 assert(Matches.size() > 1);
7733 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7734 << OvlExpr->getName()
7735 << OvlExpr->getSourceRange();
7736 S.NoteAllOverloadCandidates(OvlExpr);
7737 }
7738
7739 int getNumMatches() const { return Matches.size(); }
7740
7741 FunctionDecl* getMatchingFunctionDecl() const {
7742 if (Matches.size() != 1) return 0;
7743 return Matches[0].second;
7744 }
7745
7746 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7747 if (Matches.size() != 1) return 0;
7748 return &Matches[0].first;
7749 }
7750};
7751
7752/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7753/// an overloaded function (C++ [over.over]), where @p From is an
7754/// expression with overloaded function type and @p ToType is the type
7755/// we're trying to resolve to. For example:
7756///
7757/// @code
7758/// int f(double);
7759/// int f(int);
7760///
7761/// int (*pfd)(double) = f; // selects f(double)
7762/// @endcode
7763///
7764/// This routine returns the resulting FunctionDecl if it could be
7765/// resolved, and NULL otherwise. When @p Complain is true, this
7766/// routine will emit diagnostics if there is an error.
7767FunctionDecl *
7768Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7769 bool Complain,
7770 DeclAccessPair &FoundResult) {
7771
7772 assert(AddressOfExpr->getType() == Context.OverloadTy);
7773
7774 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7775 int NumMatches = Resolver.getNumMatches();
7776 FunctionDecl* Fn = 0;
7777 if ( NumMatches == 0 && Complain) {
7778 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7779 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7780 else
7781 Resolver.ComplainNoMatchesFound();
7782 }
7783 else if (NumMatches > 1 && Complain)
7784 Resolver.ComplainMultipleMatchesFound();
7785 else if (NumMatches == 1) {
7786 Fn = Resolver.getMatchingFunctionDecl();
7787 assert(Fn);
7788 FoundResult = *Resolver.getMatchingFunctionAccessPair();
7789 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007790 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00007791 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007792 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007793
7794 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007795}
7796
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007797/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007798/// resolve that overloaded function expression down to a single function.
7799///
7800/// This routine can only resolve template-ids that refer to a single function
7801/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007802/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007803/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00007804FunctionDecl *
7805Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
7806 bool Complain,
7807 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007808 // C++ [over.over]p1:
7809 // [...] [Note: any redundant set of parentheses surrounding the
7810 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007811 // C++ [over.over]p1:
7812 // [...] The overloaded function name can be preceded by the &
7813 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007814
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007815 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00007816 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007817 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007818
7819 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00007820 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007821
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007822 // Look through all of the overloaded functions, searching for one
7823 // whose type matches exactly.
7824 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00007825 for (UnresolvedSetIterator I = ovl->decls_begin(),
7826 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007827 // C++0x [temp.arg.explicit]p3:
7828 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007829 // where deduction is not done, if a template argument list is
7830 // specified and it, along with any default template arguments,
7831 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007832 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00007833 FunctionTemplateDecl *FunctionTemplate
7834 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007835
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007836 // C++ [over.over]p2:
7837 // If the name is a function template, template argument deduction is
7838 // done (14.8.2.2), and if the argument deduction succeeds, the
7839 // resulting template argument list is used to generate a single
7840 // function template specialization, which is added to the set of
7841 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007842 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00007843 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007844 if (TemplateDeductionResult Result
7845 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7846 Specialization, Info)) {
7847 // FIXME: make a note of the failed deduction for diagnostics.
7848 (void)Result;
7849 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007850 }
7851
John McCall0009fcc2011-04-26 20:42:42 +00007852 assert(Specialization && "no specialization and no error?");
7853
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007854 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007855 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007856 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00007857 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
7858 << ovl->getName();
7859 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007860 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007861 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00007862 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007863
John McCall0009fcc2011-04-26 20:42:42 +00007864 Matched = Specialization;
7865 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007866 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007867
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007868 return Matched;
7869}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007870
Douglas Gregor1beec452011-03-12 01:48:56 +00007871
7872
7873
7874// Resolve and fix an overloaded expression that
7875// can be resolved because it identifies a single function
7876// template specialization
7877// Last three arguments should only be supplied if Complain = true
7878ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
John McCall0009fcc2011-04-26 20:42:42 +00007879 Expr *SrcExpr, bool doFunctionPointerConverion, bool complain,
Douglas Gregor1beec452011-03-12 01:48:56 +00007880 const SourceRange& OpRangeForComplaining,
7881 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00007882 unsigned DiagIDForComplaining) {
7883 assert(SrcExpr->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00007884
John McCall0009fcc2011-04-26 20:42:42 +00007885 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr);
Douglas Gregor1beec452011-03-12 01:48:56 +00007886
John McCall0009fcc2011-04-26 20:42:42 +00007887 DeclAccessPair found;
7888 ExprResult SingleFunctionExpression;
7889 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
7890 ovl.Expression, /*complain*/ false, &found)) {
7891 if (DiagnoseUseOfDecl(fn, SrcExpr->getSourceRange().getBegin()))
7892 return ExprError();
7893
7894 // It is only correct to resolve to an instance method if we're
7895 // resolving a form that's permitted to be a pointer to member.
7896 // Otherwise we'll end up making a bound member expression, which
7897 // is illegal in all the contexts we resolve like this.
7898 if (!ovl.HasFormOfMemberPointer &&
7899 isa<CXXMethodDecl>(fn) &&
7900 cast<CXXMethodDecl>(fn)->isInstance()) {
7901 if (complain) {
7902 Diag(ovl.Expression->getExprLoc(),
7903 diag::err_invalid_use_of_bound_member_func)
7904 << ovl.Expression->getSourceRange();
7905 // TODO: I believe we only end up here if there's a mix of
7906 // static and non-static candidates (otherwise the expression
7907 // would have 'bound member' type, not 'overload' type).
7908 // Ideally we would note which candidate was chosen and why
7909 // the static candidates were rejected.
7910 }
7911
Douglas Gregor89f3cd52011-03-16 19:16:25 +00007912 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00007913 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00007914
John McCall0009fcc2011-04-26 20:42:42 +00007915 // Fix the expresion to refer to 'fn'.
7916 SingleFunctionExpression =
7917 Owned(FixOverloadedFunctionReference(SrcExpr, found, fn));
7918
7919 // If desired, do function-to-pointer decay.
7920 if (doFunctionPointerConverion)
7921 SingleFunctionExpression =
7922 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
7923 }
7924
7925 if (!SingleFunctionExpression.isUsable()) {
7926 if (complain) {
7927 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
7928 << ovl.Expression->getName()
7929 << DestTypeForComplaining
7930 << OpRangeForComplaining
7931 << ovl.Expression->getQualifierLoc().getSourceRange();
7932 NoteAllOverloadCandidates(SrcExpr);
7933 }
7934 return ExprError();
7935 }
7936
7937 return SingleFunctionExpression;
Douglas Gregor1beec452011-03-12 01:48:56 +00007938}
7939
Douglas Gregorcabea402009-09-22 15:41:20 +00007940/// \brief Add a single candidate to the overload set.
7941static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00007942 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007943 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007944 Expr **Args, unsigned NumArgs,
7945 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00007946 bool PartialOverloading,
7947 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00007948 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00007949 if (isa<UsingShadowDecl>(Callee))
7950 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7951
Douglas Gregorcabea402009-09-22 15:41:20 +00007952 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00007953 if (ExplicitTemplateArgs) {
7954 assert(!KnownValid && "Explicit template arguments?");
7955 return;
7956 }
John McCalla0296f72010-03-19 07:35:19 +00007957 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007958 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007959 return;
John McCalld14a8642009-11-21 08:51:07 +00007960 }
7961
7962 if (FunctionTemplateDecl *FuncTemplate
7963 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00007964 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7965 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007966 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00007967 return;
7968 }
7969
Richard Smith95ce4f62011-06-26 22:19:54 +00007970 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00007971}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007972
Douglas Gregorcabea402009-09-22 15:41:20 +00007973/// \brief Add the overload candidates named by callee and/or found by argument
7974/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00007975void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00007976 Expr **Args, unsigned NumArgs,
7977 OverloadCandidateSet &CandidateSet,
7978 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00007979
7980#ifndef NDEBUG
7981 // Verify that ArgumentDependentLookup is consistent with the rules
7982 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00007983 //
Douglas Gregorcabea402009-09-22 15:41:20 +00007984 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7985 // and let Y be the lookup set produced by argument dependent
7986 // lookup (defined as follows). If X contains
7987 //
7988 // -- a declaration of a class member, or
7989 //
7990 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00007991 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00007992 //
7993 // -- a declaration that is neither a function or a function
7994 // template
7995 //
7996 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00007997
John McCall57500772009-12-16 12:17:52 +00007998 if (ULE->requiresADL()) {
7999 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8000 E = ULE->decls_end(); I != E; ++I) {
8001 assert(!(*I)->getDeclContext()->isRecord());
8002 assert(isa<UsingShadowDecl>(*I) ||
8003 !(*I)->getDeclContext()->isFunctionOrMethod());
8004 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008005 }
8006 }
8007#endif
8008
John McCall57500772009-12-16 12:17:52 +00008009 // It would be nice to avoid this copy.
8010 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008011 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008012 if (ULE->hasExplicitTemplateArgs()) {
8013 ULE->copyTemplateArgumentsInto(TABuffer);
8014 ExplicitTemplateArgs = &TABuffer;
8015 }
8016
8017 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8018 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008019 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008020 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008021 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008022
John McCall57500772009-12-16 12:17:52 +00008023 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008024 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8025 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008026 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008027 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008028 PartialOverloading,
8029 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008030}
John McCalld681c392009-12-16 08:11:27 +00008031
Richard Smith998a5912011-06-05 22:42:48 +00008032/// Attempt to recover from an ill-formed use of a non-dependent name in a
8033/// template, where the non-dependent name was declared after the template
8034/// was defined. This is common in code written for a compilers which do not
8035/// correctly implement two-stage name lookup.
8036///
8037/// Returns true if a viable candidate was found and a diagnostic was issued.
8038static bool
8039DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8040 const CXXScopeSpec &SS, LookupResult &R,
8041 TemplateArgumentListInfo *ExplicitTemplateArgs,
8042 Expr **Args, unsigned NumArgs) {
8043 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8044 return false;
8045
8046 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8047 SemaRef.LookupQualifiedName(R, DC);
8048
8049 if (!R.empty()) {
8050 R.suppressDiagnostics();
8051
8052 if (isa<CXXRecordDecl>(DC)) {
8053 // Don't diagnose names we find in classes; we get much better
8054 // diagnostics for these from DiagnoseEmptyLookup.
8055 R.clear();
8056 return false;
8057 }
8058
8059 OverloadCandidateSet Candidates(FnLoc);
8060 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8061 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8062 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008063 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008064
8065 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008066 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008067 // No viable functions. Don't bother the user with notes for functions
8068 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008069 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008070 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008071 }
Richard Smith998a5912011-06-05 22:42:48 +00008072
8073 // Find the namespaces where ADL would have looked, and suggest
8074 // declaring the function there instead.
8075 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8076 Sema::AssociatedClassSet AssociatedClasses;
8077 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8078 AssociatedNamespaces,
8079 AssociatedClasses);
8080 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008081 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008082 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008083 for (Sema::AssociatedNamespaceSet::iterator
8084 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008085 end = AssociatedNamespaces.end(); it != end; ++it) {
8086 if (!Std->Encloses(*it))
8087 SuggestedNamespaces.insert(*it);
8088 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008089 } else {
8090 // Lacking the 'std::' namespace, use all of the associated namespaces.
8091 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008092 }
8093
8094 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8095 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008096 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008097 SemaRef.Diag(Best->Function->getLocation(),
8098 diag::note_not_found_by_two_phase_lookup)
8099 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008100 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008101 SemaRef.Diag(Best->Function->getLocation(),
8102 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008103 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008104 } else {
8105 // FIXME: It would be useful to list the associated namespaces here,
8106 // but the diagnostics infrastructure doesn't provide a way to produce
8107 // a localized representation of a list of items.
8108 SemaRef.Diag(Best->Function->getLocation(),
8109 diag::note_not_found_by_two_phase_lookup)
8110 << R.getLookupName() << 2;
8111 }
8112
8113 // Try to recover by calling this function.
8114 return true;
8115 }
8116
8117 R.clear();
8118 }
8119
8120 return false;
8121}
8122
8123/// Attempt to recover from ill-formed use of a non-dependent operator in a
8124/// template, where the non-dependent operator was declared after the template
8125/// was defined.
8126///
8127/// Returns true if a viable candidate was found and a diagnostic was issued.
8128static bool
8129DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8130 SourceLocation OpLoc,
8131 Expr **Args, unsigned NumArgs) {
8132 DeclarationName OpName =
8133 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8134 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8135 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8136 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8137}
8138
John McCalld681c392009-12-16 08:11:27 +00008139/// Attempts to recover from a call where no functions were found.
8140///
8141/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00008142static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008143BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00008144 UnresolvedLookupExpr *ULE,
8145 SourceLocation LParenLoc,
8146 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008147 SourceLocation RParenLoc,
8148 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00008149
8150 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00008151 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00008152
John McCall57500772009-12-16 12:17:52 +00008153 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00008154 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008155 if (ULE->hasExplicitTemplateArgs()) {
8156 ULE->copyTemplateArgumentsInto(TABuffer);
8157 ExplicitTemplateArgs = &TABuffer;
8158 }
8159
John McCalld681c392009-12-16 08:11:27 +00008160 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8161 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00008162 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8163 ExplicitTemplateArgs, Args, NumArgs) &&
8164 (!EmptyLookup ||
8165 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression)))
John McCallfaf5fb42010-08-26 23:41:50 +00008166 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00008167
John McCall57500772009-12-16 12:17:52 +00008168 assert(!R.empty() && "lookup results empty despite recovery");
8169
8170 // Build an implicit member call if appropriate. Just drop the
8171 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00008172 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00008173 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00008174 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8175 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00008176 else if (ExplicitTemplateArgs)
8177 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8178 else
8179 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8180
8181 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008182 return ExprError();
John McCall57500772009-12-16 12:17:52 +00008183
8184 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00008185 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00008186 // end up here.
John McCallb268a282010-08-23 23:25:46 +00008187 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008188 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00008189}
Douglas Gregor4038cf42010-06-08 17:35:15 +00008190
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008191/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00008192/// (which eventually refers to the declaration Func) and the call
8193/// arguments Args/NumArgs, attempt to resolve the function call down
8194/// to a specific function. If overload resolution succeeds, returns
8195/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00008196/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008197/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00008198ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008199Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00008200 SourceLocation LParenLoc,
8201 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00008202 SourceLocation RParenLoc,
8203 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00008204#ifndef NDEBUG
8205 if (ULE->requiresADL()) {
8206 // To do ADL, we must have found an unqualified name.
8207 assert(!ULE->getQualifier() && "qualified name with ADL");
8208
8209 // We don't perform ADL for implicit declarations of builtins.
8210 // Verify that this was correctly set up.
8211 FunctionDecl *F;
8212 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8213 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8214 F->getBuiltinID() && F->isImplicit())
8215 assert(0 && "performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008216
John McCall57500772009-12-16 12:17:52 +00008217 // We don't perform ADL in C.
8218 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00008219 } else
8220 assert(!ULE->isStdAssociatedNamespace() &&
8221 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00008222#endif
8223
John McCallbc077cf2010-02-08 23:07:23 +00008224 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00008225
John McCall57500772009-12-16 12:17:52 +00008226 // Add the functions denoted by the callee to the set of candidate
8227 // functions, including those from argument-dependent lookup.
8228 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00008229
8230 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00008231 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8232 // out if it fails.
John McCall57500772009-12-16 12:17:52 +00008233 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008234 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008235 RParenLoc, /*EmptyLookup=*/true);
John McCalld681c392009-12-16 08:11:27 +00008236
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008237 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008238 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00008239 case OR_Success: {
8240 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00008241 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00008242 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008243 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
8244 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00008245 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00008246 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8247 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00008248 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008249
Richard Smith998a5912011-06-05 22:42:48 +00008250 case OR_No_Viable_Function: {
8251 // Try to recover by looking for viable functions which the user might
8252 // have meant to call.
8253 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8254 Args, NumArgs, RParenLoc,
8255 /*EmptyLookup=*/false);
8256 if (!Recovery.isInvalid())
8257 return Recovery;
8258
Chris Lattner45d9d602009-02-17 07:29:20 +00008259 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008260 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00008261 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008262 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008263 break;
Richard Smith998a5912011-06-05 22:42:48 +00008264 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008265
8266 case OR_Ambiguous:
8267 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00008268 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008269 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008270 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008271
8272 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008273 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008274 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8275 << Best->Function->isDeleted()
8276 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008277 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008278 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008279 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8280 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00008281 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008282 }
8283
Douglas Gregorb412e172010-07-25 18:17:45 +00008284 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00008285 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008286}
8287
John McCall4c4c1df2010-01-26 03:27:55 +00008288static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00008289 return Functions.size() > 1 ||
8290 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8291}
8292
Douglas Gregor084d8552009-03-13 23:49:33 +00008293/// \brief Create a unary operation that may resolve to an overloaded
8294/// operator.
8295///
8296/// \param OpLoc The location of the operator itself (e.g., '*').
8297///
8298/// \param OpcIn The UnaryOperator::Opcode that describes this
8299/// operator.
8300///
8301/// \param Functions The set of non-member functions that will be
8302/// considered by overload resolution. The caller needs to build this
8303/// set based on the context using, e.g.,
8304/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8305/// set should not contain any member functions; those will be added
8306/// by CreateOverloadedUnaryOp().
8307///
8308/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00008309ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00008310Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8311 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00008312 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008313 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00008314
8315 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8316 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8317 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008318 // TODO: provide better source location info.
8319 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008320
John Wiegley01296292011-04-08 18:41:53 +00008321 if (Input->getObjectKind() == OK_ObjCProperty) {
8322 ExprResult Result = ConvertPropertyForRValue(Input);
8323 if (Result.isInvalid())
8324 return ExprError();
8325 Input = Result.take();
8326 }
John McCalle26a8722010-12-04 08:14:53 +00008327
Douglas Gregor084d8552009-03-13 23:49:33 +00008328 Expr *Args[2] = { Input, 0 };
8329 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00008330
Douglas Gregor084d8552009-03-13 23:49:33 +00008331 // For post-increment and post-decrement, add the implicit '0' as
8332 // the second argument, so that we know this is a post-increment or
8333 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00008334 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008335 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008336 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8337 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00008338 NumArgs = 2;
8339 }
8340
8341 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00008342 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00008343 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008344 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00008345 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008346 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00008347 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008348
John McCall58cc69d2010-01-27 01:50:18 +00008349 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00008350 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008351 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008352 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008353 /*ADL*/ true, IsOverloaded(Fns),
8354 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00008355 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008356 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00008357 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008358 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00008359 OpLoc));
8360 }
8361
8362 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008363 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008364
8365 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008366 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00008367
8368 // Add operator candidates that are member functions.
8369 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8370
John McCall4c4c1df2010-01-26 03:27:55 +00008371 // Add candidates from ADL.
8372 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00008373 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00008374 /*ExplicitTemplateArgs*/ 0,
8375 CandidateSet);
8376
Douglas Gregor084d8552009-03-13 23:49:33 +00008377 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008378 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00008379
8380 // Perform overload resolution.
8381 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008382 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008383 case OR_Success: {
8384 // We found a built-in operator or an overloaded operator.
8385 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00008386
Douglas Gregor084d8552009-03-13 23:49:33 +00008387 if (FnDecl) {
8388 // We matched an overloaded operator. Build a call to that
8389 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00008390
Chandler Carruth30141632011-02-25 19:41:05 +00008391 MarkDeclarationReferenced(OpLoc, FnDecl);
8392
Douglas Gregor084d8552009-03-13 23:49:33 +00008393 // Convert the arguments.
8394 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00008395 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008396
John Wiegley01296292011-04-08 18:41:53 +00008397 ExprResult InputRes =
8398 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8399 Best->FoundDecl, Method);
8400 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008401 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008402 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008403 } else {
8404 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008405 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00008406 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008407 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00008408 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008409 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00008410 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00008411 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008412 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008413 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008414 }
8415
John McCall4fa0d5f2010-05-06 18:15:07 +00008416 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8417
John McCall7decc9e2010-11-18 06:31:45 +00008418 // Determine the result type.
8419 QualType ResultTy = FnDecl->getResultType();
8420 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8421 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00008422
Douglas Gregor084d8552009-03-13 23:49:33 +00008423 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008424 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl);
8425 if (FnExpr.isInvalid())
8426 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00008427
Eli Friedman030eee42009-11-18 03:58:17 +00008428 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00008429 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008430 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008431 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00008432
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008433 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00008434 FnDecl))
8435 return ExprError();
8436
John McCallb268a282010-08-23 23:25:46 +00008437 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00008438 } else {
8439 // We matched a built-in operator. Convert the arguments, then
8440 // break out so that we will build the appropriate built-in
8441 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008442 ExprResult InputRes =
8443 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8444 Best->Conversions[0], AA_Passing);
8445 if (InputRes.isInvalid())
8446 return ExprError();
8447 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008448 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00008449 }
John Wiegley01296292011-04-08 18:41:53 +00008450 }
8451
8452 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00008453 // This is an erroneous use of an operator which can be overloaded by
8454 // a non-member function. Check for non-member operators which were
8455 // defined too late to be candidates.
8456 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
8457 // FIXME: Recover by calling the found function.
8458 return ExprError();
8459
John Wiegley01296292011-04-08 18:41:53 +00008460 // No viable function; fall through to handling this as a
8461 // built-in operator, which will produce an error message for us.
8462 break;
8463
8464 case OR_Ambiguous:
8465 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8466 << UnaryOperator::getOpcodeStr(Opc)
8467 << Input->getType()
8468 << Input->getSourceRange();
8469 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
8470 Args, NumArgs,
8471 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8472 return ExprError();
8473
8474 case OR_Deleted:
8475 Diag(OpLoc, diag::err_ovl_deleted_oper)
8476 << Best->Function->isDeleted()
8477 << UnaryOperator::getOpcodeStr(Opc)
8478 << getDeletedOrUnavailableSuffix(Best->Function)
8479 << Input->getSourceRange();
8480 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8481 return ExprError();
8482 }
Douglas Gregor084d8552009-03-13 23:49:33 +00008483
8484 // Either we found no viable overloaded operator or we matched a
8485 // built-in operator. In either case, fall through to trying to
8486 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00008487 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008488}
8489
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008490/// \brief Create a binary operation that may resolve to an overloaded
8491/// operator.
8492///
8493/// \param OpLoc The location of the operator itself (e.g., '+').
8494///
8495/// \param OpcIn The BinaryOperator::Opcode that describes this
8496/// operator.
8497///
8498/// \param Functions The set of non-member functions that will be
8499/// considered by overload resolution. The caller needs to build this
8500/// set based on the context using, e.g.,
8501/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8502/// set should not contain any member functions; those will be added
8503/// by CreateOverloadedBinOp().
8504///
8505/// \param LHS Left-hand argument.
8506/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00008507ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008508Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008509 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00008510 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008511 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008512 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00008513 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008514
8515 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8516 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8517 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8518
8519 // If either side is type-dependent, create an appropriate dependent
8520 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00008521 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00008522 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008523 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00008524 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00008525 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00008526 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00008527 Context.DependentTy,
8528 VK_RValue, OK_Ordinary,
8529 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008530
Douglas Gregor5287f092009-11-05 00:51:44 +00008531 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8532 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008533 VK_LValue,
8534 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00008535 Context.DependentTy,
8536 Context.DependentTy,
8537 OpLoc));
8538 }
John McCall4c4c1df2010-01-26 03:27:55 +00008539
8540 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00008541 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008542 // TODO: provide better source location info in DNLoc component.
8543 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00008544 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00008545 = UnresolvedLookupExpr::Create(Context, NamingClass,
8546 NestedNameSpecifierLoc(), OpNameInfo,
8547 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008548 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008549 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00008550 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008551 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008552 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008553 OpLoc));
8554 }
8555
John McCalle26a8722010-12-04 08:14:53 +00008556 // Always do property rvalue conversions on the RHS.
John Wiegley01296292011-04-08 18:41:53 +00008557 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8558 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8559 if (Result.isInvalid())
8560 return ExprError();
8561 Args[1] = Result.take();
8562 }
John McCalle26a8722010-12-04 08:14:53 +00008563
8564 // The LHS is more complicated.
8565 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8566
8567 // There's a tension for assignment operators between primitive
8568 // property assignment and the overloaded operators.
8569 if (BinaryOperator::isAssignmentOp(Opc)) {
8570 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8571
8572 // Is the property "logically" settable?
8573 bool Settable = (PRE->isExplicitProperty() ||
8574 PRE->getImplicitPropertySetter());
8575
8576 // To avoid gratuitously inventing semantics, use the primitive
8577 // unless it isn't. Thoughts in case we ever really care:
8578 // - If the property isn't logically settable, we have to
8579 // load and hope.
8580 // - If the property is settable and this is simple assignment,
8581 // we really should use the primitive.
8582 // - If the property is settable, then we could try overloading
8583 // on a generic lvalue of the appropriate type; if it works
8584 // out to a builtin candidate, we would do that same operation
8585 // on the property, and otherwise just error.
8586 if (Settable)
8587 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8588 }
8589
John Wiegley01296292011-04-08 18:41:53 +00008590 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8591 if (Result.isInvalid())
8592 return ExprError();
8593 Args[0] = Result.take();
John McCalle26a8722010-12-04 08:14:53 +00008594 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008595
Sebastian Redl6a96bf72009-11-18 23:10:33 +00008596 // If this is the assignment operator, we only perform overload resolution
8597 // if the left-hand side is a class or enumeration type. This is actually
8598 // a hack. The standard requires that we do overload resolution between the
8599 // various built-in candidates, but as DR507 points out, this can lead to
8600 // problems. So we do it this way, which pretty much follows what GCC does.
8601 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00008602 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00008603 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008604
John McCalle26a8722010-12-04 08:14:53 +00008605 // If this is the .* operator, which is not overloadable, just
8606 // create a built-in binary operator.
8607 if (Opc == BO_PtrMemD)
8608 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8609
Douglas Gregor084d8552009-03-13 23:49:33 +00008610 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008611 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008612
8613 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008614 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008615
8616 // Add operator candidates that are member functions.
8617 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8618
John McCall4c4c1df2010-01-26 03:27:55 +00008619 // Add candidates from ADL.
8620 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8621 Args, 2,
8622 /*ExplicitTemplateArgs*/ 0,
8623 CandidateSet);
8624
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008625 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008626 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008627
8628 // Perform overload resolution.
8629 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008630 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00008631 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008632 // We found a built-in operator or an overloaded operator.
8633 FunctionDecl *FnDecl = Best->Function;
8634
8635 if (FnDecl) {
8636 // We matched an overloaded operator. Build a call to that
8637 // operator.
8638
Chandler Carruth30141632011-02-25 19:41:05 +00008639 MarkDeclarationReferenced(OpLoc, FnDecl);
8640
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008641 // Convert the arguments.
8642 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00008643 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00008644 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008645
Chandler Carruth8e543b32010-12-12 08:17:55 +00008646 ExprResult Arg1 =
8647 PerformCopyInitialization(
8648 InitializedEntity::InitializeParameter(Context,
8649 FnDecl->getParamDecl(0)),
8650 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008651 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008652 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008653
John Wiegley01296292011-04-08 18:41:53 +00008654 ExprResult Arg0 =
8655 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8656 Best->FoundDecl, Method);
8657 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008658 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008659 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008660 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008661 } else {
8662 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00008663 ExprResult Arg0 = PerformCopyInitialization(
8664 InitializedEntity::InitializeParameter(Context,
8665 FnDecl->getParamDecl(0)),
8666 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008667 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008668 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008669
Chandler Carruth8e543b32010-12-12 08:17:55 +00008670 ExprResult Arg1 =
8671 PerformCopyInitialization(
8672 InitializedEntity::InitializeParameter(Context,
8673 FnDecl->getParamDecl(1)),
8674 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008675 if (Arg1.isInvalid())
8676 return ExprError();
8677 Args[0] = LHS = Arg0.takeAs<Expr>();
8678 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008679 }
8680
John McCall4fa0d5f2010-05-06 18:15:07 +00008681 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8682
John McCall7decc9e2010-11-18 06:31:45 +00008683 // Determine the result type.
8684 QualType ResultTy = FnDecl->getResultType();
8685 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8686 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008687
8688 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008689 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
8690 if (FnExpr.isInvalid())
8691 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008692
John McCallb268a282010-08-23 23:25:46 +00008693 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008694 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008695 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008696
8697 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008698 FnDecl))
8699 return ExprError();
8700
John McCallb268a282010-08-23 23:25:46 +00008701 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008702 } else {
8703 // We matched a built-in operator. Convert the arguments, then
8704 // break out so that we will build the appropriate built-in
8705 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008706 ExprResult ArgsRes0 =
8707 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8708 Best->Conversions[0], AA_Passing);
8709 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008710 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008711 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008712
John Wiegley01296292011-04-08 18:41:53 +00008713 ExprResult ArgsRes1 =
8714 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8715 Best->Conversions[1], AA_Passing);
8716 if (ArgsRes1.isInvalid())
8717 return ExprError();
8718 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008719 break;
8720 }
8721 }
8722
Douglas Gregor66950a32009-09-30 21:46:01 +00008723 case OR_No_Viable_Function: {
8724 // C++ [over.match.oper]p9:
8725 // If the operator is the operator , [...] and there are no
8726 // viable functions, then the operator is assumed to be the
8727 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00008728 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00008729 break;
8730
Chandler Carruth8e543b32010-12-12 08:17:55 +00008731 // For class as left operand for assignment or compound assigment
8732 // operator do not fall through to handling in built-in, but report that
8733 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00008734 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008735 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00008736 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00008737 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8738 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00008739 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00008740 } else {
Richard Smith998a5912011-06-05 22:42:48 +00008741 // This is an erroneous use of an operator which can be overloaded by
8742 // a non-member function. Check for non-member operators which were
8743 // defined too late to be candidates.
8744 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
8745 // FIXME: Recover by calling the found function.
8746 return ExprError();
8747
Douglas Gregor66950a32009-09-30 21:46:01 +00008748 // No viable function; try to create a built-in operation, which will
8749 // produce an error. Then, show the non-viable candidates.
8750 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00008751 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008752 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00008753 "C++ binary operator overloading is missing candidates!");
8754 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00008755 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8756 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00008757 return move(Result);
8758 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008759
8760 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008761 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008762 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00008763 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00008764 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008765 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8766 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008767 return ExprError();
8768
8769 case OR_Deleted:
8770 Diag(OpLoc, diag::err_ovl_deleted_oper)
8771 << Best->Function->isDeleted()
8772 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008773 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00008774 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008775 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008776 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00008777 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008778
Douglas Gregor66950a32009-09-30 21:46:01 +00008779 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00008780 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008781}
8782
John McCalldadc5752010-08-24 06:29:42 +00008783ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00008784Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8785 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00008786 Expr *Base, Expr *Idx) {
8787 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00008788 DeclarationName OpName =
8789 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8790
8791 // If either side is type-dependent, create an appropriate dependent
8792 // expression.
8793 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8794
John McCall58cc69d2010-01-27 01:50:18 +00008795 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008796 // CHECKME: no 'operator' keyword?
8797 DeclarationNameInfo OpNameInfo(OpName, LLoc);
8798 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00008799 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008800 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008801 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008802 /*ADL*/ true, /*Overloaded*/ false,
8803 UnresolvedSetIterator(),
8804 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00008805 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00008806
Sebastian Redladba46e2009-10-29 20:17:01 +00008807 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8808 Args, 2,
8809 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008810 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00008811 RLoc));
8812 }
8813
John Wiegley01296292011-04-08 18:41:53 +00008814 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8815 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8816 if (Result.isInvalid())
8817 return ExprError();
8818 Args[0] = Result.take();
8819 }
8820 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8821 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8822 if (Result.isInvalid())
8823 return ExprError();
8824 Args[1] = Result.take();
8825 }
John McCalle26a8722010-12-04 08:14:53 +00008826
Sebastian Redladba46e2009-10-29 20:17:01 +00008827 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008828 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008829
8830 // Subscript can only be overloaded as a member function.
8831
8832 // Add operator candidates that are member functions.
8833 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8834
8835 // Add builtin operator candidates.
8836 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8837
8838 // Perform overload resolution.
8839 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008840 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00008841 case OR_Success: {
8842 // We found a built-in operator or an overloaded operator.
8843 FunctionDecl *FnDecl = Best->Function;
8844
8845 if (FnDecl) {
8846 // We matched an overloaded operator. Build a call to that
8847 // operator.
8848
Chandler Carruth30141632011-02-25 19:41:05 +00008849 MarkDeclarationReferenced(LLoc, FnDecl);
8850
John McCalla0296f72010-03-19 07:35:19 +00008851 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008852 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00008853
Sebastian Redladba46e2009-10-29 20:17:01 +00008854 // Convert the arguments.
8855 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00008856 ExprResult Arg0 =
8857 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8858 Best->FoundDecl, Method);
8859 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00008860 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008861 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00008862
Anders Carlssona68e51e2010-01-29 18:37:50 +00008863 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008864 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00008865 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008866 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00008867 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008868 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00008869 Owned(Args[1]));
8870 if (InputInit.isInvalid())
8871 return ExprError();
8872
8873 Args[1] = InputInit.takeAs<Expr>();
8874
Sebastian Redladba46e2009-10-29 20:17:01 +00008875 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00008876 QualType ResultTy = FnDecl->getResultType();
8877 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8878 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00008879
8880 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008881 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
8882 if (FnExpr.isInvalid())
8883 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00008884
John McCallb268a282010-08-23 23:25:46 +00008885 CXXOperatorCallExpr *TheCall =
8886 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00008887 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00008888 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008889
John McCallb268a282010-08-23 23:25:46 +00008890 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00008891 FnDecl))
8892 return ExprError();
8893
John McCallb268a282010-08-23 23:25:46 +00008894 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00008895 } else {
8896 // We matched a built-in operator. Convert the arguments, then
8897 // break out so that we will build the appropriate built-in
8898 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008899 ExprResult ArgsRes0 =
8900 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8901 Best->Conversions[0], AA_Passing);
8902 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00008903 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008904 Args[0] = ArgsRes0.take();
8905
8906 ExprResult ArgsRes1 =
8907 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8908 Best->Conversions[1], AA_Passing);
8909 if (ArgsRes1.isInvalid())
8910 return ExprError();
8911 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00008912
8913 break;
8914 }
8915 }
8916
8917 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00008918 if (CandidateSet.empty())
8919 Diag(LLoc, diag::err_ovl_no_oper)
8920 << Args[0]->getType() << /*subscript*/ 0
8921 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8922 else
8923 Diag(LLoc, diag::err_ovl_no_viable_subscript)
8924 << Args[0]->getType()
8925 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008926 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8927 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00008928 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00008929 }
8930
8931 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008932 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008933 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00008934 << Args[0]->getType() << Args[1]->getType()
8935 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008936 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8937 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008938 return ExprError();
8939
8940 case OR_Deleted:
8941 Diag(LLoc, diag::err_ovl_deleted_oper)
8942 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008943 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00008944 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008945 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8946 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008947 return ExprError();
8948 }
8949
8950 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00008951 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008952}
8953
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008954/// BuildCallToMemberFunction - Build a call to a member
8955/// function. MemExpr is the expression that refers to the member
8956/// function (and includes the object parameter), Args/NumArgs are the
8957/// arguments to the function call (not including the object
8958/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00008959/// expression refers to a non-static member function or an overloaded
8960/// member function.
John McCalldadc5752010-08-24 06:29:42 +00008961ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008962Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
8963 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008964 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00008965 assert(MemExprE->getType() == Context.BoundMemberTy ||
8966 MemExprE->getType() == Context.OverloadTy);
8967
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008968 // Dig out the member expression. This holds both the object
8969 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00008970 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008971
John McCall0009fcc2011-04-26 20:42:42 +00008972 // Determine whether this is a call to a pointer-to-member function.
8973 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
8974 assert(op->getType() == Context.BoundMemberTy);
8975 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
8976
8977 QualType fnType =
8978 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
8979
8980 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
8981 QualType resultType = proto->getCallResultType(Context);
8982 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
8983
8984 // Check that the object type isn't more qualified than the
8985 // member function we're calling.
8986 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
8987
8988 QualType objectType = op->getLHS()->getType();
8989 if (op->getOpcode() == BO_PtrMemI)
8990 objectType = objectType->castAs<PointerType>()->getPointeeType();
8991 Qualifiers objectQuals = objectType.getQualifiers();
8992
8993 Qualifiers difference = objectQuals - funcQuals;
8994 difference.removeObjCGCAttr();
8995 difference.removeAddressSpace();
8996 if (difference) {
8997 std::string qualsString = difference.getAsString();
8998 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
8999 << fnType.getUnqualifiedType()
9000 << qualsString
9001 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9002 }
9003
9004 CXXMemberCallExpr *call
9005 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9006 resultType, valueKind, RParenLoc);
9007
9008 if (CheckCallReturnType(proto->getResultType(),
9009 op->getRHS()->getSourceRange().getBegin(),
9010 call, 0))
9011 return ExprError();
9012
9013 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9014 return ExprError();
9015
9016 return MaybeBindToTemporary(call);
9017 }
9018
John McCall10eae182009-11-30 22:42:35 +00009019 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009020 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009021 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009022 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009023 if (isa<MemberExpr>(NakedMemExpr)) {
9024 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009025 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009026 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009027 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00009028 } else {
9029 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009030 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009031
John McCall6e9f8f62009-12-03 04:06:58 +00009032 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009033 Expr::Classification ObjectClassification
9034 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9035 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009036
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009037 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009038 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009039
John McCall2d74de92009-12-01 22:10:20 +00009040 // FIXME: avoid copy.
9041 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9042 if (UnresExpr->hasExplicitTemplateArgs()) {
9043 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9044 TemplateArgs = &TemplateArgsBuffer;
9045 }
9046
John McCall10eae182009-11-30 22:42:35 +00009047 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9048 E = UnresExpr->decls_end(); I != E; ++I) {
9049
John McCall6e9f8f62009-12-03 04:06:58 +00009050 NamedDecl *Func = *I;
9051 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9052 if (isa<UsingShadowDecl>(Func))
9053 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9054
Douglas Gregor02824322011-01-26 19:30:28 +00009055
Francois Pichet64225792011-01-18 05:04:39 +00009056 // Microsoft supports direct constructor calls.
9057 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
9058 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9059 CandidateSet);
9060 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009061 // If explicit template arguments were provided, we can't call a
9062 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009063 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009064 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009065
John McCalla0296f72010-03-19 07:35:19 +00009066 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009067 ObjectClassification,
9068 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009069 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009070 } else {
John McCall10eae182009-11-30 22:42:35 +00009071 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009072 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009073 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009074 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009075 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009076 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009077 }
Mike Stump11289f42009-09-09 15:08:12 +00009078
John McCall10eae182009-11-30 22:42:35 +00009079 DeclarationName DeclName = UnresExpr->getMemberName();
9080
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009081 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009082 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009083 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009084 case OR_Success:
9085 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009086 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009087 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009088 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009089 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009090 break;
9091
9092 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009093 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009094 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009095 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009096 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009097 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009098 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009099
9100 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009101 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009102 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009103 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009104 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009105 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009106
9107 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009108 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009109 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009110 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009111 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009112 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009113 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009114 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009115 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009116 }
9117
John McCall16df1e52010-03-30 21:47:33 +00009118 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009119
John McCall2d74de92009-12-01 22:10:20 +00009120 // If overload resolution picked a static member, build a
9121 // non-member call based on that function.
9122 if (Method->isStatic()) {
9123 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9124 Args, NumArgs, RParenLoc);
9125 }
9126
John McCall10eae182009-11-30 22:42:35 +00009127 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009128 }
9129
John McCall7decc9e2010-11-18 06:31:45 +00009130 QualType ResultType = Method->getResultType();
9131 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9132 ResultType = ResultType.getNonLValueExprType(Context);
9133
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009134 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009135 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00009136 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009137 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009138
Anders Carlssonc4859ba2009-10-10 00:06:20 +00009139 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009140 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00009141 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00009142 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009143
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009144 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00009145 // We only need to do this if there was actually an overload; otherwise
9146 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00009147 if (!Method->isStatic()) {
9148 ExprResult ObjectArg =
9149 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9150 FoundDecl, Method);
9151 if (ObjectArg.isInvalid())
9152 return ExprError();
9153 MemExpr->setBase(ObjectArg.take());
9154 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009155
9156 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00009157 const FunctionProtoType *Proto =
9158 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00009159 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009160 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00009161 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009162
John McCallb268a282010-08-23 23:25:46 +00009163 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00009164 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00009165
Anders Carlsson47061ee2011-05-06 14:25:31 +00009166 if ((isa<CXXConstructorDecl>(CurContext) ||
9167 isa<CXXDestructorDecl>(CurContext)) &&
9168 TheCall->getMethodDecl()->isPure()) {
9169 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9170
Chandler Carruth59259262011-06-27 08:31:58 +00009171 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +00009172 Diag(MemExpr->getLocStart(),
9173 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9174 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9175 << MD->getParent()->getDeclName();
9176
9177 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +00009178 }
Anders Carlsson47061ee2011-05-06 14:25:31 +00009179 }
John McCallb268a282010-08-23 23:25:46 +00009180 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009181}
9182
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009183/// BuildCallToObjectOfClassType - Build a call to an object of class
9184/// type (C++ [over.call.object]), which can end up invoking an
9185/// overloaded function call operator (@c operator()) or performing a
9186/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00009187ExprResult
John Wiegley01296292011-04-08 18:41:53 +00009188Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00009189 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009190 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009191 SourceLocation RParenLoc) {
John Wiegley01296292011-04-08 18:41:53 +00009192 ExprResult Object = Owned(Obj);
9193 if (Object.get()->getObjectKind() == OK_ObjCProperty) {
9194 Object = ConvertPropertyForRValue(Object.take());
9195 if (Object.isInvalid())
9196 return ExprError();
9197 }
John McCalle26a8722010-12-04 08:14:53 +00009198
John Wiegley01296292011-04-08 18:41:53 +00009199 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9200 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00009201
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009202 // C++ [over.call.object]p1:
9203 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00009204 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009205 // candidate functions includes at least the function call
9206 // operators of T. The function call operators of T are obtained by
9207 // ordinary lookup of the name operator() in the context of
9208 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00009209 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00009210 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009211
John Wiegley01296292011-04-08 18:41:53 +00009212 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00009213 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009214 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009215 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009216
John McCall27b18f82009-11-17 02:14:36 +00009217 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9218 LookupQualifiedName(R, Record->getDecl());
9219 R.suppressDiagnostics();
9220
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009221 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00009222 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00009223 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9224 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00009225 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00009226 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009227
Douglas Gregorab7897a2008-11-19 22:57:39 +00009228 // C++ [over.call.object]p2:
9229 // In addition, for each conversion function declared in T of the
9230 // form
9231 //
9232 // operator conversion-type-id () cv-qualifier;
9233 //
9234 // where cv-qualifier is the same cv-qualification as, or a
9235 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00009236 // denotes the type "pointer to function of (P1,...,Pn) returning
9237 // R", or the type "reference to pointer to function of
9238 // (P1,...,Pn) returning R", or the type "reference to function
9239 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00009240 // is also considered as a candidate function. Similarly,
9241 // surrogate call functions are added to the set of candidate
9242 // functions for each conversion function declared in an
9243 // accessible base class provided the function is not hidden
9244 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00009245 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00009246 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00009247 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00009248 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00009249 NamedDecl *D = *I;
9250 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9251 if (isa<UsingShadowDecl>(D))
9252 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009253
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009254 // Skip over templated conversion functions; they aren't
9255 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00009256 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009257 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00009258
John McCall6e9f8f62009-12-03 04:06:58 +00009259 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00009260
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009261 // Strip the reference type (if any) and then the pointer type (if
9262 // any) to get down to what might be a function type.
9263 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9264 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9265 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00009266
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009267 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00009268 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John Wiegley01296292011-04-08 18:41:53 +00009269 Object.get(), Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00009270 }
Mike Stump11289f42009-09-09 15:08:12 +00009271
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009272 // Perform overload resolution.
9273 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00009274 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00009275 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009276 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00009277 // Overload resolution succeeded; we'll build the appropriate call
9278 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009279 break;
9280
9281 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00009282 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00009283 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9284 << Object.get()->getType() << /*call*/ 1
9285 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00009286 else
John Wiegley01296292011-04-08 18:41:53 +00009287 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00009288 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009289 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009290 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009291 break;
9292
9293 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00009294 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009295 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009296 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009297 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009298 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009299
9300 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +00009301 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00009302 diag::err_ovl_deleted_object_call)
9303 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +00009304 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009305 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +00009306 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009307 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009308 break;
Mike Stump11289f42009-09-09 15:08:12 +00009309 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009310
Douglas Gregorb412e172010-07-25 18:17:45 +00009311 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009312 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009313
Douglas Gregorab7897a2008-11-19 22:57:39 +00009314 if (Best->Function == 0) {
9315 // Since there is no function declaration, this is one of the
9316 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00009317 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00009318 = cast<CXXConversionDecl>(
9319 Best->Conversions[0].UserDefined.ConversionFunction);
9320
John Wiegley01296292011-04-08 18:41:53 +00009321 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009322 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009323
Douglas Gregorab7897a2008-11-19 22:57:39 +00009324 // We selected one of the surrogate functions that converts the
9325 // object parameter to a function pointer. Perform the conversion
9326 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009327
Fariborz Jahanian774cf792009-09-28 18:35:46 +00009328 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00009329 // and then call it.
John Wiegley01296292011-04-08 18:41:53 +00009330 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv);
Douglas Gregor668443e2011-01-20 00:18:04 +00009331 if (Call.isInvalid())
9332 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009333
Douglas Gregor668443e2011-01-20 00:18:04 +00009334 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00009335 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00009336 }
9337
Chandler Carruth30141632011-02-25 19:41:05 +00009338 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009339 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009340 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009341
Douglas Gregorab7897a2008-11-19 22:57:39 +00009342 // We found an overloaded operator(). Build a CXXOperatorCallExpr
9343 // that calls this method, using Object for the implicit object
9344 // parameter and passing along the remaining arguments.
9345 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00009346 const FunctionProtoType *Proto =
9347 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009348
9349 unsigned NumArgsInProto = Proto->getNumArgs();
9350 unsigned NumArgsToCheck = NumArgs;
9351
9352 // Build the full argument list for the method call (the
9353 // implicit object parameter is placed at the beginning of the
9354 // list).
9355 Expr **MethodArgs;
9356 if (NumArgs < NumArgsInProto) {
9357 NumArgsToCheck = NumArgsInProto;
9358 MethodArgs = new Expr*[NumArgsInProto + 1];
9359 } else {
9360 MethodArgs = new Expr*[NumArgs + 1];
9361 }
John Wiegley01296292011-04-08 18:41:53 +00009362 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009363 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9364 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00009365
John Wiegley01296292011-04-08 18:41:53 +00009366 ExprResult NewFn = CreateFunctionRefExpr(*this, Method);
9367 if (NewFn.isInvalid())
9368 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009369
9370 // Once we've built TheCall, all of the expressions are properly
9371 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00009372 QualType ResultTy = Method->getResultType();
9373 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9374 ResultTy = ResultTy.getNonLValueExprType(Context);
9375
John McCallb268a282010-08-23 23:25:46 +00009376 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009377 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +00009378 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00009379 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009380 delete [] MethodArgs;
9381
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009382 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00009383 Method))
9384 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009385
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009386 // We may have default arguments. If so, we need to allocate more
9387 // slots in the call for them.
9388 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00009389 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009390 else if (NumArgs > NumArgsInProto)
9391 NumArgsToCheck = NumArgsInProto;
9392
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009393 bool IsError = false;
9394
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009395 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +00009396 ExprResult ObjRes =
9397 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9398 Best->FoundDecl, Method);
9399 if (ObjRes.isInvalid())
9400 IsError = true;
9401 else
9402 Object = move(ObjRes);
9403 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009404
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009405 // Check the argument types.
9406 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009407 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009408 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009409 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00009410
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009411 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009412
John McCalldadc5752010-08-24 06:29:42 +00009413 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009414 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009415 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009416 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00009417 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009418
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009419 IsError |= InputInit.isInvalid();
9420 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009421 } else {
John McCalldadc5752010-08-24 06:29:42 +00009422 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009423 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9424 if (DefArg.isInvalid()) {
9425 IsError = true;
9426 break;
9427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009428
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009429 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009430 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009431
9432 TheCall->setArg(i + 1, Arg);
9433 }
9434
9435 // If this is a variadic call, handle args passed through "...".
9436 if (Proto->isVariadic()) {
9437 // Promote the arguments (C99 6.5.2.2p7).
9438 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +00009439 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9440 IsError |= Arg.isInvalid();
9441 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009442 }
9443 }
9444
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009445 if (IsError) return true;
9446
John McCallb268a282010-08-23 23:25:46 +00009447 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00009448 return true;
9449
John McCalle172be52010-08-24 06:09:16 +00009450 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009451}
9452
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009453/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00009454/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009455/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00009456ExprResult
John McCallb268a282010-08-23 23:25:46 +00009457Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009458 assert(Base->getType()->isRecordType() &&
9459 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00009460
John Wiegley01296292011-04-08 18:41:53 +00009461 if (Base->getObjectKind() == OK_ObjCProperty) {
9462 ExprResult Result = ConvertPropertyForRValue(Base);
9463 if (Result.isInvalid())
9464 return ExprError();
9465 Base = Result.take();
9466 }
John McCalle26a8722010-12-04 08:14:53 +00009467
John McCallbc077cf2010-02-08 23:07:23 +00009468 SourceLocation Loc = Base->getExprLoc();
9469
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009470 // C++ [over.ref]p1:
9471 //
9472 // [...] An expression x->m is interpreted as (x.operator->())->m
9473 // for a class object x of type T if T::operator->() exists and if
9474 // the operator is selected as the best match function by the
9475 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00009476 DeclarationName OpName =
9477 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00009478 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009479 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00009480
John McCallbc077cf2010-02-08 23:07:23 +00009481 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00009482 PDiag(diag::err_typecheck_incomplete_tag)
9483 << Base->getSourceRange()))
9484 return ExprError();
9485
John McCall27b18f82009-11-17 02:14:36 +00009486 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9487 LookupQualifiedName(R, BaseRecord->getDecl());
9488 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00009489
9490 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00009491 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00009492 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9493 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00009494 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009495
9496 // Perform overload resolution.
9497 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009498 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009499 case OR_Success:
9500 // Overload resolution succeeded; we'll build the call below.
9501 break;
9502
9503 case OR_No_Viable_Function:
9504 if (CandidateSet.empty())
9505 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00009506 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009507 else
9508 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00009509 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009510 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009511 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009512
9513 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009514 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9515 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009516 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009517 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009518
9519 case OR_Deleted:
9520 Diag(OpLoc, diag::err_ovl_deleted_oper)
9521 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009522 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009523 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009524 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009525 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009526 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009527 }
9528
Chandler Carruth30141632011-02-25 19:41:05 +00009529 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +00009530 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009531 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00009532
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009533 // Convert the object parameter.
9534 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009535 ExprResult BaseResult =
9536 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9537 Best->FoundDecl, Method);
9538 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +00009539 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009540 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +00009541
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009542 // Build the operator call.
John Wiegley01296292011-04-08 18:41:53 +00009543 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method);
9544 if (FnExpr.isInvalid())
9545 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009546
John McCall7decc9e2010-11-18 06:31:45 +00009547 QualType ResultTy = Method->getResultType();
9548 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9549 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00009550 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009551 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009552 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009553
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009554 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009555 Method))
9556 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +00009557
9558 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009559}
9560
Douglas Gregorcd695e52008-11-10 20:40:00 +00009561/// FixOverloadedFunctionReference - E is an expression that refers to
9562/// a C++ overloaded function (possibly with some parentheses and
9563/// perhaps a '&' around it). We have resolved the overloaded function
9564/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00009565/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00009566Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00009567 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00009568 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009569 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9570 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009571 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009572 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009573
Douglas Gregor51c538b2009-11-20 19:42:02 +00009574 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009575 }
9576
Douglas Gregor51c538b2009-11-20 19:42:02 +00009577 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009578 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9579 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009580 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00009581 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00009582 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00009583 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00009584 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009585 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009586
9587 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +00009588 ICE->getCastKind(),
9589 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00009590 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009591 }
9592
Douglas Gregor51c538b2009-11-20 19:42:02 +00009593 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00009594 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00009595 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009596 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9597 if (Method->isStatic()) {
9598 // Do nothing: static member functions aren't any different
9599 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00009600 } else {
John McCalle66edc12009-11-24 19:00:30 +00009601 // Fix the sub expression, which really has to be an
9602 // UnresolvedLookupExpr holding an overloaded member function
9603 // or template.
John McCall16df1e52010-03-30 21:47:33 +00009604 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9605 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00009606 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009607 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00009608
John McCalld14a8642009-11-21 08:51:07 +00009609 assert(isa<DeclRefExpr>(SubExpr)
9610 && "fixed to something other than a decl ref");
9611 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
9612 && "fixed to a member ref with no nested name qualifier");
9613
9614 // We have taken the address of a pointer to member
9615 // function. Perform the computation here so that we get the
9616 // appropriate pointer to member type.
9617 QualType ClassType
9618 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
9619 QualType MemPtrType
9620 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9621
John McCall7decc9e2010-11-18 06:31:45 +00009622 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9623 VK_RValue, OK_Ordinary,
9624 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009625 }
9626 }
John McCall16df1e52010-03-30 21:47:33 +00009627 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9628 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009629 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009630 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009631
John McCalle3027922010-08-25 11:45:40 +00009632 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009633 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00009634 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009635 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009636 }
John McCalld14a8642009-11-21 08:51:07 +00009637
9638 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00009639 // FIXME: avoid copy.
9640 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00009641 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00009642 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9643 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00009644 }
9645
John McCalld14a8642009-11-21 08:51:07 +00009646 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009647 ULE->getQualifierLoc(),
John McCalld14a8642009-11-21 08:51:07 +00009648 Fn,
9649 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009650 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009651 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009652 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009653 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00009654 }
9655
John McCall10eae182009-11-30 22:42:35 +00009656 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00009657 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00009658 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9659 if (MemExpr->hasExplicitTemplateArgs()) {
9660 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9661 TemplateArgs = &TemplateArgsBuffer;
9662 }
John McCall6b51f282009-11-23 01:53:49 +00009663
John McCall2d74de92009-12-01 22:10:20 +00009664 Expr *Base;
9665
John McCall7decc9e2010-11-18 06:31:45 +00009666 // If we're filling in a static method where we used to have an
9667 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00009668 if (MemExpr->isImplicitAccess()) {
9669 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9670 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009671 MemExpr->getQualifierLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009672 Fn,
9673 MemExpr->getMemberLoc(),
9674 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009675 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009676 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009677 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00009678 } else {
9679 SourceLocation Loc = MemExpr->getMemberLoc();
9680 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +00009681 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +00009682 Base = new (Context) CXXThisExpr(Loc,
9683 MemExpr->getBaseType(),
9684 /*isImplicit=*/true);
9685 }
John McCall2d74de92009-12-01 22:10:20 +00009686 } else
John McCallc3007a22010-10-26 07:05:15 +00009687 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00009688
John McCall4adb38c2011-04-27 00:36:17 +00009689 ExprValueKind valueKind;
9690 QualType type;
9691 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9692 valueKind = VK_LValue;
9693 type = Fn->getType();
9694 } else {
9695 valueKind = VK_RValue;
9696 type = Context.BoundMemberTy;
9697 }
9698
John McCall2d74de92009-12-01 22:10:20 +00009699 return MemberExpr::Create(Context, Base,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009700 MemExpr->isArrow(),
Douglas Gregorea972d32011-02-28 21:54:11 +00009701 MemExpr->getQualifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009702 Fn,
John McCall16df1e52010-03-30 21:47:33 +00009703 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009704 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00009705 TemplateArgs,
John McCall4adb38c2011-04-27 00:36:17 +00009706 type, valueKind, OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009707 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009708
John McCallc3007a22010-10-26 07:05:15 +00009709 llvm_unreachable("Invalid reference to overloaded function");
9710 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009711}
9712
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009713ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +00009714 DeclAccessPair Found,
9715 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00009716 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00009717}
9718
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009719} // end namespace clang