blob: 6d5eb8038db82f29fe3f926752e428f7f8b786ce [file] [log] [blame]
Douglas Gregor8e9bebd2008-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 McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCall0e800c92010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000036
John McCallf89e55a2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
39static Expr *
40CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41 SourceLocation Loc = SourceLocation()) {
42 Expr *E = new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc);
43 S.DefaultFunctionArrayConversion(E);
44 return E;
45}
46
John McCall120d63c2010-08-24 20:38:10 +000047static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
48 bool InOverloadResolution,
49 StandardConversionSequence &SCS);
50static OverloadingResult
51IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
52 UserDefinedConversionSequence& User,
53 OverloadCandidateSet& Conversions,
54 bool AllowExplicit);
55
56
57static ImplicitConversionSequence::CompareKind
58CompareStandardConversionSequences(Sema &S,
59 const StandardConversionSequence& SCS1,
60 const StandardConversionSequence& SCS2);
61
62static ImplicitConversionSequence::CompareKind
63CompareQualificationConversions(Sema &S,
64 const StandardConversionSequence& SCS1,
65 const StandardConversionSequence& SCS2);
66
67static ImplicitConversionSequence::CompareKind
68CompareDerivedToBaseConversions(Sema &S,
69 const StandardConversionSequence& SCS1,
70 const StandardConversionSequence& SCS2);
71
72
73
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000074/// GetConversionCategory - Retrieve the implicit conversion
75/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000076ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000077GetConversionCategory(ImplicitConversionKind Kind) {
78 static const ImplicitConversionCategory
79 Category[(int)ICK_Num_Conversion_Kinds] = {
80 ICC_Identity,
81 ICC_Lvalue_Transformation,
82 ICC_Lvalue_Transformation,
83 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000084 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000085 ICC_Qualification_Adjustment,
86 ICC_Promotion,
87 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000088 ICC_Promotion,
89 ICC_Conversion,
90 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000091 ICC_Conversion,
92 ICC_Conversion,
93 ICC_Conversion,
94 ICC_Conversion,
95 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000096 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000097 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +000098 ICC_Conversion,
99 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000100 ICC_Conversion
101 };
102 return Category[(int)Kind];
103}
104
105/// GetConversionRank - Retrieve the implicit conversion rank
106/// corresponding to the given implicit conversion kind.
107ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
108 static const ImplicitConversionRank
109 Rank[(int)ICK_Num_Conversion_Kinds] = {
110 ICR_Exact_Match,
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000115 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000116 ICR_Promotion,
117 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000118 ICR_Promotion,
119 ICR_Conversion,
120 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000121 ICR_Conversion,
122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000126 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000127 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000128 ICR_Conversion,
129 ICR_Conversion,
Chandler Carruth23a370f2010-02-25 07:20:54 +0000130 ICR_Complex_Real_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000131 };
132 return Rank[(int)Kind];
133}
134
135/// GetImplicitConversionName - Return the name of this kind of
136/// implicit conversion.
137const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000138 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000139 "No conversion",
140 "Lvalue-to-rvalue",
141 "Array-to-pointer",
142 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000143 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000144 "Qualification",
145 "Integral promotion",
146 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000147 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000148 "Integral conversion",
149 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000150 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000151 "Floating-integral conversion",
152 "Pointer conversion",
153 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000154 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000155 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000156 "Derived-to-base conversion",
157 "Vector conversion",
158 "Vector splat",
159 "Complex-real conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000160 };
161 return Name[Kind];
162}
163
Douglas Gregor60d62c22008-10-31 16:23:19 +0000164/// StandardConversionSequence - Set the standard conversion
165/// sequence to the identity conversion.
166void StandardConversionSequence::setAsIdentityConversion() {
167 First = ICK_Identity;
168 Second = ICK_Identity;
169 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000170 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000171 ReferenceBinding = false;
172 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000173 IsLvalueReference = true;
174 BindsToFunctionLvalue = false;
175 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000176 BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000177 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000178}
179
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000180/// getRank - Retrieve the rank of this standard conversion sequence
181/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
182/// implicit conversions.
183ImplicitConversionRank StandardConversionSequence::getRank() const {
184 ImplicitConversionRank Rank = ICR_Exact_Match;
185 if (GetConversionRank(First) > Rank)
186 Rank = GetConversionRank(First);
187 if (GetConversionRank(Second) > Rank)
188 Rank = GetConversionRank(Second);
189 if (GetConversionRank(Third) > Rank)
190 Rank = GetConversionRank(Third);
191 return Rank;
192}
193
194/// isPointerConversionToBool - Determines whether this conversion is
195/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000196/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000197/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000198bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000199 // Note that FromType has not necessarily been transformed by the
200 // array-to-pointer or function-to-pointer implicit conversions, so
201 // check for their presence as well as checking whether FromType is
202 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000203 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000204 (getFromType()->isPointerType() ||
205 getFromType()->isObjCObjectPointerType() ||
206 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000207 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000208 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
209 return true;
210
211 return false;
212}
213
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000214/// isPointerConversionToVoidPointer - Determines whether this
215/// conversion is a conversion of a pointer to a void pointer. This is
216/// used as part of the ranking of standard conversion sequences (C++
217/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000218bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000219StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000220isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000221 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000222 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000223
224 // Note that FromType has not necessarily been transformed by the
225 // array-to-pointer implicit conversion, so check for its presence
226 // and redo the conversion to get a pointer.
227 if (First == ICK_Array_To_Pointer)
228 FromType = Context.getArrayDecayedType(FromType);
229
John McCall202422e2010-10-26 06:40:27 +0000230 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000231 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000232 return ToPtrType->getPointeeType()->isVoidType();
233
234 return false;
235}
236
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000237/// DebugPrint - Print this standard conversion sequence to standard
238/// error. Useful for debugging overloading issues.
239void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000240 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000241 bool PrintedSomething = false;
242 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000243 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000244 PrintedSomething = true;
245 }
246
247 if (Second != ICK_Identity) {
248 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000249 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000250 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000251 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000252
253 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000254 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000255 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000256 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000257 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000258 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000259 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000260 PrintedSomething = true;
261 }
262
263 if (Third != ICK_Identity) {
264 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000265 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000266 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000267 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000268 PrintedSomething = true;
269 }
270
271 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000272 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000273 }
274}
275
276/// DebugPrint - Print this user-defined conversion sequence to standard
277/// error. Useful for debugging overloading issues.
278void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000279 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000280 if (Before.First || Before.Second || Before.Third) {
281 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000282 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000283 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000284 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000285 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000286 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000287 After.DebugPrint();
288 }
289}
290
291/// DebugPrint - Print this implicit conversion sequence to standard
292/// error. Useful for debugging overloading issues.
293void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000294 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000295 switch (ConversionKind) {
296 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000297 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000298 Standard.DebugPrint();
299 break;
300 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000301 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000302 UserDefined.DebugPrint();
303 break;
304 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000305 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000306 break;
John McCall1d318332010-01-12 00:44:57 +0000307 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000308 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000309 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000310 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000311 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000312 break;
313 }
314
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000315 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000316}
317
John McCall1d318332010-01-12 00:44:57 +0000318void AmbiguousConversionSequence::construct() {
319 new (&conversions()) ConversionSet();
320}
321
322void AmbiguousConversionSequence::destruct() {
323 conversions().~ConversionSet();
324}
325
326void
327AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
328 FromTypePtr = O.FromTypePtr;
329 ToTypePtr = O.ToTypePtr;
330 new (&conversions()) ConversionSet(O.conversions());
331}
332
Douglas Gregora9333192010-05-08 17:41:32 +0000333namespace {
334 // Structure used by OverloadCandidate::DeductionFailureInfo to store
335 // template parameter and template argument information.
336 struct DFIParamWithArguments {
337 TemplateParameter Param;
338 TemplateArgument FirstArg;
339 TemplateArgument SecondArg;
340 };
341}
342
343/// \brief Convert from Sema's representation of template deduction information
344/// to the form used in overload-candidate information.
345OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000346static MakeDeductionFailureInfo(ASTContext &Context,
347 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000348 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000349 OverloadCandidate::DeductionFailureInfo Result;
350 Result.Result = static_cast<unsigned>(TDK);
351 Result.Data = 0;
352 switch (TDK) {
353 case Sema::TDK_Success:
354 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000355 case Sema::TDK_TooManyArguments:
356 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000357 break;
358
359 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000360 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000361 Result.Data = Info.Param.getOpaqueValue();
362 break;
363
Douglas Gregora9333192010-05-08 17:41:32 +0000364 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000365 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000366 // FIXME: Should allocate from normal heap so that we can free this later.
367 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000368 Saved->Param = Info.Param;
369 Saved->FirstArg = Info.FirstArg;
370 Saved->SecondArg = Info.SecondArg;
371 Result.Data = Saved;
372 break;
373 }
374
375 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000376 Result.Data = Info.take();
377 break;
378
Douglas Gregora9333192010-05-08 17:41:32 +0000379 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000380 case Sema::TDK_FailedOverloadResolution:
381 break;
382 }
383
384 return Result;
385}
John McCall1d318332010-01-12 00:44:57 +0000386
Douglas Gregora9333192010-05-08 17:41:32 +0000387void OverloadCandidate::DeductionFailureInfo::Destroy() {
388 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
389 case Sema::TDK_Success:
390 case Sema::TDK_InstantiationDepth:
391 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000392 case Sema::TDK_TooManyArguments:
393 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000394 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000395 break;
396
Douglas Gregora9333192010-05-08 17:41:32 +0000397 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000398 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000399 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000400 Data = 0;
401 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000402
403 case Sema::TDK_SubstitutionFailure:
404 // FIXME: Destroy the template arugment list?
405 Data = 0;
406 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000407
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000408 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000409 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000410 case Sema::TDK_FailedOverloadResolution:
411 break;
412 }
413}
414
415TemplateParameter
416OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
417 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
418 case Sema::TDK_Success:
419 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000420 case Sema::TDK_TooManyArguments:
421 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000422 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000423 return TemplateParameter();
424
425 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000426 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000427 return TemplateParameter::getFromOpaqueValue(Data);
428
429 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000430 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000431 return static_cast<DFIParamWithArguments*>(Data)->Param;
432
433 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000434 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000435 case Sema::TDK_FailedOverloadResolution:
436 break;
437 }
438
439 return TemplateParameter();
440}
Douglas Gregorec20f462010-05-08 20:07:26 +0000441
442TemplateArgumentList *
443OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
444 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
445 case Sema::TDK_Success:
446 case Sema::TDK_InstantiationDepth:
447 case Sema::TDK_TooManyArguments:
448 case Sema::TDK_TooFewArguments:
449 case Sema::TDK_Incomplete:
450 case Sema::TDK_InvalidExplicitArguments:
451 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000452 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000453 return 0;
454
455 case Sema::TDK_SubstitutionFailure:
456 return static_cast<TemplateArgumentList*>(Data);
457
458 // Unhandled
459 case Sema::TDK_NonDeducedMismatch:
460 case Sema::TDK_FailedOverloadResolution:
461 break;
462 }
463
464 return 0;
465}
466
Douglas Gregora9333192010-05-08 17:41:32 +0000467const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
468 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
469 case Sema::TDK_Success:
470 case Sema::TDK_InstantiationDepth:
471 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000472 case Sema::TDK_TooManyArguments:
473 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000474 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000475 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000476 return 0;
477
Douglas Gregora9333192010-05-08 17:41:32 +0000478 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000479 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000480 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
481
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000482 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000483 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000484 case Sema::TDK_FailedOverloadResolution:
485 break;
486 }
487
488 return 0;
489}
490
491const TemplateArgument *
492OverloadCandidate::DeductionFailureInfo::getSecondArg() {
493 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
494 case Sema::TDK_Success:
495 case Sema::TDK_InstantiationDepth:
496 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000497 case Sema::TDK_TooManyArguments:
498 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000499 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000500 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000501 return 0;
502
Douglas Gregora9333192010-05-08 17:41:32 +0000503 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000504 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000505 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
506
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000507 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000508 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000509 case Sema::TDK_FailedOverloadResolution:
510 break;
511 }
512
513 return 0;
514}
515
516void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000517 inherited::clear();
518 Functions.clear();
519}
520
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000521// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000522// overload of the declarations in Old. This routine returns false if
523// New and Old cannot be overloaded, e.g., if New has the same
524// signature as some function in Old (C++ 1.3.10) or if the Old
525// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000526// it does return false, MatchedDecl will point to the decl that New
527// cannot be overloaded with. This decl may be a UsingShadowDecl on
528// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000529//
530// Example: Given the following input:
531//
532// void f(int, float); // #1
533// void f(int, int); // #2
534// int f(int, int); // #3
535//
536// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000537// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000538//
John McCall51fa86f2009-12-02 08:47:38 +0000539// When we process #2, Old contains only the FunctionDecl for #1. By
540// comparing the parameter types, we see that #1 and #2 are overloaded
541// (since they have different signatures), so this routine returns
542// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000543//
John McCall51fa86f2009-12-02 08:47:38 +0000544// When we process #3, Old is an overload set containing #1 and #2. We
545// compare the signatures of #3 to #1 (they're overloaded, so we do
546// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
547// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000548// signature), IsOverload returns false and MatchedDecl will be set to
549// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000550//
551// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
552// into a class by a using declaration. The rules for whether to hide
553// shadow declarations ignore some properties which otherwise figure
554// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000555Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000556Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
557 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000558 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000559 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000560 NamedDecl *OldD = *I;
561
562 bool OldIsUsingDecl = false;
563 if (isa<UsingShadowDecl>(OldD)) {
564 OldIsUsingDecl = true;
565
566 // We can always introduce two using declarations into the same
567 // context, even if they have identical signatures.
568 if (NewIsUsingDecl) continue;
569
570 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
571 }
572
573 // If either declaration was introduced by a using declaration,
574 // we'll need to use slightly different rules for matching.
575 // Essentially, these rules are the normal rules, except that
576 // function templates hide function templates with different
577 // return types or template parameter lists.
578 bool UseMemberUsingDeclRules =
579 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
580
John McCall51fa86f2009-12-02 08:47:38 +0000581 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000582 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
583 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
584 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
585 continue;
586 }
587
John McCall871b2e72009-12-09 03:35:25 +0000588 Match = *I;
589 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000590 }
John McCall51fa86f2009-12-02 08:47:38 +0000591 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000592 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
593 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
594 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
595 continue;
596 }
597
John McCall871b2e72009-12-09 03:35:25 +0000598 Match = *I;
599 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000600 }
John McCalld7945c62010-11-10 03:01:53 +0000601 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000602 // We can overload with these, which can show up when doing
603 // redeclaration checks for UsingDecls.
604 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000605 } else if (isa<TagDecl>(OldD)) {
606 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000607 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
608 // Optimistically assume that an unresolved using decl will
609 // overload; if it doesn't, we'll have to diagnose during
610 // template instantiation.
611 } else {
John McCall68263142009-11-18 22:49:29 +0000612 // (C++ 13p1):
613 // Only function declarations can be overloaded; object and type
614 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000615 Match = *I;
616 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000617 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000618 }
John McCall68263142009-11-18 22:49:29 +0000619
John McCall871b2e72009-12-09 03:35:25 +0000620 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000621}
622
John McCallad00b772010-06-16 08:42:20 +0000623bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
624 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000625 // If both of the functions are extern "C", then they are not
626 // overloads.
627 if (Old->isExternC() && New->isExternC())
628 return false;
629
John McCall68263142009-11-18 22:49:29 +0000630 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
631 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
632
633 // C++ [temp.fct]p2:
634 // A function template can be overloaded with other function templates
635 // and with normal (non-template) functions.
636 if ((OldTemplate == 0) != (NewTemplate == 0))
637 return true;
638
639 // Is the function New an overload of the function Old?
640 QualType OldQType = Context.getCanonicalType(Old->getType());
641 QualType NewQType = Context.getCanonicalType(New->getType());
642
643 // Compare the signatures (C++ 1.3.10) of the two functions to
644 // determine whether they are overloads. If we find any mismatch
645 // in the signature, they are overloads.
646
647 // If either of these functions is a K&R-style function (no
648 // prototype), then we consider them to have matching signatures.
649 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
650 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
651 return false;
652
John McCallf4c73712011-01-19 06:33:43 +0000653 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
654 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000655
656 // The signature of a function includes the types of its
657 // parameters (C++ 1.3.10), which includes the presence or absence
658 // of the ellipsis; see C++ DR 357).
659 if (OldQType != NewQType &&
660 (OldType->getNumArgs() != NewType->getNumArgs() ||
661 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000662 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000663 return true;
664
665 // C++ [temp.over.link]p4:
666 // The signature of a function template consists of its function
667 // signature, its return type and its template parameter list. The names
668 // of the template parameters are significant only for establishing the
669 // relationship between the template parameters and the rest of the
670 // signature.
671 //
672 // We check the return type and template parameter lists for function
673 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000674 //
675 // However, we don't consider either of these when deciding whether
676 // a member introduced by a shadow declaration is hidden.
677 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000678 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
679 OldTemplate->getTemplateParameters(),
680 false, TPL_TemplateMatch) ||
681 OldType->getResultType() != NewType->getResultType()))
682 return true;
683
684 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000685 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +0000686 //
687 // As part of this, also check whether one of the member functions
688 // is static, in which case they are not overloads (C++
689 // 13.1p2). While not part of the definition of the signature,
690 // this check is important to determine whether these functions
691 // can be overloaded.
692 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
693 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
694 if (OldMethod && NewMethod &&
695 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000696 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
697 OldMethod->getRefQualifier() != NewMethod->getRefQualifier()))
John McCall68263142009-11-18 22:49:29 +0000698 return true;
699
700 // The signatures match; this is not an overload.
701 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000702}
703
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000704/// TryImplicitConversion - Attempt to perform an implicit conversion
705/// from the given expression (Expr) to the given type (ToType). This
706/// function returns an implicit conversion sequence that can be used
707/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000708///
709/// void f(float f);
710/// void g(int i) { f(i); }
711///
712/// this routine would produce an implicit conversion sequence to
713/// describe the initialization of f from i, which will be a standard
714/// conversion sequence containing an lvalue-to-rvalue conversion (C++
715/// 4.1) followed by a floating-integral conversion (C++ 4.9).
716//
717/// Note that this routine only determines how the conversion can be
718/// performed; it does not actually perform the conversion. As such,
719/// it will not produce any diagnostics if no conversion is available,
720/// but will instead return an implicit conversion sequence of kind
721/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000722///
723/// If @p SuppressUserConversions, then user-defined conversions are
724/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000725/// If @p AllowExplicit, then explicit user-defined conversions are
726/// permitted.
John McCall120d63c2010-08-24 20:38:10 +0000727static ImplicitConversionSequence
728TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
729 bool SuppressUserConversions,
730 bool AllowExplicit,
731 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000732 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +0000733 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
734 ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000735 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000736 return ICS;
737 }
738
John McCall120d63c2010-08-24 20:38:10 +0000739 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000740 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000741 return ICS;
742 }
743
Douglas Gregor604eb652010-08-11 02:15:33 +0000744 // C++ [over.ics.user]p4:
745 // A conversion of an expression of class type to the same class
746 // type is given Exact Match rank, and a conversion of an
747 // expression of class type to a base class of that type is
748 // given Conversion rank, in spite of the fact that a copy/move
749 // constructor (i.e., a user-defined conversion function) is
750 // called for those cases.
751 QualType FromType = From->getType();
752 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +0000753 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
754 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000755 ICS.setStandard();
756 ICS.Standard.setAsIdentityConversion();
757 ICS.Standard.setFromType(FromType);
758 ICS.Standard.setAllToTypes(ToType);
759
760 // We don't actually check at this point whether there is a valid
761 // copy/move constructor, since overloading just assumes that it
762 // exists. When we actually perform initialization, we'll find the
763 // appropriate constructor to copy the returned object, if needed.
764 ICS.Standard.CopyConstructor = 0;
Douglas Gregor604eb652010-08-11 02:15:33 +0000765
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000766 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +0000767 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000768 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor604eb652010-08-11 02:15:33 +0000769
770 return ICS;
771 }
772
773 if (SuppressUserConversions) {
774 // We're not in the case above, so there is no conversion that
775 // we can perform.
776 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000777 return ICS;
778 }
779
780 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000781 OverloadCandidateSet Conversions(From->getExprLoc());
782 OverloadingResult UserDefResult
John McCall120d63c2010-08-24 20:38:10 +0000783 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000784 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000785
786 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000787 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000788 // C++ [over.ics.user]p4:
789 // A conversion of an expression of class type to the same class
790 // type is given Exact Match rank, and a conversion of an
791 // expression of class type to a base class of that type is
792 // given Conversion rank, in spite of the fact that a copy
793 // constructor (i.e., a user-defined conversion function) is
794 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000795 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000796 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000797 QualType FromCanon
John McCall120d63c2010-08-24 20:38:10 +0000798 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
799 QualType ToCanon
800 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000801 if (Constructor->isCopyConstructor() &&
John McCall120d63c2010-08-24 20:38:10 +0000802 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000803 // Turn this into a "standard" conversion sequence, so that it
804 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000805 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000806 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000807 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000808 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000809 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000810 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000811 ICS.Standard.Second = ICK_Derived_To_Base;
812 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000813 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000814
815 // C++ [over.best.ics]p4:
816 // However, when considering the argument of a user-defined
817 // conversion function that is a candidate by 13.3.1.3 when
818 // invoked for the copying of the temporary in the second step
819 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
820 // 13.3.1.6 in all cases, only standard conversion sequences and
821 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000822 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000823 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000824 }
John McCallcefd3ad2010-01-13 22:30:33 +0000825 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000826 ICS.setAmbiguous();
827 ICS.Ambiguous.setFromType(From->getType());
828 ICS.Ambiguous.setToType(ToType);
829 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
830 Cand != Conversions.end(); ++Cand)
831 if (Cand->Viable)
832 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000833 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000834 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000835 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000836
837 return ICS;
838}
839
John McCall120d63c2010-08-24 20:38:10 +0000840bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
841 const InitializedEntity &Entity,
842 Expr *Initializer,
843 bool SuppressUserConversions,
844 bool AllowExplicitConversions,
845 bool InOverloadResolution) {
846 ImplicitConversionSequence ICS
847 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
848 SuppressUserConversions,
849 AllowExplicitConversions,
850 InOverloadResolution);
851 if (ICS.isBad()) return true;
852
853 // Perform the actual conversion.
854 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
855 return false;
856}
857
Douglas Gregor575c63a2010-04-16 22:27:05 +0000858/// PerformImplicitConversion - Perform an implicit conversion of the
859/// expression From to the type ToType. Returns true if there was an
860/// error, false otherwise. The expression From is replaced with the
861/// converted expression. Flavor is the kind of conversion we're
862/// performing, used in the error message. If @p AllowExplicit,
863/// explicit user-defined conversions are permitted.
864bool
865Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
866 AssignmentAction Action, bool AllowExplicit) {
867 ImplicitConversionSequence ICS;
868 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
869}
870
871bool
872Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
873 AssignmentAction Action, bool AllowExplicit,
874 ImplicitConversionSequence& ICS) {
John McCall120d63c2010-08-24 20:38:10 +0000875 ICS = clang::TryImplicitConversion(*this, From, ToType,
876 /*SuppressUserConversions=*/false,
877 AllowExplicit,
878 /*InOverloadResolution=*/false);
Douglas Gregor575c63a2010-04-16 22:27:05 +0000879 return PerformImplicitConversion(From, ToType, ICS, Action);
880}
881
Douglas Gregor43c79c22009-12-09 00:47:37 +0000882/// \brief Determine whether the conversion from FromType to ToType is a valid
883/// conversion that strips "noreturn" off the nested function type.
884static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
885 QualType ToType, QualType &ResultTy) {
886 if (Context.hasSameUnqualifiedType(FromType, ToType))
887 return false;
888
John McCall00ccbef2010-12-21 00:44:39 +0000889 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
890 // where F adds one of the following at most once:
891 // - a pointer
892 // - a member pointer
893 // - a block pointer
894 CanQualType CanTo = Context.getCanonicalType(ToType);
895 CanQualType CanFrom = Context.getCanonicalType(FromType);
896 Type::TypeClass TyClass = CanTo->getTypeClass();
897 if (TyClass != CanFrom->getTypeClass()) return false;
898 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
899 if (TyClass == Type::Pointer) {
900 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
901 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
902 } else if (TyClass == Type::BlockPointer) {
903 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
904 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
905 } else if (TyClass == Type::MemberPointer) {
906 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
907 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
908 } else {
909 return false;
910 }
Douglas Gregor43c79c22009-12-09 00:47:37 +0000911
John McCall00ccbef2010-12-21 00:44:39 +0000912 TyClass = CanTo->getTypeClass();
913 if (TyClass != CanFrom->getTypeClass()) return false;
914 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
915 return false;
916 }
917
918 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
919 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
920 if (!EInfo.getNoReturn()) return false;
921
922 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
923 assert(QualType(FromFn, 0).isCanonical());
924 if (QualType(FromFn, 0) != CanTo) return false;
925
926 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +0000927 return true;
928}
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000929
930/// \brief Determine whether the conversion from FromType to ToType is a valid
931/// vector conversion.
932///
933/// \param ICK Will be set to the vector conversion kind, if this is a vector
934/// conversion.
935static bool IsVectorConversion(ASTContext &Context, QualType FromType,
936 QualType ToType, ImplicitConversionKind &ICK) {
937 // We need at least one of these types to be a vector type to have a vector
938 // conversion.
939 if (!ToType->isVectorType() && !FromType->isVectorType())
940 return false;
941
942 // Identical types require no conversions.
943 if (Context.hasSameUnqualifiedType(FromType, ToType))
944 return false;
945
946 // There are no conversions between extended vector types, only identity.
947 if (ToType->isExtVectorType()) {
948 // There are no conversions between extended vector types other than the
949 // identity conversion.
950 if (FromType->isExtVectorType())
951 return false;
952
953 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +0000954 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000955 ICK = ICK_Vector_Splat;
956 return true;
957 }
958 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000959
960 // We can perform the conversion between vector types in the following cases:
961 // 1)vector types are equivalent AltiVec and GCC vector types
962 // 2)lax vector conversions are permitted and the vector types are of the
963 // same size
964 if (ToType->isVectorType() && FromType->isVectorType()) {
965 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +0000966 (Context.getLangOptions().LaxVectorConversions &&
967 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +0000968 ICK = ICK_Vector_Conversion;
969 return true;
970 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000971 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000972
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000973 return false;
974}
Douglas Gregor43c79c22009-12-09 00:47:37 +0000975
Douglas Gregor60d62c22008-10-31 16:23:19 +0000976/// IsStandardConversion - Determines whether there is a standard
977/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
978/// expression From to the type ToType. Standard conversion sequences
979/// only consider non-class types; for conversions that involve class
980/// types, use TryImplicitConversion. If a conversion exists, SCS will
981/// contain the standard conversion sequence required to perform this
982/// conversion and this routine will return true. Otherwise, this
983/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +0000984static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
985 bool InOverloadResolution,
986 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000987 QualType FromType = From->getType();
John McCall120d63c2010-08-24 20:38:10 +0000988
Douglas Gregor60d62c22008-10-31 16:23:19 +0000989 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000990 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000991 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000992 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000993 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000994 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000995
Douglas Gregorf9201e02009-02-11 23:02:49 +0000996 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000997 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000998 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +0000999 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001000 return false;
1001
Mike Stump1eb44332009-09-09 15:08:12 +00001002 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001003 }
1004
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001005 // The first conversion can be an lvalue-to-rvalue conversion,
1006 // array-to-pointer conversion, or function-to-pointer conversion
1007 // (C++ 4p1).
1008
John McCall120d63c2010-08-24 20:38:10 +00001009 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001010 DeclAccessPair AccessPair;
1011 if (FunctionDecl *Fn
John McCall120d63c2010-08-24 20:38:10 +00001012 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1013 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001014 // We were able to resolve the address of the overloaded function,
1015 // so we can convert to the type of that function.
1016 FromType = Fn->getType();
1017 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
1018 if (!Method->isStatic()) {
John McCallf4c73712011-01-19 06:33:43 +00001019 const Type *ClassType
John McCall120d63c2010-08-24 20:38:10 +00001020 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1021 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001022 }
1023 }
1024
1025 // If the "from" expression takes the address of the overloaded
1026 // function, update the type of the resulting expression accordingly.
1027 if (FromType->getAs<FunctionType>())
1028 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCall2de56d12010-08-25 11:45:40 +00001029 if (UnOp->getOpcode() == UO_AddrOf)
John McCall120d63c2010-08-24 20:38:10 +00001030 FromType = S.Context.getPointerType(FromType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001031
1032 // Check that we've computed the proper type after overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00001033 assert(S.Context.hasSameType(FromType,
1034 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001035 } else {
1036 return false;
1037 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001038 }
Mike Stump1eb44332009-09-09 15:08:12 +00001039 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001040 // An lvalue (3.10) of a non-function, non-array type T can be
1041 // converted to an rvalue.
John McCall7eb0a9e2010-11-24 05:12:34 +00001042 bool argIsLValue = From->isLValue();
1043 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001044 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001045 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001046 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001047
1048 // If T is a non-class type, the type of the rvalue is the
1049 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001050 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1051 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001052 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001053 } else if (FromType->isArrayType()) {
1054 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001055 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001056
1057 // An lvalue or rvalue of type "array of N T" or "array of unknown
1058 // bound of T" can be converted to an rvalue of type "pointer to
1059 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001060 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001061
John McCall120d63c2010-08-24 20:38:10 +00001062 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001063 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001064 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001065
1066 // For the purpose of ranking in overload resolution
1067 // (13.3.3.1.1), this conversion is considered an
1068 // array-to-pointer conversion followed by a qualification
1069 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001070 SCS.Second = ICK_Identity;
1071 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +00001072 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001073 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001074 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001075 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001076 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001077 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001078
1079 // An lvalue of function type T can be converted to an rvalue of
1080 // type "pointer to T." The result is a pointer to the
1081 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001082 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001083 } else {
1084 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001085 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001086 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001087 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001088
1089 // The second conversion can be an integral promotion, floating
1090 // point promotion, integral conversion, floating point conversion,
1091 // floating-integral conversion, pointer conversion,
1092 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001093 // For overloading in C, this can also be a "compatible-type"
1094 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001095 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001096 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001097 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001098 // The unqualified versions of the types are the same: there's no
1099 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001100 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001101 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001102 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001103 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001104 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001105 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001106 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001107 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001108 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001109 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001110 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001111 SCS.Second = ICK_Complex_Promotion;
1112 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001113 } else if (ToType->isBooleanType() &&
1114 (FromType->isArithmeticType() ||
1115 FromType->isAnyPointerType() ||
1116 FromType->isBlockPointerType() ||
1117 FromType->isMemberPointerType() ||
1118 FromType->isNullPtrType())) {
1119 // Boolean conversions (C++ 4.12).
1120 SCS.Second = ICK_Boolean_Conversion;
1121 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001122 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001123 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001124 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001125 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001126 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001127 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001128 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001129 SCS.Second = ICK_Complex_Conversion;
1130 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001131 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1132 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001133 // Complex-real conversions (C99 6.3.1.7)
1134 SCS.Second = ICK_Complex_Real;
1135 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001136 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001137 // Floating point conversions (C++ 4.8).
1138 SCS.Second = ICK_Floating_Conversion;
1139 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001140 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001141 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001142 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001143 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001144 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001145 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001146 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001147 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1148 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001149 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001150 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001151 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall120d63c2010-08-24 20:38:10 +00001152 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1153 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001154 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001155 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001156 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001157 SCS.Second = SecondICK;
1158 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001159 } else if (!S.getLangOptions().CPlusPlus &&
1160 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001161 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001162 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001163 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001164 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001165 // Treat a conversion that strips "noreturn" as an identity conversion.
1166 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001167 } else {
1168 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001169 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001170 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001171 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001172
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001173 QualType CanonFrom;
1174 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001175 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall120d63c2010-08-24 20:38:10 +00001176 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001177 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001178 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001179 CanonFrom = S.Context.getCanonicalType(FromType);
1180 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001181 } else {
1182 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001183 SCS.Third = ICK_Identity;
1184
Mike Stump1eb44332009-09-09 15:08:12 +00001185 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001186 // [...] Any difference in top-level cv-qualification is
1187 // subsumed by the initialization itself and does not constitute
1188 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001189 CanonFrom = S.Context.getCanonicalType(FromType);
1190 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001191 if (CanonFrom.getLocalUnqualifiedType()
1192 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001193 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1194 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001195 FromType = ToType;
1196 CanonFrom = CanonTo;
1197 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001198 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001199 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001200
1201 // If we have not converted the argument type to the parameter type,
1202 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001203 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001204 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001205
Douglas Gregor60d62c22008-10-31 16:23:19 +00001206 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001207}
1208
1209/// IsIntegralPromotion - Determines whether the conversion from the
1210/// expression From (whose potentially-adjusted type is FromType) to
1211/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1212/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001213bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001214 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001215 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001216 if (!To) {
1217 return false;
1218 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001219
1220 // An rvalue of type char, signed char, unsigned char, short int, or
1221 // unsigned short int can be converted to an rvalue of type int if
1222 // int can represent all the values of the source type; otherwise,
1223 // the source rvalue can be converted to an rvalue of type unsigned
1224 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001225 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1226 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001227 if (// We can promote any signed, promotable integer type to an int
1228 (FromType->isSignedIntegerType() ||
1229 // We can promote any unsigned integer type whose size is
1230 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001231 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001232 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001233 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001234 }
1235
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001236 return To->getKind() == BuiltinType::UInt;
1237 }
1238
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001239 // C++0x [conv.prom]p3:
1240 // A prvalue of an unscoped enumeration type whose underlying type is not
1241 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1242 // following types that can represent all the values of the enumeration
1243 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1244 // unsigned int, long int, unsigned long int, long long int, or unsigned
1245 // long long int. If none of the types in that list can represent all the
1246 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1247 // type can be converted to an rvalue a prvalue of the extended integer type
1248 // with lowest integer conversion rank (4.13) greater than the rank of long
1249 // long in which all the values of the enumeration can be represented. If
1250 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001251 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1252 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1253 // provided for a scoped enumeration.
1254 if (FromEnumType->getDecl()->isScoped())
1255 return false;
1256
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001257 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregor5dde1602010-09-12 03:38:25 +00001258 if (ToType->isIntegerType() &&
1259 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001260 return Context.hasSameUnqualifiedType(ToType,
1261 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001262 }
John McCall842aef82009-12-09 09:09:27 +00001263
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001264 // C++0x [conv.prom]p2:
1265 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1266 // to an rvalue a prvalue of the first of the following types that can
1267 // represent all the values of its underlying type: int, unsigned int,
1268 // long int, unsigned long int, long long int, or unsigned long long int.
1269 // If none of the types in that list can represent all the values of its
1270 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1271 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1272 // type.
1273 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1274 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001275 // Determine whether the type we're converting from is signed or
1276 // unsigned.
1277 bool FromIsSigned;
1278 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +00001279
1280 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1281 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001282
1283 // The types we'll try to promote to, in the appropriate
1284 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001285 QualType PromoteTypes[6] = {
1286 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001287 Context.LongTy, Context.UnsignedLongTy ,
1288 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001289 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001290 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001291 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1292 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001293 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001294 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1295 // We found the type that we can promote to. If this is the
1296 // type we wanted, we have a promotion. Otherwise, no
1297 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001298 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001299 }
1300 }
1301 }
1302
1303 // An rvalue for an integral bit-field (9.6) can be converted to an
1304 // rvalue of type int if int can represent all the values of the
1305 // bit-field; otherwise, it can be converted to unsigned int if
1306 // unsigned int can represent all the values of the bit-field. If
1307 // the bit-field is larger yet, no integral promotion applies to
1308 // it. If the bit-field has an enumerated type, it is treated as any
1309 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001310 // FIXME: We should delay checking of bit-fields until we actually perform the
1311 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001312 using llvm::APSInt;
1313 if (From)
1314 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001315 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001316 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001317 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1318 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1319 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001320
Douglas Gregor86f19402008-12-20 23:49:58 +00001321 // Are we promoting to an int from a bitfield that fits in an int?
1322 if (BitWidth < ToSize ||
1323 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1324 return To->getKind() == BuiltinType::Int;
1325 }
Mike Stump1eb44332009-09-09 15:08:12 +00001326
Douglas Gregor86f19402008-12-20 23:49:58 +00001327 // Are we promoting to an unsigned int from an unsigned bitfield
1328 // that fits into an unsigned int?
1329 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1330 return To->getKind() == BuiltinType::UInt;
1331 }
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Douglas Gregor86f19402008-12-20 23:49:58 +00001333 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001334 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001335 }
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001337 // An rvalue of type bool can be converted to an rvalue of type int,
1338 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001339 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001340 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001341 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001342
1343 return false;
1344}
1345
1346/// IsFloatingPointPromotion - Determines whether the conversion from
1347/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1348/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001349bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001350 /// An rvalue of type float can be converted to an rvalue of type
1351 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001352 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1353 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001354 if (FromBuiltin->getKind() == BuiltinType::Float &&
1355 ToBuiltin->getKind() == BuiltinType::Double)
1356 return true;
1357
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001358 // C99 6.3.1.5p1:
1359 // When a float is promoted to double or long double, or a
1360 // double is promoted to long double [...].
1361 if (!getLangOptions().CPlusPlus &&
1362 (FromBuiltin->getKind() == BuiltinType::Float ||
1363 FromBuiltin->getKind() == BuiltinType::Double) &&
1364 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1365 return true;
1366 }
1367
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001368 return false;
1369}
1370
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001371/// \brief Determine if a conversion is a complex promotion.
1372///
1373/// A complex promotion is defined as a complex -> complex conversion
1374/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001375/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001376bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001377 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001378 if (!FromComplex)
1379 return false;
1380
John McCall183700f2009-09-21 23:43:11 +00001381 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001382 if (!ToComplex)
1383 return false;
1384
1385 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001386 ToComplex->getElementType()) ||
1387 IsIntegralPromotion(0, FromComplex->getElementType(),
1388 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001389}
1390
Douglas Gregorcb7de522008-11-26 23:31:11 +00001391/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1392/// the pointer type FromPtr to a pointer to type ToPointee, with the
1393/// same type qualifiers as FromPtr has on its pointee type. ToType,
1394/// if non-empty, will be a pointer to ToType that may or may not have
1395/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001396static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001397BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001398 QualType ToPointee, QualType ToType,
1399 ASTContext &Context) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001400 assert((FromPtr->getTypeClass() == Type::Pointer ||
1401 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1402 "Invalid similarly-qualified pointer type");
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001403
1404 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1405 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1406 return ToType.getUnqualifiedType();
1407
Douglas Gregorda80f742010-12-01 21:43:58 +00001408 QualType CanonFromPointee
1409 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001410 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001411 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001412
1413 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001414 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001415 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001416 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001417 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001418
1419 // Build a pointer to ToPointee. It has the right qualifiers
1420 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001421 if (isa<ObjCObjectPointerType>(ToType))
1422 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001423 return Context.getPointerType(ToPointee);
1424 }
1425
1426 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001427 QualType QualifiedCanonToPointee
1428 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001429
Douglas Gregorda80f742010-12-01 21:43:58 +00001430 if (isa<ObjCObjectPointerType>(ToType))
1431 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1432 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001433}
1434
Mike Stump1eb44332009-09-09 15:08:12 +00001435static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001436 bool InOverloadResolution,
1437 ASTContext &Context) {
1438 // Handle value-dependent integral null pointer constants correctly.
1439 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1440 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001441 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001442 return !InOverloadResolution;
1443
Douglas Gregorce940492009-09-25 04:25:58 +00001444 return Expr->isNullPointerConstant(Context,
1445 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1446 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001447}
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001449/// IsPointerConversion - Determines whether the conversion of the
1450/// expression From, which has the (possibly adjusted) type FromType,
1451/// can be converted to the type ToType via a pointer conversion (C++
1452/// 4.10). If so, returns true and places the converted type (that
1453/// might differ from ToType in its cv-qualifiers at some level) into
1454/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001455///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001456/// This routine also supports conversions to and from block pointers
1457/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1458/// pointers to interfaces. FIXME: Once we've determined the
1459/// appropriate overloading rules for Objective-C, we may want to
1460/// split the Objective-C checks into a different routine; however,
1461/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001462/// conversions, so for now they live here. IncompatibleObjC will be
1463/// set if the conversion is an allowed Objective-C conversion that
1464/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001465bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001466 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001467 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001468 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001469 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001470 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1471 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001472 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001473
Mike Stump1eb44332009-09-09 15:08:12 +00001474 // Conversion from a null pointer constant to any Objective-C pointer type.
1475 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001476 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001477 ConvertedType = ToType;
1478 return true;
1479 }
1480
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001481 // Blocks: Block pointers can be converted to void*.
1482 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001483 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001484 ConvertedType = ToType;
1485 return true;
1486 }
1487 // Blocks: A null pointer constant can be converted to a block
1488 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001489 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001490 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001491 ConvertedType = ToType;
1492 return true;
1493 }
1494
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001495 // If the left-hand-side is nullptr_t, the right side can be a null
1496 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001497 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001498 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001499 ConvertedType = ToType;
1500 return true;
1501 }
1502
Ted Kremenek6217b802009-07-29 21:53:49 +00001503 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001504 if (!ToTypePtr)
1505 return false;
1506
1507 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001508 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001509 ConvertedType = ToType;
1510 return true;
1511 }
Sebastian Redl07779722008-10-31 14:43:28 +00001512
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001513 // Beyond this point, both types need to be pointers
1514 // , including objective-c pointers.
1515 QualType ToPointeeType = ToTypePtr->getPointeeType();
1516 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001517 ConvertedType = BuildSimilarlyQualifiedPointerType(
1518 FromType->getAs<ObjCObjectPointerType>(),
1519 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001520 ToType, Context);
1521 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001522 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001523 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001524 if (!FromTypePtr)
1525 return false;
1526
1527 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001528
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001529 // If the unqualified pointee types are the same, this can't be a
1530 // pointer conversion, so don't do all of the work below.
1531 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1532 return false;
1533
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001534 // An rvalue of type "pointer to cv T," where T is an object type,
1535 // can be converted to an rvalue of type "pointer to cv void" (C++
1536 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001537 if (FromPointeeType->isIncompleteOrObjectType() &&
1538 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001539 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001540 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001541 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001542 return true;
1543 }
1544
Douglas Gregorf9201e02009-02-11 23:02:49 +00001545 // When we're overloading in C, we allow a special kind of pointer
1546 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001547 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001548 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001549 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001550 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001551 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001552 return true;
1553 }
1554
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001555 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001556 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001557 // An rvalue of type "pointer to cv D," where D is a class type,
1558 // can be converted to an rvalue of type "pointer to cv B," where
1559 // B is a base class (clause 10) of D. If B is an inaccessible
1560 // (clause 11) or ambiguous (10.2) base class of D, a program that
1561 // necessitates this conversion is ill-formed. The result of the
1562 // conversion is a pointer to the base class sub-object of the
1563 // derived class object. The null pointer value is converted to
1564 // the null pointer value of the destination type.
1565 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001566 // Note that we do not check for ambiguity or inaccessibility
1567 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001568 if (getLangOptions().CPlusPlus &&
1569 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001570 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001571 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001572 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001573 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001574 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001575 ToType, Context);
1576 return true;
1577 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001578
Douglas Gregorc7887512008-12-19 19:13:09 +00001579 return false;
1580}
1581
1582/// isObjCPointerConversion - Determines whether this is an
1583/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1584/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001585bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001586 QualType& ConvertedType,
1587 bool &IncompatibleObjC) {
1588 if (!getLangOptions().ObjC1)
1589 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001590
Steve Naroff14108da2009-07-10 23:34:53 +00001591 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00001592 const ObjCObjectPointerType* ToObjCPtr =
1593 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001594 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001595 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001596
Steve Naroff14108da2009-07-10 23:34:53 +00001597 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001598 // If the pointee types are the same (ignoring qualifications),
1599 // then this is not a pointer conversion.
1600 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1601 FromObjCPtr->getPointeeType()))
1602 return false;
1603
Steve Naroffde2e22d2009-07-15 18:40:39 +00001604 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001605 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001606 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001607 ConvertedType = ToType;
1608 return true;
1609 }
1610 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001611 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001612 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001613 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001614 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001615 ConvertedType = ToType;
1616 return true;
1617 }
1618 // Objective C++: We're able to convert from a pointer to an
1619 // interface to a pointer to a different interface.
1620 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001621 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1622 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1623 if (getLangOptions().CPlusPlus && LHS && RHS &&
1624 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1625 FromObjCPtr->getPointeeType()))
1626 return false;
Douglas Gregorda80f742010-12-01 21:43:58 +00001627 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1628 ToObjCPtr->getPointeeType(),
1629 ToType, Context);
Steve Naroff14108da2009-07-10 23:34:53 +00001630 return true;
1631 }
1632
1633 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1634 // Okay: this is some kind of implicit downcast of Objective-C
1635 // interfaces, which is permitted. However, we're going to
1636 // complain about it.
1637 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00001638 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1639 ToObjCPtr->getPointeeType(),
1640 ToType, Context);
Steve Naroff14108da2009-07-10 23:34:53 +00001641 return true;
1642 }
Mike Stump1eb44332009-09-09 15:08:12 +00001643 }
Steve Naroff14108da2009-07-10 23:34:53 +00001644 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001645 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001646 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001647 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001648 else if (const BlockPointerType *ToBlockPtr =
1649 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001650 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001651 // to a block pointer type.
1652 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1653 ConvertedType = ToType;
1654 return true;
1655 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001656 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001657 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001658 else if (FromType->getAs<BlockPointerType>() &&
1659 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1660 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001661 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001662 ConvertedType = ToType;
1663 return true;
1664 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001665 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001666 return false;
1667
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001668 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001669 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001670 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00001671 else if (const BlockPointerType *FromBlockPtr =
1672 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001673 FromPointeeType = FromBlockPtr->getPointeeType();
1674 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001675 return false;
1676
Douglas Gregorc7887512008-12-19 19:13:09 +00001677 // If we have pointers to pointers, recursively check whether this
1678 // is an Objective-C conversion.
1679 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1680 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1681 IncompatibleObjC)) {
1682 // We always complain about this conversion.
1683 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00001684 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregorc7887512008-12-19 19:13:09 +00001685 return true;
1686 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001687 // Allow conversion of pointee being objective-c pointer to another one;
1688 // as in I* to id.
1689 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1690 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1691 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1692 IncompatibleObjC)) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001693 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001694 return true;
1695 }
1696
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001697 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001698 // differences in the argument and result types are in Objective-C
1699 // pointer conversions. If so, we permit the conversion (but
1700 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001701 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001702 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001703 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001704 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001705 if (FromFunctionType && ToFunctionType) {
1706 // If the function types are exactly the same, this isn't an
1707 // Objective-C pointer conversion.
1708 if (Context.getCanonicalType(FromPointeeType)
1709 == Context.getCanonicalType(ToPointeeType))
1710 return false;
1711
1712 // Perform the quick checks that will tell us whether these
1713 // function types are obviously different.
1714 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1715 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1716 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1717 return false;
1718
1719 bool HasObjCConversion = false;
1720 if (Context.getCanonicalType(FromFunctionType->getResultType())
1721 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1722 // Okay, the types match exactly. Nothing to do.
1723 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1724 ToFunctionType->getResultType(),
1725 ConvertedType, IncompatibleObjC)) {
1726 // Okay, we have an Objective-C pointer conversion.
1727 HasObjCConversion = true;
1728 } else {
1729 // Function types are too different. Abort.
1730 return false;
1731 }
Mike Stump1eb44332009-09-09 15:08:12 +00001732
Douglas Gregorc7887512008-12-19 19:13:09 +00001733 // Check argument types.
1734 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1735 ArgIdx != NumArgs; ++ArgIdx) {
1736 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1737 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1738 if (Context.getCanonicalType(FromArgType)
1739 == Context.getCanonicalType(ToArgType)) {
1740 // Okay, the types match exactly. Nothing to do.
1741 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1742 ConvertedType, IncompatibleObjC)) {
1743 // Okay, we have an Objective-C pointer conversion.
1744 HasObjCConversion = true;
1745 } else {
1746 // Argument types are too different. Abort.
1747 return false;
1748 }
1749 }
1750
1751 if (HasObjCConversion) {
1752 // We had an Objective-C conversion. Allow this pointer
1753 // conversion, but complain about it.
1754 ConvertedType = ToType;
1755 IncompatibleObjC = true;
1756 return true;
1757 }
1758 }
1759
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001760 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001761}
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001762
1763/// FunctionArgTypesAreEqual - This routine checks two function proto types
1764/// for equlity of their argument types. Caller has already checked that
1765/// they have same number of arguments. This routine assumes that Objective-C
1766/// pointer types which only differ in their protocol qualifiers are equal.
John McCallf4c73712011-01-19 06:33:43 +00001767bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
1768 const FunctionProtoType *NewType) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001769 if (!getLangOptions().ObjC1)
1770 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1771 NewType->arg_type_begin());
1772
1773 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1774 N = NewType->arg_type_begin(),
1775 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1776 QualType ToType = (*O);
1777 QualType FromType = (*N);
1778 if (ToType != FromType) {
1779 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1780 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001781 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1782 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1783 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1784 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001785 continue;
1786 }
John McCallc12c5bb2010-05-15 11:32:37 +00001787 else if (const ObjCObjectPointerType *PTTo =
1788 ToType->getAs<ObjCObjectPointerType>()) {
1789 if (const ObjCObjectPointerType *PTFr =
1790 FromType->getAs<ObjCObjectPointerType>())
1791 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1792 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001793 }
1794 return false;
1795 }
1796 }
1797 return true;
1798}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001799
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001800/// CheckPointerConversion - Check the pointer conversion from the
1801/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001802/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001803/// conversions for which IsPointerConversion has already returned
1804/// true. It returns true and produces a diagnostic if there was an
1805/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001806bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001807 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001808 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001809 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001810 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00001811 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001812
John McCalldaa8e4e2010-11-15 09:13:47 +00001813 Kind = CK_BitCast;
1814
Douglas Gregord7a95972010-06-08 17:35:15 +00001815 if (CXXBoolLiteralExpr* LitBool
1816 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00001817 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregord7a95972010-06-08 17:35:15 +00001818 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1819 << ToType;
1820
Ted Kremenek6217b802009-07-29 21:53:49 +00001821 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1822 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001823 QualType FromPointeeType = FromPtrType->getPointeeType(),
1824 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001825
Douglas Gregor5fccd362010-03-03 23:55:11 +00001826 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1827 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001828 // We must have a derived-to-base conversion. Check an
1829 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001830 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1831 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001832 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001833 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001834 return true;
1835
1836 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00001837 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001838 }
1839 }
Mike Stump1eb44332009-09-09 15:08:12 +00001840 if (const ObjCObjectPointerType *FromPtrType =
John McCalldaa8e4e2010-11-15 09:13:47 +00001841 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001842 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001843 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001844 // Objective-C++ conversions are always okay.
1845 // FIXME: We should have a different class of conversions for the
1846 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001847 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001848 return false;
John McCalldaa8e4e2010-11-15 09:13:47 +00001849 }
Steve Naroff14108da2009-07-10 23:34:53 +00001850 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001851
1852 // We shouldn't fall into this case unless it's valid for other
1853 // reasons.
1854 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1855 Kind = CK_NullToPointer;
1856
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001857 return false;
1858}
1859
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001860/// IsMemberPointerConversion - Determines whether the conversion of the
1861/// expression From, which has the (possibly adjusted) type FromType, can be
1862/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1863/// If so, returns true and places the converted type (that might differ from
1864/// ToType in its cv-qualifiers at some level) into ConvertedType.
1865bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001866 QualType ToType,
1867 bool InOverloadResolution,
1868 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001869 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001870 if (!ToTypePtr)
1871 return false;
1872
1873 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001874 if (From->isNullPointerConstant(Context,
1875 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1876 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001877 ConvertedType = ToType;
1878 return true;
1879 }
1880
1881 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001882 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001883 if (!FromTypePtr)
1884 return false;
1885
1886 // A pointer to member of B can be converted to a pointer to member of D,
1887 // where D is derived from B (C++ 4.11p2).
1888 QualType FromClass(FromTypePtr->getClass(), 0);
1889 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001890
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00001891 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
1892 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
1893 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001894 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1895 ToClass.getTypePtr());
1896 return true;
1897 }
1898
1899 return false;
1900}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001901
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001902/// CheckMemberPointerConversion - Check the member pointer conversion from the
1903/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001904/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001905/// for which IsMemberPointerConversion has already returned true. It returns
1906/// true and produces a diagnostic if there was an error, or returns false
1907/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001908bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001909 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001910 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001911 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001912 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001913 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001914 if (!FromPtrType) {
1915 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001916 assert(From->isNullPointerConstant(Context,
1917 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001918 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00001919 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001920 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001921 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001922
Ted Kremenek6217b802009-07-29 21:53:49 +00001923 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001924 assert(ToPtrType && "No member pointer cast has a target type "
1925 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001926
Sebastian Redl21593ac2009-01-28 18:33:18 +00001927 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1928 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001929
Sebastian Redl21593ac2009-01-28 18:33:18 +00001930 // FIXME: What about dependent types?
1931 assert(FromClass->isRecordType() && "Pointer into non-class.");
1932 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001933
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001934 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001935 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001936 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1937 assert(DerivationOkay &&
1938 "Should not have been called if derivation isn't OK.");
1939 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001940
Sebastian Redl21593ac2009-01-28 18:33:18 +00001941 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1942 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001943 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1944 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1945 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1946 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001947 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001948
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001949 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001950 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1951 << FromClass << ToClass << QualType(VBase, 0)
1952 << From->getSourceRange();
1953 return true;
1954 }
1955
John McCall6b2accb2010-02-10 09:31:12 +00001956 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001957 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1958 Paths.front(),
1959 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001960
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001961 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001962 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001963 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001964 return false;
1965}
1966
Douglas Gregor98cd5992008-10-21 23:43:52 +00001967/// IsQualificationConversion - Determines whether the conversion from
1968/// an rvalue of type FromType to ToType is a qualification conversion
1969/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001970bool
1971Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001972 FromType = Context.getCanonicalType(FromType);
1973 ToType = Context.getCanonicalType(ToType);
1974
1975 // If FromType and ToType are the same type, this is not a
1976 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001977 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001978 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001979
Douglas Gregor98cd5992008-10-21 23:43:52 +00001980 // (C++ 4.4p4):
1981 // A conversion can add cv-qualifiers at levels other than the first
1982 // in multi-level pointers, subject to the following rules: [...]
1983 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001984 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001985 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001986 // Within each iteration of the loop, we check the qualifiers to
1987 // determine if this still looks like a qualification
1988 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001989 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001990 // until there are no more pointers or pointers-to-members left to
1991 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001992 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001993
1994 // -- for every j > 0, if const is in cv 1,j then const is in cv
1995 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001996 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001997 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001998
Douglas Gregor98cd5992008-10-21 23:43:52 +00001999 // -- if the cv 1,j and cv 2,j are different, then const is in
2000 // every cv for 0 < k < j.
2001 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002002 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002003 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Douglas Gregor98cd5992008-10-21 23:43:52 +00002005 // Keep track of whether all prior cv-qualifiers in the "to" type
2006 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002007 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00002008 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00002009 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002010
2011 // We are left with FromType and ToType being the pointee types
2012 // after unwrapping the original FromType and ToType the same number
2013 // of types. If we unwrapped any pointers, and if FromType and
2014 // ToType have the same unqualified type (since we checked
2015 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002016 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002017}
2018
Douglas Gregor734d9862009-01-30 23:27:23 +00002019/// Determines whether there is a user-defined conversion sequence
2020/// (C++ [over.ics.user]) that converts expression From to the type
2021/// ToType. If such a conversion exists, User will contain the
2022/// user-defined conversion sequence that performs such a conversion
2023/// and this routine will return true. Otherwise, this routine returns
2024/// false and User is unspecified.
2025///
Douglas Gregor734d9862009-01-30 23:27:23 +00002026/// \param AllowExplicit true if the conversion should consider C++0x
2027/// "explicit" conversion functions as well as non-explicit conversion
2028/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002029static OverloadingResult
2030IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2031 UserDefinedConversionSequence& User,
2032 OverloadCandidateSet& CandidateSet,
2033 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002034 // Whether we will only visit constructors.
2035 bool ConstructorsOnly = false;
2036
2037 // If the type we are conversion to is a class type, enumerate its
2038 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002039 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002040 // C++ [over.match.ctor]p1:
2041 // When objects of class type are direct-initialized (8.5), or
2042 // copy-initialized from an expression of the same or a
2043 // derived class type (8.5), overload resolution selects the
2044 // constructor. [...] For copy-initialization, the candidate
2045 // functions are all the converting constructors (12.3.1) of
2046 // that class. The argument list is the expression-list within
2047 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002048 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002049 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002050 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002051 ConstructorsOnly = true;
2052
John McCall120d63c2010-08-24 20:38:10 +00002053 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002054 // We're not going to find any constructors.
2055 } else if (CXXRecordDecl *ToRecordDecl
2056 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002057 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002058 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002059 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002060 NamedDecl *D = *Con;
2061 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2062
Douglas Gregordec06662009-08-21 18:42:58 +00002063 // Find the constructor (which may be a template).
2064 CXXConstructorDecl *Constructor = 0;
2065 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002066 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002067 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002068 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002069 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2070 else
John McCall9aa472c2010-03-19 07:35:19 +00002071 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002072
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00002073 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00002074 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00002075 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002076 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2077 /*ExplicitArgs*/ 0,
2078 &From, 1, CandidateSet,
2079 /*SuppressUserConversions=*/
2080 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002081 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002082 // Allow one user-defined conversion when user specifies a
2083 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002084 S.AddOverloadCandidate(Constructor, FoundDecl,
2085 &From, 1, CandidateSet,
2086 /*SuppressUserConversions=*/
2087 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002088 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002089 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002090 }
2091 }
2092
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002093 // Enumerate conversion functions, if we're allowed to.
2094 if (ConstructorsOnly) {
John McCall120d63c2010-08-24 20:38:10 +00002095 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2096 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002097 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002098 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002099 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002100 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002101 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2102 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002103 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002104 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002105 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002106 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002107 DeclAccessPair FoundDecl = I.getPair();
2108 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002109 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2110 if (isa<UsingShadowDecl>(D))
2111 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2112
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002113 CXXConversionDecl *Conv;
2114 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002115 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2116 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002117 else
John McCall32daa422010-03-31 01:36:47 +00002118 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002119
2120 if (AllowExplicit || !Conv->isExplicit()) {
2121 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002122 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2123 ActingContext, From, ToType,
2124 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002125 else
John McCall120d63c2010-08-24 20:38:10 +00002126 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2127 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002128 }
2129 }
2130 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002131 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002132
2133 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002134 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002135 case OR_Success:
2136 // Record the standard conversion we used and the conversion function.
2137 if (CXXConstructorDecl *Constructor
2138 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2139 // C++ [over.ics.user]p1:
2140 // If the user-defined conversion is specified by a
2141 // constructor (12.3.1), the initial standard conversion
2142 // sequence converts the source type to the type required by
2143 // the argument of the constructor.
2144 //
2145 QualType ThisType = Constructor->getThisType(S.Context);
2146 if (Best->Conversions[0].isEllipsis())
2147 User.EllipsisConversion = true;
2148 else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002149 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002150 User.EllipsisConversion = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002151 }
John McCall120d63c2010-08-24 20:38:10 +00002152 User.ConversionFunction = Constructor;
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002153 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall120d63c2010-08-24 20:38:10 +00002154 User.After.setAsIdentityConversion();
2155 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2156 User.After.setAllToTypes(ToType);
2157 return OR_Success;
2158 } else if (CXXConversionDecl *Conversion
2159 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2160 // C++ [over.ics.user]p1:
2161 //
2162 // [...] If the user-defined conversion is specified by a
2163 // conversion function (12.3.2), the initial standard
2164 // conversion sequence converts the source type to the
2165 // implicit object parameter of the conversion function.
2166 User.Before = Best->Conversions[0].Standard;
2167 User.ConversionFunction = Conversion;
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002168 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall120d63c2010-08-24 20:38:10 +00002169 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002170
John McCall120d63c2010-08-24 20:38:10 +00002171 // C++ [over.ics.user]p2:
2172 // The second standard conversion sequence converts the
2173 // result of the user-defined conversion to the target type
2174 // for the sequence. Since an implicit conversion sequence
2175 // is an initialization, the special rules for
2176 // initialization by user-defined conversion apply when
2177 // selecting the best user-defined conversion for a
2178 // user-defined conversion sequence (see 13.3.3 and
2179 // 13.3.3.1).
2180 User.After = Best->FinalConversion;
2181 return OR_Success;
2182 } else {
2183 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002184 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002185 }
2186
John McCall120d63c2010-08-24 20:38:10 +00002187 case OR_No_Viable_Function:
2188 return OR_No_Viable_Function;
2189 case OR_Deleted:
2190 // No conversion here! We're done.
2191 return OR_Deleted;
2192
2193 case OR_Ambiguous:
2194 return OR_Ambiguous;
2195 }
2196
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002197 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002198}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002199
2200bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002201Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002202 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002203 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002204 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00002205 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002206 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002207 if (OvResult == OR_Ambiguous)
2208 Diag(From->getSourceRange().getBegin(),
2209 diag::err_typecheck_ambiguous_condition)
2210 << From->getType() << ToType << From->getSourceRange();
2211 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2212 Diag(From->getSourceRange().getBegin(),
2213 diag::err_typecheck_nonviable_condition)
2214 << From->getType() << ToType << From->getSourceRange();
2215 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002216 return false;
John McCall120d63c2010-08-24 20:38:10 +00002217 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002218 return true;
2219}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002220
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002221/// CompareImplicitConversionSequences - Compare two implicit
2222/// conversion sequences to determine whether one is better than the
2223/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00002224static ImplicitConversionSequence::CompareKind
2225CompareImplicitConversionSequences(Sema &S,
2226 const ImplicitConversionSequence& ICS1,
2227 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002228{
2229 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2230 // conversion sequences (as defined in 13.3.3.1)
2231 // -- a standard conversion sequence (13.3.3.1.1) is a better
2232 // conversion sequence than a user-defined conversion sequence or
2233 // an ellipsis conversion sequence, and
2234 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2235 // conversion sequence than an ellipsis conversion sequence
2236 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002237 //
John McCall1d318332010-01-12 00:44:57 +00002238 // C++0x [over.best.ics]p10:
2239 // For the purpose of ranking implicit conversion sequences as
2240 // described in 13.3.3.2, the ambiguous conversion sequence is
2241 // treated as a user-defined sequence that is indistinguishable
2242 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002243 if (ICS1.getKindRank() < ICS2.getKindRank())
2244 return ImplicitConversionSequence::Better;
2245 else if (ICS2.getKindRank() < ICS1.getKindRank())
2246 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002247
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002248 // The following checks require both conversion sequences to be of
2249 // the same kind.
2250 if (ICS1.getKind() != ICS2.getKind())
2251 return ImplicitConversionSequence::Indistinguishable;
2252
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002253 // Two implicit conversion sequences of the same form are
2254 // indistinguishable conversion sequences unless one of the
2255 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002256 if (ICS1.isStandard())
John McCall120d63c2010-08-24 20:38:10 +00002257 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002258 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002259 // User-defined conversion sequence U1 is a better conversion
2260 // sequence than another user-defined conversion sequence U2 if
2261 // they contain the same user-defined conversion function or
2262 // constructor and if the second standard conversion sequence of
2263 // U1 is better than the second standard conversion sequence of
2264 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002265 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002266 ICS2.UserDefined.ConversionFunction)
John McCall120d63c2010-08-24 20:38:10 +00002267 return CompareStandardConversionSequences(S,
2268 ICS1.UserDefined.After,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002269 ICS2.UserDefined.After);
2270 }
2271
2272 return ImplicitConversionSequence::Indistinguishable;
2273}
2274
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002275static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2276 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2277 Qualifiers Quals;
2278 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2279 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2280 }
2281
2282 return Context.hasSameUnqualifiedType(T1, T2);
2283}
2284
Douglas Gregorad323a82010-01-27 03:51:04 +00002285// Per 13.3.3.2p3, compare the given standard conversion sequences to
2286// determine if one is a proper subset of the other.
2287static ImplicitConversionSequence::CompareKind
2288compareStandardConversionSubsets(ASTContext &Context,
2289 const StandardConversionSequence& SCS1,
2290 const StandardConversionSequence& SCS2) {
2291 ImplicitConversionSequence::CompareKind Result
2292 = ImplicitConversionSequence::Indistinguishable;
2293
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002294 // the identity conversion sequence is considered to be a subsequence of
2295 // any non-identity conversion sequence
2296 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2297 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2298 return ImplicitConversionSequence::Better;
2299 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2300 return ImplicitConversionSequence::Worse;
2301 }
2302
Douglas Gregorad323a82010-01-27 03:51:04 +00002303 if (SCS1.Second != SCS2.Second) {
2304 if (SCS1.Second == ICK_Identity)
2305 Result = ImplicitConversionSequence::Better;
2306 else if (SCS2.Second == ICK_Identity)
2307 Result = ImplicitConversionSequence::Worse;
2308 else
2309 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002310 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002311 return ImplicitConversionSequence::Indistinguishable;
2312
2313 if (SCS1.Third == SCS2.Third) {
2314 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2315 : ImplicitConversionSequence::Indistinguishable;
2316 }
2317
2318 if (SCS1.Third == ICK_Identity)
2319 return Result == ImplicitConversionSequence::Worse
2320 ? ImplicitConversionSequence::Indistinguishable
2321 : ImplicitConversionSequence::Better;
2322
2323 if (SCS2.Third == ICK_Identity)
2324 return Result == ImplicitConversionSequence::Better
2325 ? ImplicitConversionSequence::Indistinguishable
2326 : ImplicitConversionSequence::Worse;
2327
2328 return ImplicitConversionSequence::Indistinguishable;
2329}
2330
Douglas Gregor440a4832011-01-26 14:52:12 +00002331/// \brief Determine whether one of the given reference bindings is better
2332/// than the other based on what kind of bindings they are.
2333static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2334 const StandardConversionSequence &SCS2) {
2335 // C++0x [over.ics.rank]p3b4:
2336 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2337 // implicit object parameter of a non-static member function declared
2338 // without a ref-qualifier, and *either* S1 binds an rvalue reference
2339 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
2340 // lvalue reference to a function lvalue and S2 binds an rvalue
2341 // reference*.
2342 //
2343 // FIXME: Rvalue references. We're going rogue with the above edits,
2344 // because the semantics in the current C++0x working paper (N3225 at the
2345 // time of this writing) break the standard definition of std::forward
2346 // and std::reference_wrapper when dealing with references to functions.
2347 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00002348 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2349 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2350 return false;
2351
Douglas Gregor440a4832011-01-26 14:52:12 +00002352 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2353 SCS2.IsLvalueReference) ||
2354 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2355 !SCS2.IsLvalueReference);
2356}
2357
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002358/// CompareStandardConversionSequences - Compare two standard
2359/// conversion sequences to determine whether one is better than the
2360/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00002361static ImplicitConversionSequence::CompareKind
2362CompareStandardConversionSequences(Sema &S,
2363 const StandardConversionSequence& SCS1,
2364 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002365{
2366 // Standard conversion sequence S1 is a better conversion sequence
2367 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2368
2369 // -- S1 is a proper subsequence of S2 (comparing the conversion
2370 // sequences in the canonical form defined by 13.3.3.1.1,
2371 // excluding any Lvalue Transformation; the identity conversion
2372 // sequence is considered to be a subsequence of any
2373 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002374 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00002375 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00002376 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002377
2378 // -- the rank of S1 is better than the rank of S2 (by the rules
2379 // defined below), or, if not that,
2380 ImplicitConversionRank Rank1 = SCS1.getRank();
2381 ImplicitConversionRank Rank2 = SCS2.getRank();
2382 if (Rank1 < Rank2)
2383 return ImplicitConversionSequence::Better;
2384 else if (Rank2 < Rank1)
2385 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002386
Douglas Gregor57373262008-10-22 14:17:15 +00002387 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2388 // are indistinguishable unless one of the following rules
2389 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002390
Douglas Gregor57373262008-10-22 14:17:15 +00002391 // A conversion that is not a conversion of a pointer, or
2392 // pointer to member, to bool is better than another conversion
2393 // that is such a conversion.
2394 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2395 return SCS2.isPointerConversionToBool()
2396 ? ImplicitConversionSequence::Better
2397 : ImplicitConversionSequence::Worse;
2398
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002399 // C++ [over.ics.rank]p4b2:
2400 //
2401 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002402 // conversion of B* to A* is better than conversion of B* to
2403 // void*, and conversion of A* to void* is better than conversion
2404 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002405 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002406 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002407 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002408 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002409 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2410 // Exactly one of the conversion sequences is a conversion to
2411 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002412 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2413 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002414 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2415 // Neither conversion sequence converts to a void pointer; compare
2416 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002417 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00002418 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002419 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002420 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2421 // Both conversion sequences are conversions to void
2422 // pointers. Compare the source types to determine if there's an
2423 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002424 QualType FromType1 = SCS1.getFromType();
2425 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002426
2427 // Adjust the types we're converting from via the array-to-pointer
2428 // conversion, if we need to.
2429 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002430 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002431 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002432 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002433
Douglas Gregor01919692009-12-13 21:37:05 +00002434 QualType FromPointee1
2435 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2436 QualType FromPointee2
2437 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002438
John McCall120d63c2010-08-24 20:38:10 +00002439 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00002440 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002441 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00002442 return ImplicitConversionSequence::Worse;
2443
2444 // Objective-C++: If one interface is more specific than the
2445 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002446 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2447 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002448 if (FromIface1 && FromIface1) {
John McCall120d63c2010-08-24 20:38:10 +00002449 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor01919692009-12-13 21:37:05 +00002450 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002451 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor01919692009-12-13 21:37:05 +00002452 return ImplicitConversionSequence::Worse;
2453 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002454 }
Douglas Gregor57373262008-10-22 14:17:15 +00002455
2456 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2457 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002458 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00002459 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002460 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002461
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002462 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00002463 // Check for a better reference binding based on the kind of bindings.
2464 if (isBetterReferenceBindingKind(SCS1, SCS2))
2465 return ImplicitConversionSequence::Better;
2466 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2467 return ImplicitConversionSequence::Worse;
2468
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002469 // C++ [over.ics.rank]p3b4:
2470 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2471 // which the references refer are the same type except for
2472 // top-level cv-qualifiers, and the type to which the reference
2473 // initialized by S2 refers is more cv-qualified than the type
2474 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002475 QualType T1 = SCS1.getToType(2);
2476 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002477 T1 = S.Context.getCanonicalType(T1);
2478 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002479 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002480 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2481 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002482 if (UnqualT1 == UnqualT2) {
Chandler Carruth6df868e2010-12-12 08:17:55 +00002483 // If the type is an array type, promote the element qualifiers to the
2484 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002485 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002486 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002487 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002488 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002489 if (T2.isMoreQualifiedThan(T1))
2490 return ImplicitConversionSequence::Better;
2491 else if (T1.isMoreQualifiedThan(T2))
2492 return ImplicitConversionSequence::Worse;
2493 }
2494 }
Douglas Gregor57373262008-10-22 14:17:15 +00002495
2496 return ImplicitConversionSequence::Indistinguishable;
2497}
2498
2499/// CompareQualificationConversions - Compares two standard conversion
2500/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002501/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2502ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002503CompareQualificationConversions(Sema &S,
2504 const StandardConversionSequence& SCS1,
2505 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002506 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002507 // -- S1 and S2 differ only in their qualification conversion and
2508 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2509 // cv-qualification signature of type T1 is a proper subset of
2510 // the cv-qualification signature of type T2, and S1 is not the
2511 // deprecated string literal array-to-pointer conversion (4.2).
2512 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2513 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2514 return ImplicitConversionSequence::Indistinguishable;
2515
2516 // FIXME: the example in the standard doesn't use a qualification
2517 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002518 QualType T1 = SCS1.getToType(2);
2519 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002520 T1 = S.Context.getCanonicalType(T1);
2521 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002522 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002523 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2524 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002525
2526 // If the types are the same, we won't learn anything by unwrapped
2527 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002528 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002529 return ImplicitConversionSequence::Indistinguishable;
2530
Chandler Carruth28e318c2009-12-29 07:16:59 +00002531 // If the type is an array type, promote the element qualifiers to the type
2532 // for comparison.
2533 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002534 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002535 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002536 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002537
Mike Stump1eb44332009-09-09 15:08:12 +00002538 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002539 = ImplicitConversionSequence::Indistinguishable;
John McCall120d63c2010-08-24 20:38:10 +00002540 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002541 // Within each iteration of the loop, we check the qualifiers to
2542 // determine if this still looks like a qualification
2543 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002544 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002545 // until there are no more pointers or pointers-to-members left
2546 // to unwrap. This essentially mimics what
2547 // IsQualificationConversion does, but here we're checking for a
2548 // strict subset of qualifiers.
2549 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2550 // The qualifiers are the same, so this doesn't tell us anything
2551 // about how the sequences rank.
2552 ;
2553 else if (T2.isMoreQualifiedThan(T1)) {
2554 // T1 has fewer qualifiers, so it could be the better sequence.
2555 if (Result == ImplicitConversionSequence::Worse)
2556 // Neither has qualifiers that are a subset of the other's
2557 // qualifiers.
2558 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002559
Douglas Gregor57373262008-10-22 14:17:15 +00002560 Result = ImplicitConversionSequence::Better;
2561 } else if (T1.isMoreQualifiedThan(T2)) {
2562 // T2 has fewer qualifiers, so it could be the better sequence.
2563 if (Result == ImplicitConversionSequence::Better)
2564 // Neither has qualifiers that are a subset of the other's
2565 // qualifiers.
2566 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002567
Douglas Gregor57373262008-10-22 14:17:15 +00002568 Result = ImplicitConversionSequence::Worse;
2569 } else {
2570 // Qualifiers are disjoint.
2571 return ImplicitConversionSequence::Indistinguishable;
2572 }
2573
2574 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00002575 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002576 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002577 }
2578
Douglas Gregor57373262008-10-22 14:17:15 +00002579 // Check that the winning standard conversion sequence isn't using
2580 // the deprecated string literal array to pointer conversion.
2581 switch (Result) {
2582 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002583 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002584 Result = ImplicitConversionSequence::Indistinguishable;
2585 break;
2586
2587 case ImplicitConversionSequence::Indistinguishable:
2588 break;
2589
2590 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002591 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002592 Result = ImplicitConversionSequence::Indistinguishable;
2593 break;
2594 }
2595
2596 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002597}
2598
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002599/// CompareDerivedToBaseConversions - Compares two standard conversion
2600/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002601/// various kinds of derived-to-base conversions (C++
2602/// [over.ics.rank]p4b3). As part of these checks, we also look at
2603/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002604ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002605CompareDerivedToBaseConversions(Sema &S,
2606 const StandardConversionSequence& SCS1,
2607 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002608 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002609 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002610 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002611 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002612
2613 // Adjust the types we're converting from via the array-to-pointer
2614 // conversion, if we need to.
2615 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002616 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002617 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002618 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002619
2620 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00002621 FromType1 = S.Context.getCanonicalType(FromType1);
2622 ToType1 = S.Context.getCanonicalType(ToType1);
2623 FromType2 = S.Context.getCanonicalType(FromType2);
2624 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002625
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002626 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002627 //
2628 // If class B is derived directly or indirectly from class A and
2629 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002630 //
2631 // For Objective-C, we let A, B, and C also be Objective-C
2632 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002633
2634 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002635 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002636 SCS2.Second == ICK_Pointer_Conversion &&
2637 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2638 FromType1->isPointerType() && FromType2->isPointerType() &&
2639 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002640 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002641 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002642 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002643 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002644 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002645 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002646 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002647 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002648
John McCallc12c5bb2010-05-15 11:32:37 +00002649 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2650 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2651 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2652 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002653
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002654 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002655 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002656 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002657 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002658 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002659 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002660
2661 if (ToIface1 && ToIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002662 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002663 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002664 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002665 return ImplicitConversionSequence::Worse;
2666 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002667 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002668
2669 // -- conversion of B* to A* is better than conversion of C* to A*,
2670 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002671 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002672 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002673 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002674 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002675
Douglas Gregorcb7de522008-11-26 23:31:11 +00002676 if (FromIface1 && FromIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002677 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002678 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002679 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002680 return ImplicitConversionSequence::Worse;
2681 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002682 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002683 }
2684
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002685 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002686 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2687 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2688 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2689 const MemberPointerType * FromMemPointer1 =
2690 FromType1->getAs<MemberPointerType>();
2691 const MemberPointerType * ToMemPointer1 =
2692 ToType1->getAs<MemberPointerType>();
2693 const MemberPointerType * FromMemPointer2 =
2694 FromType2->getAs<MemberPointerType>();
2695 const MemberPointerType * ToMemPointer2 =
2696 ToType2->getAs<MemberPointerType>();
2697 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2698 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2699 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2700 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2701 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2702 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2703 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2704 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002705 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002706 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002707 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002708 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00002709 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002710 return ImplicitConversionSequence::Better;
2711 }
2712 // conversion of B::* to C::* is better than conversion of A::* to C::*
2713 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002714 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002715 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002716 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002717 return ImplicitConversionSequence::Worse;
2718 }
2719 }
2720
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002721 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002722 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002723 // -- binding of an expression of type C to a reference of type
2724 // B& is better than binding an expression of type C to a
2725 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002726 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2727 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2728 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002729 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002730 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002731 return ImplicitConversionSequence::Worse;
2732 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002733
Douglas Gregor225c41e2008-11-03 19:09:14 +00002734 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002735 // -- binding of an expression of type B to a reference of type
2736 // A& is better than binding an expression of type C to a
2737 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002738 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2739 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2740 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002741 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002742 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002743 return ImplicitConversionSequence::Worse;
2744 }
2745 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002746
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002747 return ImplicitConversionSequence::Indistinguishable;
2748}
2749
Douglas Gregorabe183d2010-04-13 16:31:36 +00002750/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2751/// determine whether they are reference-related,
2752/// reference-compatible, reference-compatible with added
2753/// qualification, or incompatible, for use in C++ initialization by
2754/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2755/// type, and the first type (T1) is the pointee type of the reference
2756/// type being initialized.
2757Sema::ReferenceCompareResult
2758Sema::CompareReferenceRelationship(SourceLocation Loc,
2759 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00002760 bool &DerivedToBase,
2761 bool &ObjCConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002762 assert(!OrigT1->isReferenceType() &&
2763 "T1 must be the pointee type of the reference type");
2764 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2765
2766 QualType T1 = Context.getCanonicalType(OrigT1);
2767 QualType T2 = Context.getCanonicalType(OrigT2);
2768 Qualifiers T1Quals, T2Quals;
2769 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2770 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2771
2772 // C++ [dcl.init.ref]p4:
2773 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2774 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2775 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00002776 DerivedToBase = false;
2777 ObjCConversion = false;
2778 if (UnqualT1 == UnqualT2) {
2779 // Nothing to do.
2780 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002781 IsDerivedFrom(UnqualT2, UnqualT1))
2782 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00002783 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2784 UnqualT2->isObjCObjectOrInterfaceType() &&
2785 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2786 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002787 else
2788 return Ref_Incompatible;
2789
2790 // At this point, we know that T1 and T2 are reference-related (at
2791 // least).
2792
2793 // If the type is an array type, promote the element qualifiers to the type
2794 // for comparison.
2795 if (isa<ArrayType>(T1) && T1Quals)
2796 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2797 if (isa<ArrayType>(T2) && T2Quals)
2798 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2799
2800 // C++ [dcl.init.ref]p4:
2801 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2802 // reference-related to T2 and cv1 is the same cv-qualification
2803 // as, or greater cv-qualification than, cv2. For purposes of
2804 // overload resolution, cases for which cv1 is greater
2805 // cv-qualification than cv2 are identified as
2806 // reference-compatible with added qualification (see 13.3.3.2).
2807 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2808 return Ref_Compatible;
2809 else if (T1.isMoreQualifiedThan(T2))
2810 return Ref_Compatible_With_Added_Qualification;
2811 else
2812 return Ref_Related;
2813}
2814
Douglas Gregor604eb652010-08-11 02:15:33 +00002815/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00002816/// with DeclType. Return true if something definite is found.
2817static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00002818FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2819 QualType DeclType, SourceLocation DeclLoc,
2820 Expr *Init, QualType T2, bool AllowRvalues,
2821 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002822 assert(T2->isRecordType() && "Can only find conversions of record types.");
2823 CXXRecordDecl *T2RecordDecl
2824 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2825
2826 OverloadCandidateSet CandidateSet(DeclLoc);
2827 const UnresolvedSetImpl *Conversions
2828 = T2RecordDecl->getVisibleConversionFunctions();
2829 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2830 E = Conversions->end(); I != E; ++I) {
2831 NamedDecl *D = *I;
2832 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2833 if (isa<UsingShadowDecl>(D))
2834 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2835
2836 FunctionTemplateDecl *ConvTemplate
2837 = dyn_cast<FunctionTemplateDecl>(D);
2838 CXXConversionDecl *Conv;
2839 if (ConvTemplate)
2840 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2841 else
2842 Conv = cast<CXXConversionDecl>(D);
2843
Douglas Gregor604eb652010-08-11 02:15:33 +00002844 // If this is an explicit conversion, and we're not allowed to consider
2845 // explicit conversions, skip it.
2846 if (!AllowExplicit && Conv->isExplicit())
2847 continue;
2848
2849 if (AllowRvalues) {
2850 bool DerivedToBase = false;
2851 bool ObjCConversion = false;
2852 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00002853 S.CompareReferenceRelationship(
2854 DeclLoc,
2855 Conv->getConversionType().getNonReferenceType()
2856 .getUnqualifiedType(),
2857 DeclType.getNonReferenceType().getUnqualifiedType(),
2858 DerivedToBase, ObjCConversion) ==
2859 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00002860 continue;
2861 } else {
2862 // If the conversion function doesn't return a reference type,
2863 // it can't be considered for this conversion. An rvalue reference
2864 // is only acceptable if its referencee is a function type.
2865
2866 const ReferenceType *RefType =
2867 Conv->getConversionType()->getAs<ReferenceType>();
2868 if (!RefType ||
2869 (!RefType->isLValueReferenceType() &&
2870 !RefType->getPointeeType()->isFunctionType()))
2871 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002872 }
Douglas Gregor604eb652010-08-11 02:15:33 +00002873
2874 if (ConvTemplate)
2875 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00002876 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00002877 else
2878 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00002879 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002880 }
2881
2882 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002883 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002884 case OR_Success:
2885 // C++ [over.ics.ref]p1:
2886 //
2887 // [...] If the parameter binds directly to the result of
2888 // applying a conversion function to the argument
2889 // expression, the implicit conversion sequence is a
2890 // user-defined conversion sequence (13.3.3.1.2), with the
2891 // second standard conversion sequence either an identity
2892 // conversion or, if the conversion function returns an
2893 // entity of a type that is a derived class of the parameter
2894 // type, a derived-to-base Conversion.
2895 if (!Best->FinalConversion.DirectBinding)
2896 return false;
2897
2898 ICS.setUserDefined();
2899 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2900 ICS.UserDefined.After = Best->FinalConversion;
2901 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002902 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002903 ICS.UserDefined.EllipsisConversion = false;
2904 assert(ICS.UserDefined.After.ReferenceBinding &&
2905 ICS.UserDefined.After.DirectBinding &&
2906 "Expected a direct reference binding!");
2907 return true;
2908
2909 case OR_Ambiguous:
2910 ICS.setAmbiguous();
2911 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2912 Cand != CandidateSet.end(); ++Cand)
2913 if (Cand->Viable)
2914 ICS.Ambiguous.addConversion(Cand->Function);
2915 return true;
2916
2917 case OR_No_Viable_Function:
2918 case OR_Deleted:
2919 // There was no suitable conversion, or we found a deleted
2920 // conversion; continue with other checks.
2921 return false;
2922 }
Eric Christopher1c3d5022010-06-30 18:36:32 +00002923
2924 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002925}
2926
Douglas Gregorabe183d2010-04-13 16:31:36 +00002927/// \brief Compute an implicit conversion sequence for reference
2928/// initialization.
2929static ImplicitConversionSequence
2930TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2931 SourceLocation DeclLoc,
2932 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002933 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002934 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2935
2936 // Most paths end in a failed conversion.
2937 ImplicitConversionSequence ICS;
2938 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2939
2940 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2941 QualType T2 = Init->getType();
2942
2943 // If the initializer is the address of an overloaded function, try
2944 // to resolve the overloaded function. If all goes well, T2 is the
2945 // type of the resulting function.
2946 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2947 DeclAccessPair Found;
2948 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2949 false, Found))
2950 T2 = Fn->getType();
2951 }
2952
2953 // Compute some basic properties of the types and the initializer.
2954 bool isRValRef = DeclType->isRValueReferenceType();
2955 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002956 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002957 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002958 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002959 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2960 ObjCConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002961
Douglas Gregorabe183d2010-04-13 16:31:36 +00002962
Sebastian Redl4680bf22010-06-30 18:13:39 +00002963 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00002964 // A reference to type "cv1 T1" is initialized by an expression
2965 // of type "cv2 T2" as follows:
2966
Sebastian Redl4680bf22010-06-30 18:13:39 +00002967 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00002968 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002969 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2970 // reference-compatible with "cv2 T2," or
2971 //
2972 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2973 if (InitCategory.isLValue() &&
2974 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002975 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00002976 // When a parameter of reference type binds directly (8.5.3)
2977 // to an argument expression, the implicit conversion sequence
2978 // is the identity conversion, unless the argument expression
2979 // has a type that is a derived class of the parameter type,
2980 // in which case the implicit conversion sequence is a
2981 // derived-to-base Conversion (13.3.3.1).
2982 ICS.setStandard();
2983 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00002984 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2985 : ObjCConversion? ICK_Compatible_Conversion
2986 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002987 ICS.Standard.Third = ICK_Identity;
2988 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2989 ICS.Standard.setToType(0, T2);
2990 ICS.Standard.setToType(1, T1);
2991 ICS.Standard.setToType(2, T1);
2992 ICS.Standard.ReferenceBinding = true;
2993 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00002994 ICS.Standard.IsLvalueReference = !isRValRef;
2995 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
2996 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00002997 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002998 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002999
Sebastian Redl4680bf22010-06-30 18:13:39 +00003000 // Nothing more to do: the inaccessibility/ambiguity check for
3001 // derived-to-base conversions is suppressed when we're
3002 // computing the implicit conversion sequence (C++
3003 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00003004 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003005 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00003006
Sebastian Redl4680bf22010-06-30 18:13:39 +00003007 // -- has a class type (i.e., T2 is a class type), where T1 is
3008 // not reference-related to T2, and can be implicitly
3009 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3010 // is reference-compatible with "cv3 T3" 92) (this
3011 // conversion is selected by enumerating the applicable
3012 // conversion functions (13.3.1.6) and choosing the best
3013 // one through overload resolution (13.3)),
3014 if (!SuppressUserConversions && T2->isRecordType() &&
3015 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3016 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00003017 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3018 Init, T2, /*AllowRvalues=*/false,
3019 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00003020 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003021 }
3022 }
3023
Sebastian Redl4680bf22010-06-30 18:13:39 +00003024 // -- Otherwise, the reference shall be an lvalue reference to a
3025 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003026 // shall be an rvalue reference.
Douglas Gregor66821b52010-04-18 09:22:00 +00003027 //
3028 // We actually handle one oddity of C++ [over.ics.ref] at this
3029 // point, which is that, due to p2 (which short-circuits reference
3030 // binding by only attempting a simple conversion for non-direct
3031 // bindings) and p3's strange wording, we allow a const volatile
3032 // reference to bind to an rvalue. Hence the check for the presence
3033 // of "const" rather than checking for "const" being the only
3034 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00003035 // This is also the point where rvalue references and lvalue inits no longer
3036 // go together.
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003037 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00003038 return ICS;
3039
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003040 // -- If the initializer expression
3041 //
3042 // -- is an xvalue, class prvalue, array prvalue or function
3043 // lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3044 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3045 (InitCategory.isXValue() ||
3046 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3047 (InitCategory.isLValue() && T2->isFunctionType()))) {
3048 ICS.setStandard();
3049 ICS.Standard.First = ICK_Identity;
3050 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3051 : ObjCConversion? ICK_Compatible_Conversion
3052 : ICK_Identity;
3053 ICS.Standard.Third = ICK_Identity;
3054 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3055 ICS.Standard.setToType(0, T2);
3056 ICS.Standard.setToType(1, T1);
3057 ICS.Standard.setToType(2, T1);
3058 ICS.Standard.ReferenceBinding = true;
3059 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3060 // binding unless we're binding to a class prvalue.
3061 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3062 // allow the use of rvalue references in C++98/03 for the benefit of
3063 // standard library implementors; therefore, we need the xvalue check here.
3064 ICS.Standard.DirectBinding =
3065 S.getLangOptions().CPlusPlus0x ||
3066 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00003067 ICS.Standard.IsLvalueReference = !isRValRef;
3068 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3069 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003070 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003071 ICS.Standard.CopyConstructor = 0;
3072 return ICS;
3073 }
3074
3075 // -- has a class type (i.e., T2 is a class type), where T1 is not
3076 // reference-related to T2, and can be implicitly converted to
3077 // an xvalue, class prvalue, or function lvalue of type
3078 // "cv3 T3", where "cv1 T1" is reference-compatible with
3079 // "cv3 T3",
3080 //
3081 // then the reference is bound to the value of the initializer
3082 // expression in the first case and to the result of the conversion
3083 // in the second case (or, in either case, to an appropriate base
3084 // class subobject).
3085 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3086 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
3087 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3088 Init, T2, /*AllowRvalues=*/true,
3089 AllowExplicit)) {
3090 // In the second case, if the reference is an rvalue reference
3091 // and the second standard conversion sequence of the
3092 // user-defined conversion sequence includes an lvalue-to-rvalue
3093 // conversion, the program is ill-formed.
3094 if (ICS.isUserDefined() && isRValRef &&
3095 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3096 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3097
Douglas Gregor68ed68b2011-01-21 16:36:05 +00003098 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00003099 }
Douglas Gregor68ed68b2011-01-21 16:36:05 +00003100
Douglas Gregorabe183d2010-04-13 16:31:36 +00003101 // -- Otherwise, a temporary of type "cv1 T1" is created and
3102 // initialized from the initializer expression using the
3103 // rules for a non-reference copy initialization (8.5). The
3104 // reference is then bound to the temporary. If T1 is
3105 // reference-related to T2, cv1 must be the same
3106 // cv-qualification as, or greater cv-qualification than,
3107 // cv2; otherwise, the program is ill-formed.
3108 if (RefRelationship == Sema::Ref_Related) {
3109 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3110 // we would be reference-compatible or reference-compatible with
3111 // added qualification. But that wasn't the case, so the reference
3112 // initialization fails.
3113 return ICS;
3114 }
3115
3116 // If at least one of the types is a class type, the types are not
3117 // related, and we aren't allowed any user conversions, the
3118 // reference binding fails. This case is important for breaking
3119 // recursion, since TryImplicitConversion below will attempt to
3120 // create a temporary through the use of a copy constructor.
3121 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3122 (T1->isRecordType() || T2->isRecordType()))
3123 return ICS;
3124
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003125 // If T1 is reference-related to T2 and the reference is an rvalue
3126 // reference, the initializer expression shall not be an lvalue.
3127 if (RefRelationship >= Sema::Ref_Related &&
3128 isRValRef && Init->Classify(S.Context).isLValue())
3129 return ICS;
3130
Douglas Gregorabe183d2010-04-13 16:31:36 +00003131 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00003132 // When a parameter of reference type is not bound directly to
3133 // an argument expression, the conversion sequence is the one
3134 // required to convert the argument expression to the
3135 // underlying type of the reference according to
3136 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3137 // to copy-initializing a temporary of the underlying type with
3138 // the argument expression. Any difference in top-level
3139 // cv-qualification is subsumed by the initialization itself
3140 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00003141 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3142 /*AllowExplicit=*/false,
3143 /*InOverloadResolution=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003144
3145 // Of course, that's still a reference binding.
3146 if (ICS.isStandard()) {
3147 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003148 ICS.Standard.IsLvalueReference = !isRValRef;
3149 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3150 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003151 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003152 } else if (ICS.isUserDefined()) {
3153 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003154 ICS.Standard.IsLvalueReference = !isRValRef;
3155 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3156 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003157 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003158 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003159
Douglas Gregorabe183d2010-04-13 16:31:36 +00003160 return ICS;
3161}
3162
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003163/// TryCopyInitialization - Try to copy-initialize a value of type
3164/// ToType from the expression From. Return the implicit conversion
3165/// sequence required to pass this argument, which may be a bad
3166/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00003167/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00003168/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00003169static ImplicitConversionSequence
3170TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00003171 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00003172 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003173 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00003174 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003175 /*FIXME:*/From->getLocStart(),
3176 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003177 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003178
John McCall120d63c2010-08-24 20:38:10 +00003179 return TryImplicitConversion(S, From, ToType,
3180 SuppressUserConversions,
3181 /*AllowExplicit=*/false,
3182 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003183}
3184
Douglas Gregor96176b32008-11-18 23:14:02 +00003185/// TryObjectArgumentInitialization - Try to initialize the object
3186/// parameter of the given member function (@c Method) from the
3187/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00003188static ImplicitConversionSequence
3189TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003190 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00003191 CXXMethodDecl *Method,
3192 CXXRecordDecl *ActingContext) {
3193 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003194 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3195 // const volatile object.
3196 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3197 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00003198 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00003199
3200 // Set up the conversion sequence as a "bad" conversion, to allow us
3201 // to exit early.
3202 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00003203
3204 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00003205 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003206 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003207 FromType = PT->getPointeeType();
3208
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003209 // When we had a pointer, it's implicitly dereferenced, so we
3210 // better have an lvalue.
3211 assert(FromClassification.isLValue());
3212 }
3213
Anders Carlssona552f7c2009-05-01 18:34:30 +00003214 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00003215
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003216 // C++0x [over.match.funcs]p4:
3217 // For non-static member functions, the type of the implicit object
3218 // parameter is
3219 //
3220 // — "lvalue reference to cv X" for functions declared without a
3221 // ref-qualifier or with the & ref-qualifier
3222 // — "rvalue reference to cv X" for functions declared with the &&
3223 // ref-qualifier
3224 //
3225 // where X is the class of which the function is a member and cv is the
3226 // cv-qualification on the member function declaration.
3227 //
3228 // However, when finding an implicit conversion sequence for the argument, we
3229 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00003230 // (C++ [over.match.funcs]p5). We perform a simplified version of
3231 // reference binding here, that allows class rvalues to bind to
3232 // non-constant references.
3233
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003234 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00003235 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00003236 if (ImplicitParamType.getCVRQualifiers()
3237 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00003238 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00003239 ICS.setBad(BadConversionSequence::bad_qualifiers,
3240 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003241 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003242 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003243
3244 // Check that we have either the same type or a derived type. It
3245 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00003246 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00003247 ImplicitConversionKind SecondKind;
3248 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3249 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00003250 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00003251 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00003252 else {
John McCallb1bdc622010-02-25 01:37:24 +00003253 ICS.setBad(BadConversionSequence::unrelated_class,
3254 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003255 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003256 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003257
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003258 // Check the ref-qualifier.
3259 switch (Method->getRefQualifier()) {
3260 case RQ_None:
3261 // Do nothing; we don't care about lvalueness or rvalueness.
3262 break;
3263
3264 case RQ_LValue:
3265 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3266 // non-const lvalue reference cannot bind to an rvalue
3267 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
3268 ImplicitParamType);
3269 return ICS;
3270 }
3271 break;
3272
3273 case RQ_RValue:
3274 if (!FromClassification.isRValue()) {
3275 // rvalue reference cannot bind to an lvalue
3276 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
3277 ImplicitParamType);
3278 return ICS;
3279 }
3280 break;
3281 }
3282
Douglas Gregor96176b32008-11-18 23:14:02 +00003283 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00003284 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003285 ICS.Standard.setAsIdentityConversion();
3286 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003287 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003288 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003289 ICS.Standard.ReferenceBinding = true;
3290 ICS.Standard.DirectBinding = true;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003291 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00003292 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003293 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3294 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3295 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00003296 return ICS;
3297}
3298
3299/// PerformObjectArgumentInitialization - Perform initialization of
3300/// the implicit object parameter for the given Method with the given
3301/// expression.
3302bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00003303Sema::PerformObjectArgumentInitialization(Expr *&From,
3304 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003305 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003306 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003307 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003308 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003309 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003310
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003311 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00003312 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003313 FromRecordType = PT->getPointeeType();
3314 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003315 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00003316 } else {
3317 FromRecordType = From->getType();
3318 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003319 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00003320 }
3321
John McCall701c89e2009-12-03 04:06:58 +00003322 // Note that we always use the true parent context when performing
3323 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003324 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003325 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3326 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003327 if (ICS.isBad()) {
3328 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3329 Qualifiers FromQs = FromRecordType.getQualifiers();
3330 Qualifiers ToQs = DestType.getQualifiers();
3331 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3332 if (CVR) {
3333 Diag(From->getSourceRange().getBegin(),
3334 diag::err_member_function_call_bad_cvr)
3335 << Method->getDeclName() << FromRecordType << (CVR - 1)
3336 << From->getSourceRange();
3337 Diag(Method->getLocation(), diag::note_previous_decl)
3338 << Method->getDeclName();
3339 return true;
3340 }
3341 }
3342
Douglas Gregor96176b32008-11-18 23:14:02 +00003343 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003344 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003345 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003346 }
Mike Stump1eb44332009-09-09 15:08:12 +00003347
Douglas Gregor5fccd362010-03-03 23:55:11 +00003348 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00003349 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00003350
Douglas Gregor5fccd362010-03-03 23:55:11 +00003351 if (!Context.hasSameType(From->getType(), DestType))
John McCall2de56d12010-08-25 11:45:40 +00003352 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall5baba9d2010-08-25 10:28:54 +00003353 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor96176b32008-11-18 23:14:02 +00003354 return false;
3355}
3356
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003357/// TryContextuallyConvertToBool - Attempt to contextually convert the
3358/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00003359static ImplicitConversionSequence
3360TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003361 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00003362 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003363 // FIXME: Are these flags correct?
3364 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003365 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00003366 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003367}
3368
3369/// PerformContextuallyConvertToBool - Perform a contextual conversion
3370/// of the expression From to bool (C++0x [conv]p3).
3371bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall120d63c2010-08-24 20:38:10 +00003372 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00003373 if (!ICS.isBad())
3374 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003375
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003376 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003377 return Diag(From->getSourceRange().getBegin(),
3378 diag::err_typecheck_bool_condition)
3379 << From->getType() << From->getSourceRange();
3380 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003381}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003382
3383/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3384/// expression From to 'id'.
John McCall120d63c2010-08-24 20:38:10 +00003385static ImplicitConversionSequence
3386TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3387 QualType Ty = S.Context.getObjCIdType();
3388 return TryImplicitConversion(S, From, Ty,
3389 // FIXME: Are these flags correct?
3390 /*SuppressUserConversions=*/false,
3391 /*AllowExplicit=*/true,
3392 /*InOverloadResolution=*/false);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003393}
John McCall120d63c2010-08-24 20:38:10 +00003394
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003395/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3396/// of the expression From to 'id'.
3397bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003398 QualType Ty = Context.getObjCIdType();
John McCall120d63c2010-08-24 20:38:10 +00003399 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003400 if (!ICS.isBad())
3401 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3402 return true;
3403}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003404
Douglas Gregorc30614b2010-06-29 23:17:37 +00003405/// \brief Attempt to convert the given expression to an integral or
3406/// enumeration type.
3407///
3408/// This routine will attempt to convert an expression of class type to an
3409/// integral or enumeration type, if that class type only has a single
3410/// conversion to an integral or enumeration type.
3411///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003412/// \param Loc The source location of the construct that requires the
3413/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003414///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003415/// \param FromE The expression we're converting from.
3416///
3417/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3418/// have integral or enumeration type.
3419///
3420/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3421/// incomplete class type.
3422///
3423/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3424/// explicit conversion function (because no implicit conversion functions
3425/// were available). This is a recovery mode.
3426///
3427/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3428/// showing which conversion was picked.
3429///
3430/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3431/// conversion function that could convert to integral or enumeration type.
3432///
3433/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3434/// usable conversion function.
3435///
3436/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3437/// function, which may be an extension in this case.
3438///
3439/// \returns The expression, converted to an integral or enumeration type if
3440/// successful.
John McCall60d7b3a2010-08-24 06:29:42 +00003441ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003442Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003443 const PartialDiagnostic &NotIntDiag,
3444 const PartialDiagnostic &IncompleteDiag,
3445 const PartialDiagnostic &ExplicitConvDiag,
3446 const PartialDiagnostic &ExplicitConvNote,
3447 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003448 const PartialDiagnostic &AmbigNote,
3449 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00003450 // We can't perform any more checking for type-dependent expressions.
3451 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00003452 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003453
3454 // If the expression already has integral or enumeration type, we're golden.
3455 QualType T = From->getType();
3456 if (T->isIntegralOrEnumerationType())
John McCall9ae2f072010-08-23 23:25:46 +00003457 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003458
3459 // FIXME: Check for missing '()' if T is a function type?
3460
3461 // If we don't have a class type in C++, there's no way we can get an
3462 // expression of integral or enumeration type.
3463 const RecordType *RecordTy = T->getAs<RecordType>();
3464 if (!RecordTy || !getLangOptions().CPlusPlus) {
3465 Diag(Loc, NotIntDiag)
3466 << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00003467 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003468 }
3469
3470 // We must have a complete class type.
3471 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00003472 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003473
3474 // Look for a conversion to an integral or enumeration type.
3475 UnresolvedSet<4> ViableConversions;
3476 UnresolvedSet<4> ExplicitConversions;
3477 const UnresolvedSetImpl *Conversions
3478 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3479
3480 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3481 E = Conversions->end();
3482 I != E;
3483 ++I) {
3484 if (CXXConversionDecl *Conversion
3485 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3486 if (Conversion->getConversionType().getNonReferenceType()
3487 ->isIntegralOrEnumerationType()) {
3488 if (Conversion->isExplicit())
3489 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3490 else
3491 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3492 }
3493 }
3494
3495 switch (ViableConversions.size()) {
3496 case 0:
3497 if (ExplicitConversions.size() == 1) {
3498 DeclAccessPair Found = ExplicitConversions[0];
3499 CXXConversionDecl *Conversion
3500 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3501
3502 // The user probably meant to invoke the given explicit
3503 // conversion; use it.
3504 QualType ConvTy
3505 = Conversion->getConversionType().getNonReferenceType();
3506 std::string TypeStr;
3507 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3508
3509 Diag(Loc, ExplicitConvDiag)
3510 << T << ConvTy
3511 << FixItHint::CreateInsertion(From->getLocStart(),
3512 "static_cast<" + TypeStr + ">(")
3513 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3514 ")");
3515 Diag(Conversion->getLocation(), ExplicitConvNote)
3516 << ConvTy->isEnumeralType() << ConvTy;
3517
3518 // If we aren't in a SFINAE context, build a call to the
3519 // explicit conversion function.
3520 if (isSFINAEContext())
3521 return ExprError();
3522
3523 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003524 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3525 if (Result.isInvalid())
3526 return ExprError();
3527
3528 From = Result.get();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003529 }
3530
3531 // We'll complain below about a non-integral condition type.
3532 break;
3533
3534 case 1: {
3535 // Apply this conversion.
3536 DeclAccessPair Found = ViableConversions[0];
3537 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003538
3539 CXXConversionDecl *Conversion
3540 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3541 QualType ConvTy
3542 = Conversion->getConversionType().getNonReferenceType();
3543 if (ConvDiag.getDiagID()) {
3544 if (isSFINAEContext())
3545 return ExprError();
3546
3547 Diag(Loc, ConvDiag)
3548 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3549 }
3550
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003551 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003552 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003553 if (Result.isInvalid())
3554 return ExprError();
3555
3556 From = Result.get();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003557 break;
3558 }
3559
3560 default:
3561 Diag(Loc, AmbigDiag)
3562 << T << From->getSourceRange();
3563 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3564 CXXConversionDecl *Conv
3565 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3566 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3567 Diag(Conv->getLocation(), AmbigNote)
3568 << ConvTy->isEnumeralType() << ConvTy;
3569 }
John McCall9ae2f072010-08-23 23:25:46 +00003570 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003571 }
3572
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003573 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00003574 Diag(Loc, NotIntDiag)
3575 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003576
John McCall9ae2f072010-08-23 23:25:46 +00003577 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003578}
3579
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003580/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003581/// candidate functions, using the given function call arguments. If
3582/// @p SuppressUserConversions, then don't allow user-defined
3583/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003584///
3585/// \para PartialOverloading true if we are performing "partial" overloading
3586/// based on an incomplete set of function arguments. This feature is used by
3587/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003588void
3589Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003590 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003591 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003592 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003593 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003594 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003595 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003596 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003597 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003598 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003599 "Use AddTemp∫lateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003600
Douglas Gregor88a35142008-12-22 05:46:06 +00003601 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003602 if (!isa<CXXConstructorDecl>(Method)) {
3603 // If we get here, it's because we're calling a member function
3604 // that is named without a member access expression (e.g.,
3605 // "this->f") that was either written explicitly or created
3606 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003607 // function, e.g., X::f(). We use an empty type for the implied
3608 // object argument (C++ [over.call.func]p3), and the acting context
3609 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003610 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003611 QualType(), Expr::Classification::makeSimpleLValue(),
3612 Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003613 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003614 return;
3615 }
3616 // We treat a constructor like a non-member function, since its object
3617 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003618 }
3619
Douglas Gregorfd476482009-11-13 23:59:09 +00003620 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003621 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003622
Douglas Gregor7edfb692009-11-23 12:27:39 +00003623 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003624 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003625
Douglas Gregor66724ea2009-11-14 01:20:54 +00003626 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3627 // C++ [class.copy]p3:
3628 // A member function template is never instantiated to perform the copy
3629 // of a class object to an object of its class type.
3630 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3631 if (NumArgs == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00003632 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003633 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3634 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003635 return;
3636 }
3637
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003638 // Add this candidate
3639 CandidateSet.push_back(OverloadCandidate());
3640 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003641 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003642 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003643 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003644 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003645 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00003646 Candidate.ExplicitCallArguments = NumArgs;
3647
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003648 unsigned NumArgsInProto = Proto->getNumArgs();
3649
3650 // (C++ 13.3.2p2): A candidate function having fewer than m
3651 // parameters is viable only if it has an ellipsis in its parameter
3652 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003653 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3654 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003655 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003656 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003657 return;
3658 }
3659
3660 // (C++ 13.3.2p2): A candidate function having more than m parameters
3661 // is viable only if the (m+1)st parameter has a default argument
3662 // (8.3.6). For the purposes of overload resolution, the
3663 // parameter list is truncated on the right, so that there are
3664 // exactly m parameters.
3665 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003666 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003667 // Not enough arguments.
3668 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003669 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003670 return;
3671 }
3672
3673 // Determine the implicit conversion sequences for each of the
3674 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003675 Candidate.Conversions.resize(NumArgs);
3676 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3677 if (ArgIdx < NumArgsInProto) {
3678 // (C++ 13.3.2p3): for F to be a viable function, there shall
3679 // exist for each argument an implicit conversion sequence
3680 // (13.3.3.1) that converts that argument to the corresponding
3681 // parameter of F.
3682 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003683 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003684 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003685 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003686 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003687 if (Candidate.Conversions[ArgIdx].isBad()) {
3688 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003689 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003690 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003691 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003692 } else {
3693 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3694 // argument for which there is no corresponding parameter is
3695 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003696 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003697 }
3698 }
3699}
3700
Douglas Gregor063daf62009-03-13 18:40:31 +00003701/// \brief Add all of the function declarations in the given function set to
3702/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003703void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003704 Expr **Args, unsigned NumArgs,
3705 OverloadCandidateSet& CandidateSet,
3706 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003707 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003708 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3709 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003710 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003711 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003712 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003713 Args[0]->getType(), Args[0]->Classify(Context),
3714 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003715 CandidateSet, SuppressUserConversions);
3716 else
John McCall9aa472c2010-03-19 07:35:19 +00003717 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003718 SuppressUserConversions);
3719 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003720 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003721 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3722 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003723 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003724 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003725 /*FIXME: explicit args */ 0,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003726 Args[0]->getType(),
3727 Args[0]->Classify(Context),
3728 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003729 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003730 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003731 else
John McCall9aa472c2010-03-19 07:35:19 +00003732 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003733 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003734 Args, NumArgs, CandidateSet,
3735 SuppressUserConversions);
3736 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003737 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003738}
3739
John McCall314be4e2009-11-17 07:50:12 +00003740/// AddMethodCandidate - Adds a named decl (which is some kind of
3741/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003742void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003743 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003744 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00003745 Expr **Args, unsigned NumArgs,
3746 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003747 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003748 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003749 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003750
3751 if (isa<UsingShadowDecl>(Decl))
3752 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3753
3754 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3755 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3756 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003757 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3758 /*ExplicitArgs*/ 0,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003759 ObjectType, ObjectClassification, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003760 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003761 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003762 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003763 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003764 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003765 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003766 }
3767}
3768
Douglas Gregor96176b32008-11-18 23:14:02 +00003769/// AddMethodCandidate - Adds the given C++ member function to the set
3770/// of candidate functions, using the given function call arguments
3771/// and the object argument (@c Object). For example, in a call
3772/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3773/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3774/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003775/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003776void
John McCall9aa472c2010-03-19 07:35:19 +00003777Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003778 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003779 Expr::Classification ObjectClassification,
John McCall86820f52010-01-26 01:37:31 +00003780 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003781 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003782 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003783 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003784 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003785 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003786 assert(!isa<CXXConstructorDecl>(Method) &&
3787 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003788
Douglas Gregor3f396022009-09-28 04:47:19 +00003789 if (!CandidateSet.isNewCandidate(Method))
3790 return;
3791
Douglas Gregor7edfb692009-11-23 12:27:39 +00003792 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003793 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003794
Douglas Gregor96176b32008-11-18 23:14:02 +00003795 // Add this candidate
3796 CandidateSet.push_back(OverloadCandidate());
3797 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003798 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003799 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003800 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003801 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00003802 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor96176b32008-11-18 23:14:02 +00003803
3804 unsigned NumArgsInProto = Proto->getNumArgs();
3805
3806 // (C++ 13.3.2p2): A candidate function having fewer than m
3807 // parameters is viable only if it has an ellipsis in its parameter
3808 // list (8.3.5).
3809 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3810 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003811 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003812 return;
3813 }
3814
3815 // (C++ 13.3.2p2): A candidate function having more than m parameters
3816 // is viable only if the (m+1)st parameter has a default argument
3817 // (8.3.6). For the purposes of overload resolution, the
3818 // parameter list is truncated on the right, so that there are
3819 // exactly m parameters.
3820 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3821 if (NumArgs < MinRequiredArgs) {
3822 // Not enough arguments.
3823 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003824 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003825 return;
3826 }
3827
3828 Candidate.Viable = true;
3829 Candidate.Conversions.resize(NumArgs + 1);
3830
John McCall701c89e2009-12-03 04:06:58 +00003831 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003832 // The implicit object argument is ignored.
3833 Candidate.IgnoreObjectArgument = true;
3834 else {
3835 // Determine the implicit conversion sequence for the object
3836 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003837 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003838 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
3839 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003840 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003841 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003842 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003843 return;
3844 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003845 }
3846
3847 // Determine the implicit conversion sequences for each of the
3848 // arguments.
3849 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3850 if (ArgIdx < NumArgsInProto) {
3851 // (C++ 13.3.2p3): for F to be a viable function, there shall
3852 // exist for each argument an implicit conversion sequence
3853 // (13.3.3.1) that converts that argument to the corresponding
3854 // parameter of F.
3855 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003856 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003857 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003858 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003859 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003860 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003861 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003862 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003863 break;
3864 }
3865 } else {
3866 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3867 // argument for which there is no corresponding parameter is
3868 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003869 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003870 }
3871 }
3872}
Douglas Gregora9333192010-05-08 17:41:32 +00003873
Douglas Gregor6b906862009-08-21 00:16:32 +00003874/// \brief Add a C++ member function template as a candidate to the candidate
3875/// set, using template argument deduction to produce an appropriate member
3876/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003877void
Douglas Gregor6b906862009-08-21 00:16:32 +00003878Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003879 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003880 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003881 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003882 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003883 Expr::Classification ObjectClassification,
John McCall701c89e2009-12-03 04:06:58 +00003884 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003885 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003886 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003887 if (!CandidateSet.isNewCandidate(MethodTmpl))
3888 return;
3889
Douglas Gregor6b906862009-08-21 00:16:32 +00003890 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003891 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003892 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003893 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003894 // candidate functions in the usual way.113) A given name can refer to one
3895 // or more function templates and also to a set of overloaded non-template
3896 // functions. In such a case, the candidate functions generated from each
3897 // function template are combined with the set of non-template candidate
3898 // functions.
John McCall5769d612010-02-08 23:07:23 +00003899 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003900 FunctionDecl *Specialization = 0;
3901 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003902 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003903 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003904 CandidateSet.push_back(OverloadCandidate());
3905 OverloadCandidate &Candidate = CandidateSet.back();
3906 Candidate.FoundDecl = FoundDecl;
3907 Candidate.Function = MethodTmpl->getTemplatedDecl();
3908 Candidate.Viable = false;
3909 Candidate.FailureKind = ovl_fail_bad_deduction;
3910 Candidate.IsSurrogate = false;
3911 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00003912 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003913 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3914 Info);
3915 return;
3916 }
Mike Stump1eb44332009-09-09 15:08:12 +00003917
Douglas Gregor6b906862009-08-21 00:16:32 +00003918 // Add the function template specialization produced by template argument
3919 // deduction as a candidate.
3920 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003921 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003922 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003923 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003924 ActingContext, ObjectType, ObjectClassification,
3925 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003926}
3927
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003928/// \brief Add a C++ function template specialization as a candidate
3929/// in the candidate set, using template argument deduction to produce
3930/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003931void
Douglas Gregore53060f2009-06-25 22:08:12 +00003932Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003933 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003934 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003935 Expr **Args, unsigned NumArgs,
3936 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003937 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003938 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3939 return;
3940
Douglas Gregore53060f2009-06-25 22:08:12 +00003941 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003942 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003943 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003944 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003945 // candidate functions in the usual way.113) A given name can refer to one
3946 // or more function templates and also to a set of overloaded non-template
3947 // functions. In such a case, the candidate functions generated from each
3948 // function template are combined with the set of non-template candidate
3949 // functions.
John McCall5769d612010-02-08 23:07:23 +00003950 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003951 FunctionDecl *Specialization = 0;
3952 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003953 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003954 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003955 CandidateSet.push_back(OverloadCandidate());
3956 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003957 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003958 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3959 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003960 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003961 Candidate.IsSurrogate = false;
3962 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00003963 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003964 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3965 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003966 return;
3967 }
Mike Stump1eb44332009-09-09 15:08:12 +00003968
Douglas Gregore53060f2009-06-25 22:08:12 +00003969 // Add the function template specialization produced by template argument
3970 // deduction as a candidate.
3971 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003972 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003973 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003974}
Mike Stump1eb44332009-09-09 15:08:12 +00003975
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003976/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003977/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003978/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003979/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003980/// (which may or may not be the same type as the type that the
3981/// conversion function produces).
3982void
3983Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003984 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003985 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003986 Expr *From, QualType ToType,
3987 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003988 assert(!Conversion->getDescribedFunctionTemplate() &&
3989 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003990 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003991 if (!CandidateSet.isNewCandidate(Conversion))
3992 return;
3993
Douglas Gregor7edfb692009-11-23 12:27:39 +00003994 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003995 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003996
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003997 // Add this candidate
3998 CandidateSet.push_back(OverloadCandidate());
3999 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004000 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004001 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004002 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004003 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004004 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004005 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004006 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004007 Candidate.Viable = true;
4008 Candidate.Conversions.resize(1);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004009 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004010
Douglas Gregorbca39322010-08-19 15:37:02 +00004011 // C++ [over.match.funcs]p4:
4012 // For conversion functions, the function is considered to be a member of
4013 // the class of the implicit implied object argument for the purpose of
4014 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004015 //
4016 // Determine the implicit conversion sequence for the implicit
4017 // object parameter.
4018 QualType ImplicitParamType = From->getType();
4019 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4020 ImplicitParamType = FromPtrType->getPointeeType();
4021 CXXRecordDecl *ConversionContext
4022 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
4023
4024 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004025 = TryObjectArgumentInitialization(*this, From->getType(),
4026 From->Classify(Context),
4027 Conversion, ConversionContext);
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004028
John McCall1d318332010-01-12 00:44:57 +00004029 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004030 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004031 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004032 return;
4033 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004034
Fariborz Jahanian3759a032009-10-19 19:18:20 +00004035 // We won't go through a user-define type conversion function to convert a
4036 // derived to base as such conversions are given Conversion Rank. They only
4037 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4038 QualType FromCanon
4039 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4040 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4041 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4042 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00004043 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00004044 return;
4045 }
4046
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004047 // To determine what the conversion from the result of calling the
4048 // conversion function to the type we're eventually trying to
4049 // convert to (ToType), we need to synthesize a call to the
4050 // conversion function and attempt copy initialization from it. This
4051 // makes sure that we get the right semantics with respect to
4052 // lvalues/rvalues and the type. Fortunately, we can allocate this
4053 // call on the stack and we don't need its arguments to be
4054 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00004055 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004056 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00004057 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4058 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00004059 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00004060 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00004061
Douglas Gregor7d14d382010-11-13 19:36:57 +00004062 QualType CallResultType
4063 = Conversion->getConversionType().getNonLValueExprType(Context);
4064 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4065 Candidate.Viable = false;
4066 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4067 return;
4068 }
4069
John McCallf89e55a2010-11-18 06:31:45 +00004070 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4071
Mike Stump1eb44332009-09-09 15:08:12 +00004072 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00004073 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4074 // allocator).
John McCallf89e55a2010-11-18 06:31:45 +00004075 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00004076 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00004077 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00004078 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004079 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004080 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004081
John McCall1d318332010-01-12 00:44:57 +00004082 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004083 case ImplicitConversionSequence::StandardConversion:
4084 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00004085
4086 // C++ [over.ics.user]p3:
4087 // If the user-defined conversion is specified by a specialization of a
4088 // conversion function template, the second standard conversion sequence
4089 // shall have exact match rank.
4090 if (Conversion->getPrimaryTemplate() &&
4091 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4092 Candidate.Viable = false;
4093 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4094 }
4095
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004096 // C++0x [dcl.init.ref]p5:
4097 // In the second case, if the reference is an rvalue reference and
4098 // the second standard conversion sequence of the user-defined
4099 // conversion sequence includes an lvalue-to-rvalue conversion, the
4100 // program is ill-formed.
4101 if (ToType->isRValueReferenceType() &&
4102 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4103 Candidate.Viable = false;
4104 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4105 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004106 break;
4107
4108 case ImplicitConversionSequence::BadConversion:
4109 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00004110 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004111 break;
4112
4113 default:
Mike Stump1eb44332009-09-09 15:08:12 +00004114 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004115 "Can only end up with a standard conversion sequence or failure");
4116 }
4117}
4118
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004119/// \brief Adds a conversion function template specialization
4120/// candidate to the overload set, using template argument deduction
4121/// to deduce the template arguments of the conversion function
4122/// template from the type that we are converting to (C++
4123/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00004124void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004125Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00004126 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004127 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004128 Expr *From, QualType ToType,
4129 OverloadCandidateSet &CandidateSet) {
4130 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4131 "Only conversion function templates permitted here");
4132
Douglas Gregor3f396022009-09-28 04:47:19 +00004133 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4134 return;
4135
John McCall5769d612010-02-08 23:07:23 +00004136 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004137 CXXConversionDecl *Specialization = 0;
4138 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00004139 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004140 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00004141 CandidateSet.push_back(OverloadCandidate());
4142 OverloadCandidate &Candidate = CandidateSet.back();
4143 Candidate.FoundDecl = FoundDecl;
4144 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4145 Candidate.Viable = false;
4146 Candidate.FailureKind = ovl_fail_bad_deduction;
4147 Candidate.IsSurrogate = false;
4148 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004149 Candidate.ExplicitCallArguments = 1;
Douglas Gregorff5adac2010-05-08 20:18:54 +00004150 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4151 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004152 return;
4153 }
Mike Stump1eb44332009-09-09 15:08:12 +00004154
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004155 // Add the conversion function template specialization produced by
4156 // template argument deduction as a candidate.
4157 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00004158 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00004159 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004160}
4161
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004162/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4163/// converts the given @c Object to a function pointer via the
4164/// conversion function @c Conversion, and then attempts to call it
4165/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4166/// the type of function that we'll eventually be calling.
4167void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00004168 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004169 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00004170 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004171 Expr *Object,
John McCall701c89e2009-12-03 04:06:58 +00004172 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004173 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004174 if (!CandidateSet.isNewCandidate(Conversion))
4175 return;
4176
Douglas Gregor7edfb692009-11-23 12:27:39 +00004177 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004178 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004179
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004180 CandidateSet.push_back(OverloadCandidate());
4181 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004182 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004183 Candidate.Function = 0;
4184 Candidate.Surrogate = Conversion;
4185 Candidate.Viable = true;
4186 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004187 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004188 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004189 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004190
4191 // Determine the implicit conversion sequence for the implicit
4192 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004193 ImplicitConversionSequence ObjectInit
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004194 = TryObjectArgumentInitialization(*this, Object->getType(),
4195 Object->Classify(Context),
4196 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00004197 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004198 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004199 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00004200 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004201 return;
4202 }
4203
4204 // The first conversion is actually a user-defined conversion whose
4205 // first conversion is ObjectInit's standard conversion (which is
4206 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00004207 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004208 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004209 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004210 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Douglas Gregor83eecbe2011-01-20 01:32:05 +00004211 Candidate.Conversions[0].UserDefined.FoundConversionFunction
4212 = FoundDecl.getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004213 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004214 = Candidate.Conversions[0].UserDefined.Before;
4215 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4216
Mike Stump1eb44332009-09-09 15:08:12 +00004217 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004218 unsigned NumArgsInProto = Proto->getNumArgs();
4219
4220 // (C++ 13.3.2p2): A candidate function having fewer than m
4221 // parameters is viable only if it has an ellipsis in its parameter
4222 // list (8.3.5).
4223 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4224 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004225 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004226 return;
4227 }
4228
4229 // Function types don't have any default arguments, so just check if
4230 // we have enough arguments.
4231 if (NumArgs < NumArgsInProto) {
4232 // Not enough arguments.
4233 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004234 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004235 return;
4236 }
4237
4238 // Determine the implicit conversion sequences for each of the
4239 // arguments.
4240 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4241 if (ArgIdx < NumArgsInProto) {
4242 // (C++ 13.3.2p3): for F to be a viable function, there shall
4243 // exist for each argument an implicit conversion sequence
4244 // (13.3.3.1) that converts that argument to the corresponding
4245 // parameter of F.
4246 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004247 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004248 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004249 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004250 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00004251 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004252 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004253 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004254 break;
4255 }
4256 } else {
4257 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4258 // argument for which there is no corresponding parameter is
4259 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004260 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004261 }
4262 }
4263}
4264
Douglas Gregor063daf62009-03-13 18:40:31 +00004265/// \brief Add overload candidates for overloaded operators that are
4266/// member functions.
4267///
4268/// Add the overloaded operator candidates that are member functions
4269/// for the operator Op that was used in an operator expression such
4270/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4271/// CandidateSet will store the added overload candidates. (C++
4272/// [over.match.oper]).
4273void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4274 SourceLocation OpLoc,
4275 Expr **Args, unsigned NumArgs,
4276 OverloadCandidateSet& CandidateSet,
4277 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004278 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4279
4280 // C++ [over.match.oper]p3:
4281 // For a unary operator @ with an operand of a type whose
4282 // cv-unqualified version is T1, and for a binary operator @ with
4283 // a left operand of a type whose cv-unqualified version is T1 and
4284 // a right operand of a type whose cv-unqualified version is T2,
4285 // three sets of candidate functions, designated member
4286 // candidates, non-member candidates and built-in candidates, are
4287 // constructed as follows:
4288 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00004289
4290 // -- If T1 is a class type, the set of member candidates is the
4291 // result of the qualified lookup of T1::operator@
4292 // (13.3.1.1.1); otherwise, the set of member candidates is
4293 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00004294 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004295 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004296 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004297 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004298
John McCalla24dc2e2009-11-17 02:14:36 +00004299 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4300 LookupQualifiedName(Operators, T1Rec->getDecl());
4301 Operators.suppressDiagnostics();
4302
Mike Stump1eb44332009-09-09 15:08:12 +00004303 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004304 OperEnd = Operators.end();
4305 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00004306 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00004307 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004308 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
4309 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00004310 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00004311 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004312}
4313
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004314/// AddBuiltinCandidate - Add a candidate for a built-in
4315/// operator. ResultTy and ParamTys are the result and parameter types
4316/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004317/// arguments being passed to the candidate. IsAssignmentOperator
4318/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004319/// operator. NumContextualBoolArguments is the number of arguments
4320/// (at the beginning of the argument list) that will be contextually
4321/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00004322void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004323 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004324 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004325 bool IsAssignmentOperator,
4326 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00004327 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004328 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004329
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004330 // Add this candidate
4331 CandidateSet.push_back(OverloadCandidate());
4332 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004333 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004334 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004335 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004336 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004337 Candidate.BuiltinTypes.ResultTy = ResultTy;
4338 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4339 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4340
4341 // Determine the implicit conversion sequences for each of the
4342 // arguments.
4343 Candidate.Viable = true;
4344 Candidate.Conversions.resize(NumArgs);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004345 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004346 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004347 // C++ [over.match.oper]p4:
4348 // For the built-in assignment operators, conversions of the
4349 // left operand are restricted as follows:
4350 // -- no temporaries are introduced to hold the left operand, and
4351 // -- no user-defined conversions are applied to the left
4352 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00004353 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004354 //
4355 // We block these conversions by turning off user-defined
4356 // conversions, since that is the only way that initialization of
4357 // a reference to a non-class type can occur from something that
4358 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004359 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004360 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004361 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00004362 Candidate.Conversions[ArgIdx]
4363 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004364 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004365 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004366 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004367 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004368 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004369 }
John McCall1d318332010-01-12 00:44:57 +00004370 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004371 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004372 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004373 break;
4374 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004375 }
4376}
4377
4378/// BuiltinCandidateTypeSet - A set of types that will be used for the
4379/// candidate operator functions for built-in operators (C++
4380/// [over.built]). The types are separated into pointer types and
4381/// enumeration types.
4382class BuiltinCandidateTypeSet {
4383 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004384 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004385
4386 /// PointerTypes - The set of pointer types that will be used in the
4387 /// built-in candidates.
4388 TypeSet PointerTypes;
4389
Sebastian Redl78eb8742009-04-19 21:53:20 +00004390 /// MemberPointerTypes - The set of member pointer types that will be
4391 /// used in the built-in candidates.
4392 TypeSet MemberPointerTypes;
4393
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004394 /// EnumerationTypes - The set of enumeration types that will be
4395 /// used in the built-in candidates.
4396 TypeSet EnumerationTypes;
4397
Douglas Gregor26bcf672010-05-19 03:21:00 +00004398 /// \brief The set of vector types that will be used in the built-in
4399 /// candidates.
4400 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00004401
4402 /// \brief A flag indicating non-record types are viable candidates
4403 bool HasNonRecordTypes;
4404
4405 /// \brief A flag indicating whether either arithmetic or enumeration types
4406 /// were present in the candidate set.
4407 bool HasArithmeticOrEnumeralTypes;
4408
Douglas Gregor5842ba92009-08-24 15:23:48 +00004409 /// Sema - The semantic analysis instance where we are building the
4410 /// candidate type set.
4411 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004412
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004413 /// Context - The AST context in which we will build the type sets.
4414 ASTContext &Context;
4415
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004416 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4417 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00004418 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004419
4420public:
4421 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004422 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004423
Mike Stump1eb44332009-09-09 15:08:12 +00004424 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00004425 : HasNonRecordTypes(false),
4426 HasArithmeticOrEnumeralTypes(false),
4427 SemaRef(SemaRef),
4428 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004429
Douglas Gregor573d9c32009-10-21 23:19:44 +00004430 void AddTypesConvertedFrom(QualType Ty,
4431 SourceLocation Loc,
4432 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004433 bool AllowExplicitConversions,
4434 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004435
4436 /// pointer_begin - First pointer type found;
4437 iterator pointer_begin() { return PointerTypes.begin(); }
4438
Sebastian Redl78eb8742009-04-19 21:53:20 +00004439 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004440 iterator pointer_end() { return PointerTypes.end(); }
4441
Sebastian Redl78eb8742009-04-19 21:53:20 +00004442 /// member_pointer_begin - First member pointer type found;
4443 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4444
4445 /// member_pointer_end - Past the last member pointer type found;
4446 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4447
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004448 /// enumeration_begin - First enumeration type found;
4449 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4450
Sebastian Redl78eb8742009-04-19 21:53:20 +00004451 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004452 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004453
4454 iterator vector_begin() { return VectorTypes.begin(); }
4455 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00004456
4457 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4458 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004459};
4460
Sebastian Redl78eb8742009-04-19 21:53:20 +00004461/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004462/// the set of pointer types along with any more-qualified variants of
4463/// that type. For example, if @p Ty is "int const *", this routine
4464/// will add "int const *", "int const volatile *", "int const
4465/// restrict *", and "int const volatile restrict *" to the set of
4466/// pointer types. Returns true if the add of @p Ty itself succeeded,
4467/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004468///
4469/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004470bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00004471BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4472 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00004473
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004474 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004475 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004476 return false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004477
4478 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00004479 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004480 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004481 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004482 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004483 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004484 buildObjCPtr = true;
4485 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004486 else
4487 assert(false && "type was not a pointer type!");
4488 }
4489 else
4490 PointeeTy = PointerTy->getPointeeType();
4491
Sebastian Redla9efada2009-11-18 20:39:26 +00004492 // Don't add qualified variants of arrays. For one, they're not allowed
4493 // (the qualifier would sink to the element type), and for another, the
4494 // only overload situation where it matters is subscript or pointer +- int,
4495 // and those shouldn't have qualifier variants anyway.
4496 if (PointeeTy->isArrayType())
4497 return true;
John McCall0953e762009-09-24 19:53:00 +00004498 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00004499 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00004500 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004501 bool hasVolatile = VisibleQuals.hasVolatile();
4502 bool hasRestrict = VisibleQuals.hasRestrict();
4503
John McCall0953e762009-09-24 19:53:00 +00004504 // Iterate through all strict supersets of BaseCVR.
4505 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4506 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004507 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4508 // in the types.
4509 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4510 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00004511 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004512 if (!buildObjCPtr)
4513 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4514 else
4515 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004516 }
4517
4518 return true;
4519}
4520
Sebastian Redl78eb8742009-04-19 21:53:20 +00004521/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4522/// to the set of pointer types along with any more-qualified variants of
4523/// that type. For example, if @p Ty is "int const *", this routine
4524/// will add "int const *", "int const volatile *", "int const
4525/// restrict *", and "int const volatile restrict *" to the set of
4526/// pointer types. Returns true if the add of @p Ty itself succeeded,
4527/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004528///
4529/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004530bool
4531BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4532 QualType Ty) {
4533 // Insert this type.
4534 if (!MemberPointerTypes.insert(Ty))
4535 return false;
4536
John McCall0953e762009-09-24 19:53:00 +00004537 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4538 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00004539
John McCall0953e762009-09-24 19:53:00 +00004540 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004541 // Don't add qualified variants of arrays. For one, they're not allowed
4542 // (the qualifier would sink to the element type), and for another, the
4543 // only overload situation where it matters is subscript or pointer +- int,
4544 // and those shouldn't have qualifier variants anyway.
4545 if (PointeeTy->isArrayType())
4546 return true;
John McCall0953e762009-09-24 19:53:00 +00004547 const Type *ClassTy = PointerTy->getClass();
4548
4549 // Iterate through all strict supersets of the pointee type's CVR
4550 // qualifiers.
4551 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4552 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4553 if ((CVR | BaseCVR) != CVR) continue;
4554
4555 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00004556 MemberPointerTypes.insert(
4557 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00004558 }
4559
4560 return true;
4561}
4562
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004563/// AddTypesConvertedFrom - Add each of the types to which the type @p
4564/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00004565/// primarily interested in pointer types and enumeration types. We also
4566/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004567/// AllowUserConversions is true if we should look at the conversion
4568/// functions of a class type, and AllowExplicitConversions if we
4569/// should also include the explicit conversion functions of a class
4570/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004571void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004572BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004573 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004574 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004575 bool AllowExplicitConversions,
4576 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004577 // Only deal with canonical types.
4578 Ty = Context.getCanonicalType(Ty);
4579
4580 // Look through reference types; they aren't part of the type of an
4581 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004582 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004583 Ty = RefTy->getPointeeType();
4584
John McCall3b657512011-01-19 10:06:00 +00004585 // If we're dealing with an array type, decay to the pointer.
4586 if (Ty->isArrayType())
4587 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4588
4589 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004590 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004591
Chandler Carruth6a577462010-12-13 01:44:01 +00004592 // Flag if we ever add a non-record type.
4593 const RecordType *TyRec = Ty->getAs<RecordType>();
4594 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4595
Chandler Carruth6a577462010-12-13 01:44:01 +00004596 // Flag if we encounter an arithmetic type.
4597 HasArithmeticOrEnumeralTypes =
4598 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4599
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004600 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4601 PointerTypes.insert(Ty);
4602 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004603 // Insert our type, and its more-qualified variants, into the set
4604 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004605 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004606 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00004607 } else if (Ty->isMemberPointerType()) {
4608 // Member pointers are far easier, since the pointee can't be converted.
4609 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4610 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004611 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00004612 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00004613 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004614 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00004615 // We treat vector types as arithmetic types in many contexts as an
4616 // extension.
4617 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00004618 VectorTypes.insert(Ty);
Chandler Carruth6a577462010-12-13 01:44:01 +00004619 } else if (AllowUserConversions && TyRec) {
4620 // No conversion functions in incomplete types.
4621 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4622 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004623
Chandler Carruth6a577462010-12-13 01:44:01 +00004624 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4625 const UnresolvedSetImpl *Conversions
4626 = ClassDecl->getVisibleConversionFunctions();
4627 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4628 E = Conversions->end(); I != E; ++I) {
4629 NamedDecl *D = I.getDecl();
4630 if (isa<UsingShadowDecl>(D))
4631 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004632
Chandler Carruth6a577462010-12-13 01:44:01 +00004633 // Skip conversion function templates; they don't tell us anything
4634 // about which builtin types we can convert to.
4635 if (isa<FunctionTemplateDecl>(D))
4636 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004637
Chandler Carruth6a577462010-12-13 01:44:01 +00004638 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4639 if (AllowExplicitConversions || !Conv->isExplicit()) {
4640 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4641 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004642 }
4643 }
4644 }
4645}
4646
Douglas Gregor19b7b152009-08-24 13:43:27 +00004647/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4648/// the volatile- and non-volatile-qualified assignment operators for the
4649/// given type to the candidate set.
4650static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4651 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004652 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004653 unsigned NumArgs,
4654 OverloadCandidateSet &CandidateSet) {
4655 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004656
Douglas Gregor19b7b152009-08-24 13:43:27 +00004657 // T& operator=(T&, T)
4658 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4659 ParamTypes[1] = T;
4660 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4661 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004662
Douglas Gregor19b7b152009-08-24 13:43:27 +00004663 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4664 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004665 ParamTypes[0]
4666 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004667 ParamTypes[1] = T;
4668 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004669 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004670 }
4671}
Mike Stump1eb44332009-09-09 15:08:12 +00004672
Sebastian Redl9994a342009-10-25 17:03:50 +00004673/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4674/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004675static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4676 Qualifiers VRQuals;
4677 const RecordType *TyRec;
4678 if (const MemberPointerType *RHSMPType =
4679 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004680 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004681 else
4682 TyRec = ArgExpr->getType()->getAs<RecordType>();
4683 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004684 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004685 VRQuals.addVolatile();
4686 VRQuals.addRestrict();
4687 return VRQuals;
4688 }
4689
4690 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004691 if (!ClassDecl->hasDefinition())
4692 return VRQuals;
4693
John McCalleec51cf2010-01-20 00:46:10 +00004694 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004695 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004696
John McCalleec51cf2010-01-20 00:46:10 +00004697 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004698 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004699 NamedDecl *D = I.getDecl();
4700 if (isa<UsingShadowDecl>(D))
4701 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4702 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004703 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4704 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4705 CanTy = ResTypeRef->getPointeeType();
4706 // Need to go down the pointer/mempointer chain and add qualifiers
4707 // as see them.
4708 bool done = false;
4709 while (!done) {
4710 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4711 CanTy = ResTypePtr->getPointeeType();
4712 else if (const MemberPointerType *ResTypeMPtr =
4713 CanTy->getAs<MemberPointerType>())
4714 CanTy = ResTypeMPtr->getPointeeType();
4715 else
4716 done = true;
4717 if (CanTy.isVolatileQualified())
4718 VRQuals.addVolatile();
4719 if (CanTy.isRestrictQualified())
4720 VRQuals.addRestrict();
4721 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4722 return VRQuals;
4723 }
4724 }
4725 }
4726 return VRQuals;
4727}
John McCall00071ec2010-11-13 05:51:15 +00004728
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004729namespace {
John McCall00071ec2010-11-13 05:51:15 +00004730
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004731/// \brief Helper class to manage the addition of builtin operator overload
4732/// candidates. It provides shared state and utility methods used throughout
4733/// the process, as well as a helper method to add each group of builtin
4734/// operator overloads from the standard to a candidate set.
4735class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00004736 // Common instance state available to all overload candidate addition methods.
4737 Sema &S;
4738 Expr **Args;
4739 unsigned NumArgs;
4740 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00004741 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruth6d695582010-12-12 10:35:00 +00004742 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4743 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004744
Chandler Carruth6d695582010-12-12 10:35:00 +00004745 // Define some constants used to index and iterate over the arithemetic types
4746 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00004747 // The "promoted arithmetic types" are the arithmetic
4748 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00004749 static const unsigned FirstIntegralType = 3;
4750 static const unsigned LastIntegralType = 18;
4751 static const unsigned FirstPromotedIntegralType = 3,
4752 LastPromotedIntegralType = 9;
4753 static const unsigned FirstPromotedArithmeticType = 0,
4754 LastPromotedArithmeticType = 9;
4755 static const unsigned NumArithmeticTypes = 18;
4756
Chandler Carruth6d695582010-12-12 10:35:00 +00004757 /// \brief Get the canonical type for a given arithmetic type index.
4758 CanQualType getArithmeticType(unsigned index) {
4759 assert(index < NumArithmeticTypes);
4760 static CanQualType ASTContext::* const
4761 ArithmeticTypes[NumArithmeticTypes] = {
4762 // Start of promoted types.
4763 &ASTContext::FloatTy,
4764 &ASTContext::DoubleTy,
4765 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00004766
Chandler Carruth6d695582010-12-12 10:35:00 +00004767 // Start of integral types.
4768 &ASTContext::IntTy,
4769 &ASTContext::LongTy,
4770 &ASTContext::LongLongTy,
4771 &ASTContext::UnsignedIntTy,
4772 &ASTContext::UnsignedLongTy,
4773 &ASTContext::UnsignedLongLongTy,
4774 // End of promoted types.
4775
4776 &ASTContext::BoolTy,
4777 &ASTContext::CharTy,
4778 &ASTContext::WCharTy,
4779 &ASTContext::Char16Ty,
4780 &ASTContext::Char32Ty,
4781 &ASTContext::SignedCharTy,
4782 &ASTContext::ShortTy,
4783 &ASTContext::UnsignedCharTy,
4784 &ASTContext::UnsignedShortTy,
4785 // End of integral types.
4786 // FIXME: What about complex?
4787 };
4788 return S.Context.*ArithmeticTypes[index];
4789 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004790
Chandler Carruth38ca8d12010-12-12 09:59:53 +00004791 /// \brief Gets the canonical type resulting from the usual arithemetic
4792 /// converions for the given arithmetic types.
4793 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
4794 // Accelerator table for performing the usual arithmetic conversions.
4795 // The rules are basically:
4796 // - if either is floating-point, use the wider floating-point
4797 // - if same signedness, use the higher rank
4798 // - if same size, use unsigned of the higher rank
4799 // - use the larger type
4800 // These rules, together with the axiom that higher ranks are
4801 // never smaller, are sufficient to precompute all of these results
4802 // *except* when dealing with signed types of higher rank.
4803 // (we could precompute SLL x UI for all known platforms, but it's
4804 // better not to make any assumptions).
4805 enum PromotedType {
4806 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
4807 };
4808 static PromotedType ConversionsTable[LastPromotedArithmeticType]
4809 [LastPromotedArithmeticType] = {
4810 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4811 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4812 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4813 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4814 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4815 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4816 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4817 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4818 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
4819 };
4820
4821 assert(L < LastPromotedArithmeticType);
4822 assert(R < LastPromotedArithmeticType);
4823 int Idx = ConversionsTable[L][R];
4824
4825 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00004826 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00004827
4828 // Slow path: we need to compare widths.
4829 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00004830 CanQualType LT = getArithmeticType(L),
4831 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00004832 unsigned LW = S.Context.getIntWidth(LT),
4833 RW = S.Context.getIntWidth(RT);
4834
4835 // If they're different widths, use the signed type.
4836 if (LW > RW) return LT;
4837 else if (LW < RW) return RT;
4838
4839 // Otherwise, use the unsigned type of the signed type's rank.
4840 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
4841 assert(L == SLL || R == SLL);
4842 return S.Context.UnsignedLongLongTy;
4843 }
4844
Chandler Carruth3c69dc42010-12-12 09:22:45 +00004845 /// \brief Helper method to factor out the common pattern of adding overloads
4846 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004847 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
4848 bool HasVolatile) {
4849 QualType ParamTypes[2] = {
4850 S.Context.getLValueReferenceType(CandidateTy),
4851 S.Context.IntTy
4852 };
4853
4854 // Non-volatile version.
4855 if (NumArgs == 1)
4856 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4857 else
4858 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4859
4860 // Use a heuristic to reduce number of builtin candidates in the set:
4861 // add volatile version only if there are conversions to a volatile type.
4862 if (HasVolatile) {
4863 ParamTypes[0] =
4864 S.Context.getLValueReferenceType(
4865 S.Context.getVolatileType(CandidateTy));
4866 if (NumArgs == 1)
4867 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4868 else
4869 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4870 }
4871 }
4872
4873public:
4874 BuiltinOperatorOverloadBuilder(
4875 Sema &S, Expr **Args, unsigned NumArgs,
4876 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00004877 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004878 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
4879 OverloadCandidateSet &CandidateSet)
4880 : S(S), Args(Args), NumArgs(NumArgs),
4881 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00004882 HasArithmeticOrEnumeralCandidateType(
4883 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004884 CandidateTypes(CandidateTypes),
4885 CandidateSet(CandidateSet) {
4886 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00004887 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004888 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00004889 assert(getArithmeticType(LastPromotedIntegralType - 1)
4890 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004891 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00004892 assert(getArithmeticType(FirstPromotedArithmeticType)
4893 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004894 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00004895 assert(getArithmeticType(LastPromotedArithmeticType - 1)
4896 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004897 "Invalid last promoted arithmetic type");
4898 }
4899
4900 // C++ [over.built]p3:
4901 //
4902 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4903 // is either volatile or empty, there exist candidate operator
4904 // functions of the form
4905 //
4906 // VQ T& operator++(VQ T&);
4907 // T operator++(VQ T&, int);
4908 //
4909 // C++ [over.built]p4:
4910 //
4911 // For every pair (T, VQ), where T is an arithmetic type other
4912 // than bool, and VQ is either volatile or empty, there exist
4913 // candidate operator functions of the form
4914 //
4915 // VQ T& operator--(VQ T&);
4916 // T operator--(VQ T&, int);
4917 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00004918 if (!HasArithmeticOrEnumeralCandidateType)
4919 return;
4920
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004921 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
4922 Arith < NumArithmeticTypes; ++Arith) {
4923 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00004924 getArithmeticType(Arith),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004925 VisibleTypeConversionsQuals.hasVolatile());
4926 }
4927 }
4928
4929 // C++ [over.built]p5:
4930 //
4931 // For every pair (T, VQ), where T is a cv-qualified or
4932 // cv-unqualified object type, and VQ is either volatile or
4933 // empty, there exist candidate operator functions of the form
4934 //
4935 // T*VQ& operator++(T*VQ&);
4936 // T*VQ& operator--(T*VQ&);
4937 // T* operator++(T*VQ&, int);
4938 // T* operator--(T*VQ&, int);
4939 void addPlusPlusMinusMinusPointerOverloads() {
4940 for (BuiltinCandidateTypeSet::iterator
4941 Ptr = CandidateTypes[0].pointer_begin(),
4942 PtrEnd = CandidateTypes[0].pointer_end();
4943 Ptr != PtrEnd; ++Ptr) {
4944 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00004945 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004946 continue;
4947
4948 addPlusPlusMinusMinusStyleOverloads(*Ptr,
4949 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4950 VisibleTypeConversionsQuals.hasVolatile()));
4951 }
4952 }
4953
4954 // C++ [over.built]p6:
4955 // For every cv-qualified or cv-unqualified object type T, there
4956 // exist candidate operator functions of the form
4957 //
4958 // T& operator*(T*);
4959 //
4960 // C++ [over.built]p7:
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004961 // For every function type T that does not have cv-qualifiers or a
4962 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004963 // T& operator*(T*);
4964 void addUnaryStarPointerOverloads() {
4965 for (BuiltinCandidateTypeSet::iterator
4966 Ptr = CandidateTypes[0].pointer_begin(),
4967 PtrEnd = CandidateTypes[0].pointer_end();
4968 Ptr != PtrEnd; ++Ptr) {
4969 QualType ParamTy = *Ptr;
4970 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00004971 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
4972 continue;
4973
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004974 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
4975 if (Proto->getTypeQuals() || Proto->getRefQualifier())
4976 continue;
4977
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004978 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
4979 &ParamTy, Args, 1, CandidateSet);
4980 }
4981 }
4982
4983 // C++ [over.built]p9:
4984 // For every promoted arithmetic type T, there exist candidate
4985 // operator functions of the form
4986 //
4987 // T operator+(T);
4988 // T operator-(T);
4989 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00004990 if (!HasArithmeticOrEnumeralCandidateType)
4991 return;
4992
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004993 for (unsigned Arith = FirstPromotedArithmeticType;
4994 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00004995 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004996 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4997 }
4998
4999 // Extension: We also add these operators for vector types.
5000 for (BuiltinCandidateTypeSet::iterator
5001 Vec = CandidateTypes[0].vector_begin(),
5002 VecEnd = CandidateTypes[0].vector_end();
5003 Vec != VecEnd; ++Vec) {
5004 QualType VecTy = *Vec;
5005 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5006 }
5007 }
5008
5009 // C++ [over.built]p8:
5010 // For every type T, there exist candidate operator functions of
5011 // the form
5012 //
5013 // T* operator+(T*);
5014 void addUnaryPlusPointerOverloads() {
5015 for (BuiltinCandidateTypeSet::iterator
5016 Ptr = CandidateTypes[0].pointer_begin(),
5017 PtrEnd = CandidateTypes[0].pointer_end();
5018 Ptr != PtrEnd; ++Ptr) {
5019 QualType ParamTy = *Ptr;
5020 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5021 }
5022 }
5023
5024 // C++ [over.built]p10:
5025 // For every promoted integral type T, there exist candidate
5026 // operator functions of the form
5027 //
5028 // T operator~(T);
5029 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00005030 if (!HasArithmeticOrEnumeralCandidateType)
5031 return;
5032
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005033 for (unsigned Int = FirstPromotedIntegralType;
5034 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005035 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005036 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5037 }
5038
5039 // Extension: We also add this operator for vector types.
5040 for (BuiltinCandidateTypeSet::iterator
5041 Vec = CandidateTypes[0].vector_begin(),
5042 VecEnd = CandidateTypes[0].vector_end();
5043 Vec != VecEnd; ++Vec) {
5044 QualType VecTy = *Vec;
5045 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5046 }
5047 }
5048
5049 // C++ [over.match.oper]p16:
5050 // For every pointer to member type T, there exist candidate operator
5051 // functions of the form
5052 //
5053 // bool operator==(T,T);
5054 // bool operator!=(T,T);
5055 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5056 /// Set of (canonical) types that we've already handled.
5057 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5058
5059 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5060 for (BuiltinCandidateTypeSet::iterator
5061 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5062 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5063 MemPtr != MemPtrEnd;
5064 ++MemPtr) {
5065 // Don't add the same builtin candidate twice.
5066 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5067 continue;
5068
5069 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5070 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5071 CandidateSet);
5072 }
5073 }
5074 }
5075
5076 // C++ [over.built]p15:
5077 //
5078 // For every pointer or enumeration type T, there exist
5079 // candidate operator functions of the form
5080 //
5081 // bool operator<(T, T);
5082 // bool operator>(T, T);
5083 // bool operator<=(T, T);
5084 // bool operator>=(T, T);
5085 // bool operator==(T, T);
5086 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005087 void addRelationalPointerOrEnumeralOverloads() {
5088 // C++ [over.built]p1:
5089 // If there is a user-written candidate with the same name and parameter
5090 // types as a built-in candidate operator function, the built-in operator
5091 // function is hidden and is not included in the set of candidate
5092 // functions.
5093 //
5094 // The text is actually in a note, but if we don't implement it then we end
5095 // up with ambiguities when the user provides an overloaded operator for
5096 // an enumeration type. Note that only enumeration types have this problem,
5097 // so we track which enumeration types we've seen operators for. Also, the
5098 // only other overloaded operator with enumeration argumenst, operator=,
5099 // cannot be overloaded for enumeration types, so this is the only place
5100 // where we must suppress candidates like this.
5101 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5102 UserDefinedBinaryOperators;
5103
5104 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5105 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5106 CandidateTypes[ArgIdx].enumeration_end()) {
5107 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5108 CEnd = CandidateSet.end();
5109 C != CEnd; ++C) {
5110 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5111 continue;
5112
5113 QualType FirstParamType =
5114 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5115 QualType SecondParamType =
5116 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5117
5118 // Skip if either parameter isn't of enumeral type.
5119 if (!FirstParamType->isEnumeralType() ||
5120 !SecondParamType->isEnumeralType())
5121 continue;
5122
5123 // Add this operator to the set of known user-defined operators.
5124 UserDefinedBinaryOperators.insert(
5125 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5126 S.Context.getCanonicalType(SecondParamType)));
5127 }
5128 }
5129 }
5130
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005131 /// Set of (canonical) types that we've already handled.
5132 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5133
5134 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5135 for (BuiltinCandidateTypeSet::iterator
5136 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5137 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5138 Ptr != PtrEnd; ++Ptr) {
5139 // Don't add the same builtin candidate twice.
5140 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5141 continue;
5142
5143 QualType ParamTypes[2] = { *Ptr, *Ptr };
5144 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5145 CandidateSet);
5146 }
5147 for (BuiltinCandidateTypeSet::iterator
5148 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5149 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5150 Enum != EnumEnd; ++Enum) {
5151 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5152
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005153 // Don't add the same builtin candidate twice, or if a user defined
5154 // candidate exists.
5155 if (!AddedTypes.insert(CanonType) ||
5156 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5157 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005158 continue;
5159
5160 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005161 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5162 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005163 }
5164 }
5165 }
5166
5167 // C++ [over.built]p13:
5168 //
5169 // For every cv-qualified or cv-unqualified object type T
5170 // there exist candidate operator functions of the form
5171 //
5172 // T* operator+(T*, ptrdiff_t);
5173 // T& operator[](T*, ptrdiff_t); [BELOW]
5174 // T* operator-(T*, ptrdiff_t);
5175 // T* operator+(ptrdiff_t, T*);
5176 // T& operator[](ptrdiff_t, T*); [BELOW]
5177 //
5178 // C++ [over.built]p14:
5179 //
5180 // For every T, where T is a pointer to object type, there
5181 // exist candidate operator functions of the form
5182 //
5183 // ptrdiff_t operator-(T, T);
5184 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5185 /// Set of (canonical) types that we've already handled.
5186 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5187
5188 for (int Arg = 0; Arg < 2; ++Arg) {
5189 QualType AsymetricParamTypes[2] = {
5190 S.Context.getPointerDiffType(),
5191 S.Context.getPointerDiffType(),
5192 };
5193 for (BuiltinCandidateTypeSet::iterator
5194 Ptr = CandidateTypes[Arg].pointer_begin(),
5195 PtrEnd = CandidateTypes[Arg].pointer_end();
5196 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005197 QualType PointeeTy = (*Ptr)->getPointeeType();
5198 if (!PointeeTy->isObjectType())
5199 continue;
5200
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005201 AsymetricParamTypes[Arg] = *Ptr;
5202 if (Arg == 0 || Op == OO_Plus) {
5203 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5204 // T* operator+(ptrdiff_t, T*);
5205 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5206 CandidateSet);
5207 }
5208 if (Op == OO_Minus) {
5209 // ptrdiff_t operator-(T, T);
5210 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5211 continue;
5212
5213 QualType ParamTypes[2] = { *Ptr, *Ptr };
5214 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5215 Args, 2, CandidateSet);
5216 }
5217 }
5218 }
5219 }
5220
5221 // C++ [over.built]p12:
5222 //
5223 // For every pair of promoted arithmetic types L and R, there
5224 // exist candidate operator functions of the form
5225 //
5226 // LR operator*(L, R);
5227 // LR operator/(L, R);
5228 // LR operator+(L, R);
5229 // LR operator-(L, R);
5230 // bool operator<(L, R);
5231 // bool operator>(L, R);
5232 // bool operator<=(L, R);
5233 // bool operator>=(L, R);
5234 // bool operator==(L, R);
5235 // bool operator!=(L, R);
5236 //
5237 // where LR is the result of the usual arithmetic conversions
5238 // between types L and R.
5239 //
5240 // C++ [over.built]p24:
5241 //
5242 // For every pair of promoted arithmetic types L and R, there exist
5243 // candidate operator functions of the form
5244 //
5245 // LR operator?(bool, L, R);
5246 //
5247 // where LR is the result of the usual arithmetic conversions
5248 // between types L and R.
5249 // Our candidates ignore the first parameter.
5250 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005251 if (!HasArithmeticOrEnumeralCandidateType)
5252 return;
5253
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005254 for (unsigned Left = FirstPromotedArithmeticType;
5255 Left < LastPromotedArithmeticType; ++Left) {
5256 for (unsigned Right = FirstPromotedArithmeticType;
5257 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005258 QualType LandR[2] = { getArithmeticType(Left),
5259 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005260 QualType Result =
5261 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005262 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005263 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5264 }
5265 }
5266
5267 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5268 // conditional operator for vector types.
5269 for (BuiltinCandidateTypeSet::iterator
5270 Vec1 = CandidateTypes[0].vector_begin(),
5271 Vec1End = CandidateTypes[0].vector_end();
5272 Vec1 != Vec1End; ++Vec1) {
5273 for (BuiltinCandidateTypeSet::iterator
5274 Vec2 = CandidateTypes[1].vector_begin(),
5275 Vec2End = CandidateTypes[1].vector_end();
5276 Vec2 != Vec2End; ++Vec2) {
5277 QualType LandR[2] = { *Vec1, *Vec2 };
5278 QualType Result = S.Context.BoolTy;
5279 if (!isComparison) {
5280 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5281 Result = *Vec1;
5282 else
5283 Result = *Vec2;
5284 }
5285
5286 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5287 }
5288 }
5289 }
5290
5291 // C++ [over.built]p17:
5292 //
5293 // For every pair of promoted integral types L and R, there
5294 // exist candidate operator functions of the form
5295 //
5296 // LR operator%(L, R);
5297 // LR operator&(L, R);
5298 // LR operator^(L, R);
5299 // LR operator|(L, R);
5300 // L operator<<(L, R);
5301 // L operator>>(L, R);
5302 //
5303 // where LR is the result of the usual arithmetic conversions
5304 // between types L and R.
5305 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005306 if (!HasArithmeticOrEnumeralCandidateType)
5307 return;
5308
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005309 for (unsigned Left = FirstPromotedIntegralType;
5310 Left < LastPromotedIntegralType; ++Left) {
5311 for (unsigned Right = FirstPromotedIntegralType;
5312 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005313 QualType LandR[2] = { getArithmeticType(Left),
5314 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005315 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5316 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005317 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005318 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5319 }
5320 }
5321 }
5322
5323 // C++ [over.built]p20:
5324 //
5325 // For every pair (T, VQ), where T is an enumeration or
5326 // pointer to member type and VQ is either volatile or
5327 // empty, there exist candidate operator functions of the form
5328 //
5329 // VQ T& operator=(VQ T&, T);
5330 void addAssignmentMemberPointerOrEnumeralOverloads() {
5331 /// Set of (canonical) types that we've already handled.
5332 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5333
5334 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5335 for (BuiltinCandidateTypeSet::iterator
5336 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5337 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5338 Enum != EnumEnd; ++Enum) {
5339 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5340 continue;
5341
5342 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5343 CandidateSet);
5344 }
5345
5346 for (BuiltinCandidateTypeSet::iterator
5347 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5348 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5349 MemPtr != MemPtrEnd; ++MemPtr) {
5350 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5351 continue;
5352
5353 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5354 CandidateSet);
5355 }
5356 }
5357 }
5358
5359 // C++ [over.built]p19:
5360 //
5361 // For every pair (T, VQ), where T is any type and VQ is either
5362 // volatile or empty, there exist candidate operator functions
5363 // of the form
5364 //
5365 // T*VQ& operator=(T*VQ&, T*);
5366 //
5367 // C++ [over.built]p21:
5368 //
5369 // For every pair (T, VQ), where T is a cv-qualified or
5370 // cv-unqualified object type and VQ is either volatile or
5371 // empty, there exist candidate operator functions of the form
5372 //
5373 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5374 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5375 void addAssignmentPointerOverloads(bool isEqualOp) {
5376 /// Set of (canonical) types that we've already handled.
5377 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5378
5379 for (BuiltinCandidateTypeSet::iterator
5380 Ptr = CandidateTypes[0].pointer_begin(),
5381 PtrEnd = CandidateTypes[0].pointer_end();
5382 Ptr != PtrEnd; ++Ptr) {
5383 // If this is operator=, keep track of the builtin candidates we added.
5384 if (isEqualOp)
5385 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005386 else if (!(*Ptr)->getPointeeType()->isObjectType())
5387 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005388
5389 // non-volatile version
5390 QualType ParamTypes[2] = {
5391 S.Context.getLValueReferenceType(*Ptr),
5392 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5393 };
5394 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5395 /*IsAssigmentOperator=*/ isEqualOp);
5396
5397 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5398 VisibleTypeConversionsQuals.hasVolatile()) {
5399 // volatile version
5400 ParamTypes[0] =
5401 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5402 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5403 /*IsAssigmentOperator=*/isEqualOp);
5404 }
5405 }
5406
5407 if (isEqualOp) {
5408 for (BuiltinCandidateTypeSet::iterator
5409 Ptr = CandidateTypes[1].pointer_begin(),
5410 PtrEnd = CandidateTypes[1].pointer_end();
5411 Ptr != PtrEnd; ++Ptr) {
5412 // Make sure we don't add the same candidate twice.
5413 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5414 continue;
5415
Chandler Carruth6df868e2010-12-12 08:17:55 +00005416 QualType ParamTypes[2] = {
5417 S.Context.getLValueReferenceType(*Ptr),
5418 *Ptr,
5419 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005420
5421 // non-volatile version
5422 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5423 /*IsAssigmentOperator=*/true);
5424
5425 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5426 VisibleTypeConversionsQuals.hasVolatile()) {
5427 // volatile version
5428 ParamTypes[0] =
5429 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00005430 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5431 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005432 }
5433 }
5434 }
5435 }
5436
5437 // C++ [over.built]p18:
5438 //
5439 // For every triple (L, VQ, R), where L is an arithmetic type,
5440 // VQ is either volatile or empty, and R is a promoted
5441 // arithmetic type, there exist candidate operator functions of
5442 // the form
5443 //
5444 // VQ L& operator=(VQ L&, R);
5445 // VQ L& operator*=(VQ L&, R);
5446 // VQ L& operator/=(VQ L&, R);
5447 // VQ L& operator+=(VQ L&, R);
5448 // VQ L& operator-=(VQ L&, R);
5449 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005450 if (!HasArithmeticOrEnumeralCandidateType)
5451 return;
5452
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005453 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5454 for (unsigned Right = FirstPromotedArithmeticType;
5455 Right < LastPromotedArithmeticType; ++Right) {
5456 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00005457 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005458
5459 // Add this built-in operator as a candidate (VQ is empty).
5460 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00005461 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005462 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5463 /*IsAssigmentOperator=*/isEqualOp);
5464
5465 // Add this built-in operator as a candidate (VQ is 'volatile').
5466 if (VisibleTypeConversionsQuals.hasVolatile()) {
5467 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00005468 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005469 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00005470 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5471 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005472 /*IsAssigmentOperator=*/isEqualOp);
5473 }
5474 }
5475 }
5476
5477 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5478 for (BuiltinCandidateTypeSet::iterator
5479 Vec1 = CandidateTypes[0].vector_begin(),
5480 Vec1End = CandidateTypes[0].vector_end();
5481 Vec1 != Vec1End; ++Vec1) {
5482 for (BuiltinCandidateTypeSet::iterator
5483 Vec2 = CandidateTypes[1].vector_begin(),
5484 Vec2End = CandidateTypes[1].vector_end();
5485 Vec2 != Vec2End; ++Vec2) {
5486 QualType ParamTypes[2];
5487 ParamTypes[1] = *Vec2;
5488 // Add this built-in operator as a candidate (VQ is empty).
5489 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5490 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5491 /*IsAssigmentOperator=*/isEqualOp);
5492
5493 // Add this built-in operator as a candidate (VQ is 'volatile').
5494 if (VisibleTypeConversionsQuals.hasVolatile()) {
5495 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5496 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00005497 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5498 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005499 /*IsAssigmentOperator=*/isEqualOp);
5500 }
5501 }
5502 }
5503 }
5504
5505 // C++ [over.built]p22:
5506 //
5507 // For every triple (L, VQ, R), where L is an integral type, VQ
5508 // is either volatile or empty, and R is a promoted integral
5509 // type, there exist candidate operator functions of the form
5510 //
5511 // VQ L& operator%=(VQ L&, R);
5512 // VQ L& operator<<=(VQ L&, R);
5513 // VQ L& operator>>=(VQ L&, R);
5514 // VQ L& operator&=(VQ L&, R);
5515 // VQ L& operator^=(VQ L&, R);
5516 // VQ L& operator|=(VQ L&, R);
5517 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00005518 if (!HasArithmeticOrEnumeralCandidateType)
5519 return;
5520
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005521 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5522 for (unsigned Right = FirstPromotedIntegralType;
5523 Right < LastPromotedIntegralType; ++Right) {
5524 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00005525 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005526
5527 // Add this built-in operator as a candidate (VQ is empty).
5528 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00005529 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005530 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5531 if (VisibleTypeConversionsQuals.hasVolatile()) {
5532 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00005533 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005534 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5535 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5536 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5537 CandidateSet);
5538 }
5539 }
5540 }
5541 }
5542
5543 // C++ [over.operator]p23:
5544 //
5545 // There also exist candidate operator functions of the form
5546 //
5547 // bool operator!(bool);
5548 // bool operator&&(bool, bool);
5549 // bool operator||(bool, bool);
5550 void addExclaimOverload() {
5551 QualType ParamTy = S.Context.BoolTy;
5552 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5553 /*IsAssignmentOperator=*/false,
5554 /*NumContextualBoolArguments=*/1);
5555 }
5556 void addAmpAmpOrPipePipeOverload() {
5557 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5558 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5559 /*IsAssignmentOperator=*/false,
5560 /*NumContextualBoolArguments=*/2);
5561 }
5562
5563 // C++ [over.built]p13:
5564 //
5565 // For every cv-qualified or cv-unqualified object type T there
5566 // exist candidate operator functions of the form
5567 //
5568 // T* operator+(T*, ptrdiff_t); [ABOVE]
5569 // T& operator[](T*, ptrdiff_t);
5570 // T* operator-(T*, ptrdiff_t); [ABOVE]
5571 // T* operator+(ptrdiff_t, T*); [ABOVE]
5572 // T& operator[](ptrdiff_t, T*);
5573 void addSubscriptOverloads() {
5574 for (BuiltinCandidateTypeSet::iterator
5575 Ptr = CandidateTypes[0].pointer_begin(),
5576 PtrEnd = CandidateTypes[0].pointer_end();
5577 Ptr != PtrEnd; ++Ptr) {
5578 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5579 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005580 if (!PointeeType->isObjectType())
5581 continue;
5582
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005583 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5584
5585 // T& operator[](T*, ptrdiff_t)
5586 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5587 }
5588
5589 for (BuiltinCandidateTypeSet::iterator
5590 Ptr = CandidateTypes[1].pointer_begin(),
5591 PtrEnd = CandidateTypes[1].pointer_end();
5592 Ptr != PtrEnd; ++Ptr) {
5593 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5594 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005595 if (!PointeeType->isObjectType())
5596 continue;
5597
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005598 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5599
5600 // T& operator[](ptrdiff_t, T*)
5601 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5602 }
5603 }
5604
5605 // C++ [over.built]p11:
5606 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5607 // C1 is the same type as C2 or is a derived class of C2, T is an object
5608 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5609 // there exist candidate operator functions of the form
5610 //
5611 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5612 //
5613 // where CV12 is the union of CV1 and CV2.
5614 void addArrowStarOverloads() {
5615 for (BuiltinCandidateTypeSet::iterator
5616 Ptr = CandidateTypes[0].pointer_begin(),
5617 PtrEnd = CandidateTypes[0].pointer_end();
5618 Ptr != PtrEnd; ++Ptr) {
5619 QualType C1Ty = (*Ptr);
5620 QualType C1;
5621 QualifierCollector Q1;
5622 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5623 if (!isa<RecordType>(C1))
5624 continue;
5625 // heuristic to reduce number of builtin candidates in the set.
5626 // Add volatile/restrict version only if there are conversions to a
5627 // volatile/restrict type.
5628 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5629 continue;
5630 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5631 continue;
5632 for (BuiltinCandidateTypeSet::iterator
5633 MemPtr = CandidateTypes[1].member_pointer_begin(),
5634 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5635 MemPtr != MemPtrEnd; ++MemPtr) {
5636 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5637 QualType C2 = QualType(mptr->getClass(), 0);
5638 C2 = C2.getUnqualifiedType();
5639 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5640 break;
5641 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5642 // build CV12 T&
5643 QualType T = mptr->getPointeeType();
5644 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5645 T.isVolatileQualified())
5646 continue;
5647 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5648 T.isRestrictQualified())
5649 continue;
5650 T = Q1.apply(S.Context, T);
5651 QualType ResultTy = S.Context.getLValueReferenceType(T);
5652 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5653 }
5654 }
5655 }
5656
5657 // Note that we don't consider the first argument, since it has been
5658 // contextually converted to bool long ago. The candidates below are
5659 // therefore added as binary.
5660 //
5661 // C++ [over.built]p25:
5662 // For every type T, where T is a pointer, pointer-to-member, or scoped
5663 // enumeration type, there exist candidate operator functions of the form
5664 //
5665 // T operator?(bool, T, T);
5666 //
5667 void addConditionalOperatorOverloads() {
5668 /// Set of (canonical) types that we've already handled.
5669 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5670
5671 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5672 for (BuiltinCandidateTypeSet::iterator
5673 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5674 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5675 Ptr != PtrEnd; ++Ptr) {
5676 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5677 continue;
5678
5679 QualType ParamTypes[2] = { *Ptr, *Ptr };
5680 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5681 }
5682
5683 for (BuiltinCandidateTypeSet::iterator
5684 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5685 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5686 MemPtr != MemPtrEnd; ++MemPtr) {
5687 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5688 continue;
5689
5690 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5691 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5692 }
5693
5694 if (S.getLangOptions().CPlusPlus0x) {
5695 for (BuiltinCandidateTypeSet::iterator
5696 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5697 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5698 Enum != EnumEnd; ++Enum) {
5699 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5700 continue;
5701
5702 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5703 continue;
5704
5705 QualType ParamTypes[2] = { *Enum, *Enum };
5706 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5707 }
5708 }
5709 }
5710 }
5711};
5712
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005713} // end anonymous namespace
5714
5715/// AddBuiltinOperatorCandidates - Add the appropriate built-in
5716/// operator overloads to the candidate set (C++ [over.built]), based
5717/// on the operator @p Op and the arguments given. For example, if the
5718/// operator is a binary '+', this routine might add "int
5719/// operator+(int, int)" to cover integer addition.
5720void
5721Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5722 SourceLocation OpLoc,
5723 Expr **Args, unsigned NumArgs,
5724 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005725 // Find all of the types that the arguments can convert to, but only
5726 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00005727 // that make use of these types. Also record whether we encounter non-record
5728 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005729 Qualifiers VisibleTypeConversionsQuals;
5730 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005731 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5732 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00005733
5734 bool HasNonRecordCandidateType = false;
5735 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorfec56e72010-11-03 17:00:07 +00005736 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5737 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5738 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5739 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5740 OpLoc,
5741 true,
5742 (Op == OO_Exclaim ||
5743 Op == OO_AmpAmp ||
5744 Op == OO_PipePipe),
5745 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00005746 HasNonRecordCandidateType = HasNonRecordCandidateType ||
5747 CandidateTypes[ArgIdx].hasNonRecordTypes();
5748 HasArithmeticOrEnumeralCandidateType =
5749 HasArithmeticOrEnumeralCandidateType ||
5750 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00005751 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005752
Chandler Carruth6a577462010-12-13 01:44:01 +00005753 // Exit early when no non-record types have been added to the candidate set
5754 // for any of the arguments to the operator.
5755 if (!HasNonRecordCandidateType)
5756 return;
5757
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005758 // Setup an object to manage the common state for building overloads.
5759 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
5760 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00005761 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005762 CandidateTypes, CandidateSet);
5763
5764 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005765 switch (Op) {
5766 case OO_None:
5767 case NUM_OVERLOADED_OPERATORS:
5768 assert(false && "Expected an overloaded operator");
5769 break;
5770
Chandler Carruthabb71842010-12-12 08:51:33 +00005771 case OO_New:
5772 case OO_Delete:
5773 case OO_Array_New:
5774 case OO_Array_Delete:
5775 case OO_Call:
5776 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
5777 break;
5778
5779 case OO_Comma:
5780 case OO_Arrow:
5781 // C++ [over.match.oper]p3:
5782 // -- For the operator ',', the unary operator '&', or the
5783 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00005784 break;
5785
5786 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00005787 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005788 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00005789 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00005790
5791 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00005792 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005793 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00005794 } else {
5795 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
5796 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5797 }
Douglas Gregor74253732008-11-19 15:42:04 +00005798 break;
5799
Chandler Carruthabb71842010-12-12 08:51:33 +00005800 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00005801 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00005802 OpBuilder.addUnaryStarPointerOverloads();
5803 else
5804 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5805 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005806
Chandler Carruthabb71842010-12-12 08:51:33 +00005807 case OO_Slash:
5808 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00005809 break;
Douglas Gregor74253732008-11-19 15:42:04 +00005810
5811 case OO_PlusPlus:
5812 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005813 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
5814 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00005815 break;
5816
Douglas Gregor19b7b152009-08-24 13:43:27 +00005817 case OO_EqualEqual:
5818 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005819 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00005820 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00005821
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005822 case OO_Less:
5823 case OO_Greater:
5824 case OO_LessEqual:
5825 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005826 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00005827 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
5828 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005829
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005830 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005831 case OO_Caret:
5832 case OO_Pipe:
5833 case OO_LessLess:
5834 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005835 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005836 break;
5837
Chandler Carruthabb71842010-12-12 08:51:33 +00005838 case OO_Amp: // '&' is either unary or binary
5839 if (NumArgs == 1)
5840 // C++ [over.match.oper]p3:
5841 // -- For the operator ',', the unary operator '&', or the
5842 // operator '->', the built-in candidates set is empty.
5843 break;
5844
5845 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
5846 break;
5847
5848 case OO_Tilde:
5849 OpBuilder.addUnaryTildePromotedIntegralOverloads();
5850 break;
5851
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005852 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005853 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005854 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005855
5856 case OO_PlusEqual:
5857 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005858 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005859 // Fall through.
5860
5861 case OO_StarEqual:
5862 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005863 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005864 break;
5865
5866 case OO_PercentEqual:
5867 case OO_LessLessEqual:
5868 case OO_GreaterGreaterEqual:
5869 case OO_AmpEqual:
5870 case OO_CaretEqual:
5871 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005872 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005873 break;
5874
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005875 case OO_Exclaim:
5876 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00005877 break;
Douglas Gregor74253732008-11-19 15:42:04 +00005878
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005879 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005880 case OO_PipePipe:
5881 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005882 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005883
5884 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005885 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005886 break;
5887
5888 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005889 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005890 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005891
5892 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005893 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00005894 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5895 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005896 }
5897}
5898
Douglas Gregorfa047642009-02-04 00:32:51 +00005899/// \brief Add function candidates found via argument-dependent lookup
5900/// to the set of overloading candidates.
5901///
5902/// This routine performs argument-dependent name lookup based on the
5903/// given function name (which may also be an operator name) and adds
5904/// all of the overload candidates found by ADL to the overload
5905/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00005906void
Douglas Gregorfa047642009-02-04 00:32:51 +00005907Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00005908 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00005909 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00005910 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005911 OverloadCandidateSet& CandidateSet,
5912 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00005913 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00005914
John McCalla113e722010-01-26 06:04:06 +00005915 // FIXME: This approach for uniquing ADL results (and removing
5916 // redundant candidates from the set) relies on pointer-equality,
5917 // which means we need to key off the canonical decl. However,
5918 // always going back to the canonical decl might not get us the
5919 // right set of default arguments. What default arguments are
5920 // we supposed to consider on ADL candidates, anyway?
5921
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005922 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00005923 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00005924
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005925 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005926 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5927 CandEnd = CandidateSet.end();
5928 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00005929 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00005930 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00005931 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00005932 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00005933 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005934
5935 // For each of the ADL candidates we found, add it to the overload
5936 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00005937 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00005938 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00005939 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00005940 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005941 continue;
5942
John McCall9aa472c2010-03-19 07:35:19 +00005943 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00005944 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005945 } else
John McCall6e266892010-01-26 03:27:55 +00005946 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00005947 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00005948 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00005949 }
Douglas Gregorfa047642009-02-04 00:32:51 +00005950}
5951
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005952/// isBetterOverloadCandidate - Determines whether the first overload
5953/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00005954bool
John McCall120d63c2010-08-24 20:38:10 +00005955isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00005956 const OverloadCandidate &Cand1,
5957 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005958 SourceLocation Loc,
5959 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005960 // Define viable functions to be better candidates than non-viable
5961 // functions.
5962 if (!Cand2.Viable)
5963 return Cand1.Viable;
5964 else if (!Cand1.Viable)
5965 return false;
5966
Douglas Gregor88a35142008-12-22 05:46:06 +00005967 // C++ [over.match.best]p1:
5968 //
5969 // -- if F is a static member function, ICS1(F) is defined such
5970 // that ICS1(F) is neither better nor worse than ICS1(G) for
5971 // any function G, and, symmetrically, ICS1(G) is neither
5972 // better nor worse than ICS1(F).
5973 unsigned StartArg = 0;
5974 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5975 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005976
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005977 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00005978 // A viable function F1 is defined to be a better function than another
5979 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005980 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005981 unsigned NumArgs = Cand1.Conversions.size();
5982 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5983 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005984 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00005985 switch (CompareImplicitConversionSequences(S,
5986 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005987 Cand2.Conversions[ArgIdx])) {
5988 case ImplicitConversionSequence::Better:
5989 // Cand1 has a better conversion sequence.
5990 HasBetterConversion = true;
5991 break;
5992
5993 case ImplicitConversionSequence::Worse:
5994 // Cand1 can't be better than Cand2.
5995 return false;
5996
5997 case ImplicitConversionSequence::Indistinguishable:
5998 // Do nothing.
5999 break;
6000 }
6001 }
6002
Mike Stump1eb44332009-09-09 15:08:12 +00006003 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006004 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006005 if (HasBetterConversion)
6006 return true;
6007
Mike Stump1eb44332009-09-09 15:08:12 +00006008 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006009 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00006010 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006011 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6012 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006013
6014 // -- F1 and F2 are function template specializations, and the function
6015 // template for F1 is more specialized than the template for F2
6016 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006017 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00006018 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00006019 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006020 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00006021 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6022 Cand2.Function->getPrimaryTemplate(),
6023 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00006024 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00006025 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00006026 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006027 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00006028 }
6029
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006030 // -- the context is an initialization by user-defined conversion
6031 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6032 // from the return type of F1 to the destination type (i.e.,
6033 // the type of the entity being initialized) is a better
6034 // conversion sequence than the standard conversion sequence
6035 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006036 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00006037 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006038 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00006039 switch (CompareStandardConversionSequences(S,
6040 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006041 Cand2.FinalConversion)) {
6042 case ImplicitConversionSequence::Better:
6043 // Cand1 has a better conversion sequence.
6044 return true;
6045
6046 case ImplicitConversionSequence::Worse:
6047 // Cand1 can't be better than Cand2.
6048 return false;
6049
6050 case ImplicitConversionSequence::Indistinguishable:
6051 // Do nothing
6052 break;
6053 }
6054 }
6055
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006056 return false;
6057}
6058
Mike Stump1eb44332009-09-09 15:08:12 +00006059/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00006060/// within an overload candidate set.
6061///
6062/// \param CandidateSet the set of candidate functions.
6063///
6064/// \param Loc the location of the function name (or operator symbol) for
6065/// which overload resolution occurs.
6066///
Mike Stump1eb44332009-09-09 15:08:12 +00006067/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00006068/// function, Best points to the candidate function found.
6069///
6070/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00006071OverloadingResult
6072OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00006073 iterator &Best,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006074 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006075 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00006076 Best = end();
6077 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6078 if (Cand->Viable)
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006079 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
6080 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006081 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006082 }
6083
6084 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00006085 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006086 return OR_No_Viable_Function;
6087
6088 // Make sure that this function is better than every other viable
6089 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00006090 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00006091 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006092 Cand != Best &&
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006093 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
6094 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00006095 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006096 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006097 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006098 }
Mike Stump1eb44332009-09-09 15:08:12 +00006099
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006100 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006101 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00006102 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006103 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006104 return OR_Deleted;
6105
Douglas Gregore0762c92009-06-19 23:52:42 +00006106 // C++ [basic.def.odr]p2:
6107 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00006108 // when referred to from a potentially-evaluated expression. [Note: this
6109 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00006110 // (clause 13), user-defined conversions (12.3.2), allocation function for
6111 // placement new (5.3.4), as well as non-default initialization (8.5).
6112 if (Best->Function)
John McCall120d63c2010-08-24 20:38:10 +00006113 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor9b623632010-10-12 23:32:35 +00006114
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006115 return OR_Success;
6116}
6117
John McCall3c80f572010-01-12 02:15:36 +00006118namespace {
6119
6120enum OverloadCandidateKind {
6121 oc_function,
6122 oc_method,
6123 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00006124 oc_function_template,
6125 oc_method_template,
6126 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00006127 oc_implicit_default_constructor,
6128 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00006129 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00006130};
6131
John McCall220ccbf2010-01-13 00:25:19 +00006132OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6133 FunctionDecl *Fn,
6134 std::string &Description) {
6135 bool isTemplate = false;
6136
6137 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6138 isTemplate = true;
6139 Description = S.getTemplateArgumentBindingsText(
6140 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6141 }
John McCallb1622a12010-01-06 09:43:14 +00006142
6143 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00006144 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00006145 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00006146
John McCall3c80f572010-01-12 02:15:36 +00006147 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6148 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00006149 }
6150
6151 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6152 // This actually gets spelled 'candidate function' for now, but
6153 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00006154 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00006155 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00006156
Douglas Gregor3e9438b2010-09-27 22:37:28 +00006157 assert(Meth->isCopyAssignmentOperator()
John McCallb1622a12010-01-06 09:43:14 +00006158 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00006159 return oc_implicit_copy_assignment;
6160 }
6161
John McCall220ccbf2010-01-13 00:25:19 +00006162 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00006163}
6164
6165} // end anonymous namespace
6166
6167// Notes the location of an overload candidate.
6168void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00006169 std::string FnDesc;
6170 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6171 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6172 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00006173}
6174
John McCall1d318332010-01-12 00:44:57 +00006175/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6176/// "lead" diagnostic; it will be given two arguments, the source and
6177/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00006178void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6179 Sema &S,
6180 SourceLocation CaretLoc,
6181 const PartialDiagnostic &PDiag) const {
6182 S.Diag(CaretLoc, PDiag)
6183 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00006184 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00006185 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6186 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00006187 }
John McCall81201622010-01-08 04:41:39 +00006188}
6189
John McCall1d318332010-01-12 00:44:57 +00006190namespace {
6191
John McCalladbb8f82010-01-13 09:16:55 +00006192void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6193 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6194 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00006195 assert(Cand->Function && "for now, candidate must be a function");
6196 FunctionDecl *Fn = Cand->Function;
6197
6198 // There's a conversion slot for the object argument if this is a
6199 // non-constructor method. Note that 'I' corresponds the
6200 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00006201 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00006202 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00006203 if (I == 0)
6204 isObjectArgument = true;
6205 else
6206 I--;
John McCall220ccbf2010-01-13 00:25:19 +00006207 }
6208
John McCall220ccbf2010-01-13 00:25:19 +00006209 std::string FnDesc;
6210 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6211
John McCalladbb8f82010-01-13 09:16:55 +00006212 Expr *FromExpr = Conv.Bad.FromExpr;
6213 QualType FromTy = Conv.Bad.getFromType();
6214 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00006215
John McCall5920dbb2010-02-02 02:42:52 +00006216 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00006217 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00006218 Expr *E = FromExpr->IgnoreParens();
6219 if (isa<UnaryOperator>(E))
6220 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00006221 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00006222
6223 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6224 << (unsigned) FnKind << FnDesc
6225 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6226 << ToTy << Name << I+1;
6227 return;
6228 }
6229
John McCall258b2032010-01-23 08:10:49 +00006230 // Do some hand-waving analysis to see if the non-viability is due
6231 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00006232 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6233 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6234 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6235 CToTy = RT->getPointeeType();
6236 else {
6237 // TODO: detect and diagnose the full richness of const mismatches.
6238 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6239 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6240 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6241 }
6242
6243 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6244 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6245 // It is dumb that we have to do this here.
6246 while (isa<ArrayType>(CFromTy))
6247 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6248 while (isa<ArrayType>(CToTy))
6249 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6250
6251 Qualifiers FromQs = CFromTy.getQualifiers();
6252 Qualifiers ToQs = CToTy.getQualifiers();
6253
6254 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6255 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6256 << (unsigned) FnKind << FnDesc
6257 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6258 << FromTy
6259 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6260 << (unsigned) isObjectArgument << I+1;
6261 return;
6262 }
6263
6264 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6265 assert(CVR && "unexpected qualifiers mismatch");
6266
6267 if (isObjectArgument) {
6268 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6269 << (unsigned) FnKind << FnDesc
6270 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6271 << FromTy << (CVR - 1);
6272 } else {
6273 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6274 << (unsigned) FnKind << FnDesc
6275 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6276 << FromTy << (CVR - 1) << I+1;
6277 }
6278 return;
6279 }
6280
John McCall258b2032010-01-23 08:10:49 +00006281 // Diagnose references or pointers to incomplete types differently,
6282 // since it's far from impossible that the incompleteness triggered
6283 // the failure.
6284 QualType TempFromTy = FromTy.getNonReferenceType();
6285 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6286 TempFromTy = PTy->getPointeeType();
6287 if (TempFromTy->isIncompleteType()) {
6288 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6289 << (unsigned) FnKind << FnDesc
6290 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6291 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6292 return;
6293 }
6294
Douglas Gregor85789812010-06-30 23:01:39 +00006295 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006296 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00006297 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6298 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6299 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6300 FromPtrTy->getPointeeType()) &&
6301 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6302 !ToPtrTy->getPointeeType()->isIncompleteType() &&
6303 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
6304 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006305 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00006306 }
6307 } else if (const ObjCObjectPointerType *FromPtrTy
6308 = FromTy->getAs<ObjCObjectPointerType>()) {
6309 if (const ObjCObjectPointerType *ToPtrTy
6310 = ToTy->getAs<ObjCObjectPointerType>())
6311 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6312 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6313 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6314 FromPtrTy->getPointeeType()) &&
6315 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006316 BaseToDerivedConversion = 2;
6317 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6318 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6319 !FromTy->isIncompleteType() &&
6320 !ToRefTy->getPointeeType()->isIncompleteType() &&
6321 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6322 BaseToDerivedConversion = 3;
6323 }
6324
6325 if (BaseToDerivedConversion) {
Douglas Gregor85789812010-06-30 23:01:39 +00006326 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006327 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00006328 << (unsigned) FnKind << FnDesc
6329 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006330 << (BaseToDerivedConversion - 1)
Douglas Gregor85789812010-06-30 23:01:39 +00006331 << FromTy << ToTy << I+1;
6332 return;
6333 }
6334
John McCall651f3ee2010-01-14 03:28:57 +00006335 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00006336 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6337 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00006338 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00006339 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00006340}
6341
6342void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6343 unsigned NumFormalArgs) {
6344 // TODO: treat calls to a missing default constructor as a special case
6345
6346 FunctionDecl *Fn = Cand->Function;
6347 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6348
6349 unsigned MinParams = Fn->getMinRequiredArguments();
6350
6351 // at least / at most / exactly
6352 unsigned mode, modeCount;
6353 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00006354 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6355 (Cand->FailureKind == ovl_fail_bad_deduction &&
6356 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00006357 if (MinParams != FnTy->getNumArgs() ||
6358 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00006359 mode = 0; // "at least"
6360 else
6361 mode = 2; // "exactly"
6362 modeCount = MinParams;
6363 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00006364 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6365 (Cand->FailureKind == ovl_fail_bad_deduction &&
6366 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00006367 if (MinParams != FnTy->getNumArgs())
6368 mode = 1; // "at most"
6369 else
6370 mode = 2; // "exactly"
6371 modeCount = FnTy->getNumArgs();
6372 }
6373
6374 std::string Description;
6375 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6376
6377 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00006378 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6379 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00006380}
6381
John McCall342fec42010-02-01 18:53:26 +00006382/// Diagnose a failed template-argument deduction.
6383void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6384 Expr **Args, unsigned NumArgs) {
6385 FunctionDecl *Fn = Cand->Function; // pattern
6386
Douglas Gregora9333192010-05-08 17:41:32 +00006387 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00006388 NamedDecl *ParamD;
6389 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6390 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6391 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00006392 switch (Cand->DeductionFailure.Result) {
6393 case Sema::TDK_Success:
6394 llvm_unreachable("TDK_success while diagnosing bad deduction");
6395
6396 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00006397 assert(ParamD && "no parameter found for incomplete deduction result");
6398 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6399 << ParamD->getDeclName();
6400 return;
6401 }
6402
John McCall57e97782010-08-05 09:05:08 +00006403 case Sema::TDK_Underqualified: {
6404 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6405 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6406
6407 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6408
6409 // Param will have been canonicalized, but it should just be a
6410 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00006411 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00006412 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00006413 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00006414 assert(S.Context.hasSameType(Param, NonCanonParam));
6415
6416 // Arg has also been canonicalized, but there's nothing we can do
6417 // about that. It also doesn't matter as much, because it won't
6418 // have any template parameters in it (because deduction isn't
6419 // done on dependent types).
6420 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6421
6422 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6423 << ParamD->getDeclName() << Arg << NonCanonParam;
6424 return;
6425 }
6426
6427 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00006428 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00006429 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00006430 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00006431 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00006432 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00006433 which = 1;
6434 else {
Douglas Gregora9333192010-05-08 17:41:32 +00006435 which = 2;
6436 }
6437
6438 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6439 << which << ParamD->getDeclName()
6440 << *Cand->DeductionFailure.getFirstArg()
6441 << *Cand->DeductionFailure.getSecondArg();
6442 return;
6443 }
Douglas Gregora18592e2010-05-08 18:13:28 +00006444
Douglas Gregorf1a84452010-05-08 19:15:54 +00006445 case Sema::TDK_InvalidExplicitArguments:
6446 assert(ParamD && "no parameter found for invalid explicit arguments");
6447 if (ParamD->getDeclName())
6448 S.Diag(Fn->getLocation(),
6449 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6450 << ParamD->getDeclName();
6451 else {
6452 int index = 0;
6453 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6454 index = TTP->getIndex();
6455 else if (NonTypeTemplateParmDecl *NTTP
6456 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6457 index = NTTP->getIndex();
6458 else
6459 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6460 S.Diag(Fn->getLocation(),
6461 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6462 << (index + 1);
6463 }
6464 return;
6465
Douglas Gregora18592e2010-05-08 18:13:28 +00006466 case Sema::TDK_TooManyArguments:
6467 case Sema::TDK_TooFewArguments:
6468 DiagnoseArityMismatch(S, Cand, NumArgs);
6469 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00006470
6471 case Sema::TDK_InstantiationDepth:
6472 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6473 return;
6474
6475 case Sema::TDK_SubstitutionFailure: {
6476 std::string ArgString;
6477 if (TemplateArgumentList *Args
6478 = Cand->DeductionFailure.getTemplateArgumentList())
6479 ArgString = S.getTemplateArgumentBindingsText(
6480 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6481 *Args);
6482 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6483 << ArgString;
6484 return;
6485 }
Douglas Gregora9333192010-05-08 17:41:32 +00006486
John McCall342fec42010-02-01 18:53:26 +00006487 // TODO: diagnose these individually, then kill off
6488 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00006489 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00006490 case Sema::TDK_FailedOverloadResolution:
6491 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6492 return;
6493 }
6494}
6495
6496/// Generates a 'note' diagnostic for an overload candidate. We've
6497/// already generated a primary error at the call site.
6498///
6499/// It really does need to be a single diagnostic with its caret
6500/// pointed at the candidate declaration. Yes, this creates some
6501/// major challenges of technical writing. Yes, this makes pointing
6502/// out problems with specific arguments quite awkward. It's still
6503/// better than generating twenty screens of text for every failed
6504/// overload.
6505///
6506/// It would be great to be able to express per-candidate problems
6507/// more richly for those diagnostic clients that cared, but we'd
6508/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00006509void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6510 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00006511 FunctionDecl *Fn = Cand->Function;
6512
John McCall81201622010-01-08 04:41:39 +00006513 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00006514 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00006515 std::string FnDesc;
6516 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00006517
6518 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00006519 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00006520 return;
John McCall81201622010-01-08 04:41:39 +00006521 }
6522
John McCall220ccbf2010-01-13 00:25:19 +00006523 // We don't really have anything else to say about viable candidates.
6524 if (Cand->Viable) {
6525 S.NoteOverloadCandidate(Fn);
6526 return;
6527 }
John McCall1d318332010-01-12 00:44:57 +00006528
John McCalladbb8f82010-01-13 09:16:55 +00006529 switch (Cand->FailureKind) {
6530 case ovl_fail_too_many_arguments:
6531 case ovl_fail_too_few_arguments:
6532 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00006533
John McCalladbb8f82010-01-13 09:16:55 +00006534 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00006535 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6536
John McCall717e8912010-01-23 05:17:32 +00006537 case ovl_fail_trivial_conversion:
6538 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00006539 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00006540 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006541
John McCallb1bdc622010-02-25 01:37:24 +00006542 case ovl_fail_bad_conversion: {
6543 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6544 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00006545 if (Cand->Conversions[I].isBad())
6546 return DiagnoseBadConversion(S, Cand, I);
6547
6548 // FIXME: this currently happens when we're called from SemaInit
6549 // when user-conversion overload fails. Figure out how to handle
6550 // those conditions and diagnose them well.
6551 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006552 }
John McCallb1bdc622010-02-25 01:37:24 +00006553 }
John McCalla1d7d622010-01-08 00:58:21 +00006554}
6555
6556void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6557 // Desugar the type of the surrogate down to a function type,
6558 // retaining as many typedefs as possible while still showing
6559 // the function type (and, therefore, its parameter types).
6560 QualType FnType = Cand->Surrogate->getConversionType();
6561 bool isLValueReference = false;
6562 bool isRValueReference = false;
6563 bool isPointer = false;
6564 if (const LValueReferenceType *FnTypeRef =
6565 FnType->getAs<LValueReferenceType>()) {
6566 FnType = FnTypeRef->getPointeeType();
6567 isLValueReference = true;
6568 } else if (const RValueReferenceType *FnTypeRef =
6569 FnType->getAs<RValueReferenceType>()) {
6570 FnType = FnTypeRef->getPointeeType();
6571 isRValueReference = true;
6572 }
6573 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6574 FnType = FnTypePtr->getPointeeType();
6575 isPointer = true;
6576 }
6577 // Desugar down to a function type.
6578 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6579 // Reconstruct the pointer/reference as appropriate.
6580 if (isPointer) FnType = S.Context.getPointerType(FnType);
6581 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6582 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6583
6584 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6585 << FnType;
6586}
6587
6588void NoteBuiltinOperatorCandidate(Sema &S,
6589 const char *Opc,
6590 SourceLocation OpLoc,
6591 OverloadCandidate *Cand) {
6592 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6593 std::string TypeStr("operator");
6594 TypeStr += Opc;
6595 TypeStr += "(";
6596 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6597 if (Cand->Conversions.size() == 1) {
6598 TypeStr += ")";
6599 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6600 } else {
6601 TypeStr += ", ";
6602 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6603 TypeStr += ")";
6604 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6605 }
6606}
6607
6608void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6609 OverloadCandidate *Cand) {
6610 unsigned NoOperands = Cand->Conversions.size();
6611 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6612 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00006613 if (ICS.isBad()) break; // all meaningless after first invalid
6614 if (!ICS.isAmbiguous()) continue;
6615
John McCall120d63c2010-08-24 20:38:10 +00006616 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006617 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00006618 }
6619}
6620
John McCall1b77e732010-01-15 23:32:50 +00006621SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6622 if (Cand->Function)
6623 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00006624 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00006625 return Cand->Surrogate->getLocation();
6626 return SourceLocation();
6627}
6628
John McCallbf65c0b2010-01-12 00:48:53 +00006629struct CompareOverloadCandidatesForDisplay {
6630 Sema &S;
6631 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00006632
6633 bool operator()(const OverloadCandidate *L,
6634 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00006635 // Fast-path this check.
6636 if (L == R) return false;
6637
John McCall81201622010-01-08 04:41:39 +00006638 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00006639 if (L->Viable) {
6640 if (!R->Viable) return true;
6641
6642 // TODO: introduce a tri-valued comparison for overload
6643 // candidates. Would be more worthwhile if we had a sort
6644 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00006645 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6646 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00006647 } else if (R->Viable)
6648 return false;
John McCall81201622010-01-08 04:41:39 +00006649
John McCall1b77e732010-01-15 23:32:50 +00006650 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00006651
John McCall1b77e732010-01-15 23:32:50 +00006652 // Criteria by which we can sort non-viable candidates:
6653 if (!L->Viable) {
6654 // 1. Arity mismatches come after other candidates.
6655 if (L->FailureKind == ovl_fail_too_many_arguments ||
6656 L->FailureKind == ovl_fail_too_few_arguments)
6657 return false;
6658 if (R->FailureKind == ovl_fail_too_many_arguments ||
6659 R->FailureKind == ovl_fail_too_few_arguments)
6660 return true;
John McCall81201622010-01-08 04:41:39 +00006661
John McCall717e8912010-01-23 05:17:32 +00006662 // 2. Bad conversions come first and are ordered by the number
6663 // of bad conversions and quality of good conversions.
6664 if (L->FailureKind == ovl_fail_bad_conversion) {
6665 if (R->FailureKind != ovl_fail_bad_conversion)
6666 return true;
6667
6668 // If there's any ordering between the defined conversions...
6669 // FIXME: this might not be transitive.
6670 assert(L->Conversions.size() == R->Conversions.size());
6671
6672 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00006673 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6674 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00006675 switch (CompareImplicitConversionSequences(S,
6676 L->Conversions[I],
6677 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00006678 case ImplicitConversionSequence::Better:
6679 leftBetter++;
6680 break;
6681
6682 case ImplicitConversionSequence::Worse:
6683 leftBetter--;
6684 break;
6685
6686 case ImplicitConversionSequence::Indistinguishable:
6687 break;
6688 }
6689 }
6690 if (leftBetter > 0) return true;
6691 if (leftBetter < 0) return false;
6692
6693 } else if (R->FailureKind == ovl_fail_bad_conversion)
6694 return false;
6695
John McCall1b77e732010-01-15 23:32:50 +00006696 // TODO: others?
6697 }
6698
6699 // Sort everything else by location.
6700 SourceLocation LLoc = GetLocationForCandidate(L);
6701 SourceLocation RLoc = GetLocationForCandidate(R);
6702
6703 // Put candidates without locations (e.g. builtins) at the end.
6704 if (LLoc.isInvalid()) return false;
6705 if (RLoc.isInvalid()) return true;
6706
6707 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00006708 }
6709};
6710
John McCall717e8912010-01-23 05:17:32 +00006711/// CompleteNonViableCandidate - Normally, overload resolution only
6712/// computes up to the first
6713void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6714 Expr **Args, unsigned NumArgs) {
6715 assert(!Cand->Viable);
6716
6717 // Don't do anything on failures other than bad conversion.
6718 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6719
6720 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00006721 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00006722 unsigned ConvCount = Cand->Conversions.size();
6723 while (true) {
6724 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6725 ConvIdx++;
6726 if (Cand->Conversions[ConvIdx - 1].isBad())
6727 break;
6728 }
6729
6730 if (ConvIdx == ConvCount)
6731 return;
6732
John McCallb1bdc622010-02-25 01:37:24 +00006733 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6734 "remaining conversion is initialized?");
6735
Douglas Gregor23ef6c02010-04-16 17:45:54 +00006736 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00006737 // operation somehow.
6738 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00006739
6740 const FunctionProtoType* Proto;
6741 unsigned ArgIdx = ConvIdx;
6742
6743 if (Cand->IsSurrogate) {
6744 QualType ConvType
6745 = Cand->Surrogate->getConversionType().getNonReferenceType();
6746 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6747 ConvType = ConvPtrType->getPointeeType();
6748 Proto = ConvType->getAs<FunctionProtoType>();
6749 ArgIdx--;
6750 } else if (Cand->Function) {
6751 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6752 if (isa<CXXMethodDecl>(Cand->Function) &&
6753 !isa<CXXConstructorDecl>(Cand->Function))
6754 ArgIdx--;
6755 } else {
6756 // Builtin binary operator with a bad first conversion.
6757 assert(ConvCount <= 3);
6758 for (; ConvIdx != ConvCount; ++ConvIdx)
6759 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006760 = TryCopyInitialization(S, Args[ConvIdx],
6761 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6762 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006763 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00006764 return;
6765 }
6766
6767 // Fill in the rest of the conversions.
6768 unsigned NumArgsInProto = Proto->getNumArgs();
6769 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6770 if (ArgIdx < NumArgsInProto)
6771 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006772 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6773 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006774 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00006775 else
6776 Cand->Conversions[ConvIdx].setEllipsis();
6777 }
6778}
6779
John McCalla1d7d622010-01-08 00:58:21 +00006780} // end anonymous namespace
6781
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006782/// PrintOverloadCandidates - When overload resolution fails, prints
6783/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00006784/// set.
John McCall120d63c2010-08-24 20:38:10 +00006785void OverloadCandidateSet::NoteCandidates(Sema &S,
6786 OverloadCandidateDisplayKind OCD,
6787 Expr **Args, unsigned NumArgs,
6788 const char *Opc,
6789 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00006790 // Sort the candidates by viability and position. Sorting directly would
6791 // be prohibitive, so we make a set of pointers and sort those.
6792 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00006793 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6794 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00006795 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00006796 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00006797 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00006798 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006799 if (Cand->Function || Cand->IsSurrogate)
6800 Cands.push_back(Cand);
6801 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6802 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00006803 }
6804 }
6805
John McCallbf65c0b2010-01-12 00:48:53 +00006806 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00006807 CompareOverloadCandidatesForDisplay(S));
John McCall81201622010-01-08 04:41:39 +00006808
John McCall1d318332010-01-12 00:44:57 +00006809 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00006810
John McCall81201622010-01-08 04:41:39 +00006811 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall120d63c2010-08-24 20:38:10 +00006812 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006813 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00006814 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6815 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00006816
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006817 // Set an arbitrary limit on the number of candidate functions we'll spam
6818 // the user with. FIXME: This limit should depend on details of the
6819 // candidate list.
6820 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6821 break;
6822 }
6823 ++CandsShown;
6824
John McCalla1d7d622010-01-08 00:58:21 +00006825 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00006826 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00006827 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00006828 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006829 else {
6830 assert(Cand->Viable &&
6831 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00006832 // Generally we only see ambiguities including viable builtin
6833 // operators if overload resolution got screwed up by an
6834 // ambiguous user-defined conversion.
6835 //
6836 // FIXME: It's quite possible for different conversions to see
6837 // different ambiguities, though.
6838 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00006839 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00006840 ReportedAmbiguousConversions = true;
6841 }
John McCalla1d7d622010-01-08 00:58:21 +00006842
John McCall1d318332010-01-12 00:44:57 +00006843 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00006844 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006845 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006846 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006847
6848 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00006849 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006850}
6851
John McCall9aa472c2010-03-19 07:35:19 +00006852static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00006853 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00006854 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006855
John McCall9aa472c2010-03-19 07:35:19 +00006856 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006857}
6858
Douglas Gregor904eed32008-11-10 20:40:00 +00006859/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6860/// an overloaded function (C++ [over.over]), where @p From is an
6861/// expression with overloaded function type and @p ToType is the type
6862/// we're trying to resolve to. For example:
6863///
6864/// @code
6865/// int f(double);
6866/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00006867///
Douglas Gregor904eed32008-11-10 20:40:00 +00006868/// int (*pfd)(double) = f; // selects f(double)
6869/// @endcode
6870///
6871/// This routine returns the resulting FunctionDecl if it could be
6872/// resolved, and NULL otherwise. When @p Complain is true, this
6873/// routine will emit diagnostics if there is an error.
6874FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00006875Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00006876 bool Complain,
6877 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006878 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00006879 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00006880 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00006881 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00006882 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00006883 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00006884 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00006885 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006886 FunctionType = MemTypePtr->getPointeeType();
6887 IsMember = true;
6888 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006889
Douglas Gregor904eed32008-11-10 20:40:00 +00006890 // C++ [over.over]p1:
6891 // [...] [Note: any redundant set of parentheses surrounding the
6892 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00006893 // C++ [over.over]p1:
6894 // [...] The overloaded function name can be preceded by the &
6895 // operator.
John McCallc988fab2010-08-24 23:26:21 +00006896 // However, remember whether the expression has member-pointer form:
6897 // C++ [expr.unary.op]p4:
6898 // A pointer to member is only formed when an explicit & is used
6899 // and its operand is a qualified-id not enclosed in
6900 // parentheses.
John McCall9c72c602010-08-27 09:08:28 +00006901 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6902 OverloadExpr *OvlExpr = Ovl.Expression;
John McCallc988fab2010-08-24 23:26:21 +00006903
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006904 // We expect a pointer or reference to function, or a function pointer.
6905 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6906 if (!FunctionType->isFunctionType()) {
6907 if (Complain)
6908 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6909 << OvlExpr->getName() << ToType;
6910
6911 return 0;
6912 }
6913
John McCallfb97e752010-08-24 22:52:39 +00006914 // If the overload expression doesn't have the form of a pointer to
John McCallc988fab2010-08-24 23:26:21 +00006915 // member, don't try to convert it to a pointer-to-member type.
John McCall9c72c602010-08-27 09:08:28 +00006916 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCallfb97e752010-08-24 22:52:39 +00006917 if (!Complain) return 0;
6918
6919 // TODO: Should we condition this on whether any functions might
6920 // have matched, or is it more appropriate to do that in callers?
6921 // TODO: a fixit wouldn't hurt.
6922 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6923 << ToType << OvlExpr->getSourceRange();
6924 return 0;
6925 }
6926
6927 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6928 if (OvlExpr->hasExplicitTemplateArgs()) {
6929 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6930 ExplicitTemplateArgs = &ETABuffer;
6931 }
6932
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006933 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00006934
Douglas Gregor904eed32008-11-10 20:40:00 +00006935 // Look through all of the overloaded functions, searching for one
6936 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00006937 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00006938 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor9b623632010-10-12 23:32:35 +00006939
Douglas Gregor00aeb522009-07-08 23:33:52 +00006940 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00006941 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6942 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00006943 // Look through any using declarations to find the underlying function.
6944 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6945
Douglas Gregor904eed32008-11-10 20:40:00 +00006946 // C++ [over.over]p3:
6947 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00006948 // targets of type "pointer-to-function" or "reference-to-function."
6949 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00006950 // type "pointer-to-member-function."
6951 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006952
Mike Stump1eb44332009-09-09 15:08:12 +00006953 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00006954 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006955 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00006956 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00006957 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00006958 // static when converting to member pointer.
6959 if (Method->isStatic() == IsMember)
6960 continue;
6961 } else if (IsMember)
6962 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00006963
Douglas Gregor00aeb522009-07-08 23:33:52 +00006964 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006965 // If the name is a function template, template argument deduction is
6966 // done (14.8.2.2), and if the argument deduction succeeds, the
6967 // resulting template argument list is used to generate a single
6968 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00006969 // overloaded functions considered.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006970 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006971 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00006972 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00006973 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00006974 FunctionType, Specialization, Info)) {
6975 // FIXME: make a note of the failed deduction for diagnostics.
6976 (void)Result;
6977 } else {
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00006978 // Template argument deduction ensures that we have an exact match.
6979 // This function template specicalization works.
Douglas Gregor9b623632010-10-12 23:32:35 +00006980 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006981 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00006982 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor9b623632010-10-12 23:32:35 +00006983 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor83314aa2009-07-08 20:55:45 +00006984 }
John McCallba135432009-11-21 08:51:07 +00006985
6986 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00006987 }
Mike Stump1eb44332009-09-09 15:08:12 +00006988
Chandler Carruthbd647292009-12-29 06:17:27 +00006989 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006990 // Skip non-static functions when converting to pointer, and static
6991 // when converting to member pointer.
6992 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00006993 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006994
6995 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00006996 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006997 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00006998 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00006999 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00007000
Chandler Carruthbd647292009-12-29 06:17:27 +00007001 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00007002 QualType ResultTy;
7003 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
7004 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
7005 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00007006 Matches.push_back(std::make_pair(I.getPair(),
7007 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00007008 FoundNonTemplateFunction = true;
7009 }
Mike Stump1eb44332009-09-09 15:08:12 +00007010 }
Douglas Gregor904eed32008-11-10 20:40:00 +00007011 }
7012
Douglas Gregor00aeb522009-07-08 23:33:52 +00007013 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00007014 if (Matches.empty()) {
7015 if (Complain) {
7016 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
7017 << OvlExpr->getName() << FunctionType;
7018 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7019 E = OvlExpr->decls_end();
7020 I != E; ++I)
7021 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
7022 NoteOverloadCandidate(F);
7023 }
7024
Douglas Gregor00aeb522009-07-08 23:33:52 +00007025 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00007026 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00007027 FunctionDecl *Result = Matches[0].second;
Douglas Gregor9b623632010-10-12 23:32:35 +00007028 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00007029 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor9b623632010-10-12 23:32:35 +00007030 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00007031 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor9b623632010-10-12 23:32:35 +00007032 }
Sebastian Redl07ab2022009-10-17 21:12:09 +00007033 return Result;
7034 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00007035
7036 // C++ [over.over]p4:
7037 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00007038 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007039 // [...] and any given function template specialization F1 is
7040 // eliminated if the set contains a second function template
7041 // specialization whose function template is more specialized
7042 // than the function template of F1 according to the partial
7043 // ordering rules of 14.5.5.2.
7044
7045 // The algorithm specified above is quadratic. We instead use a
7046 // two-pass algorithm (similar to the one used to identify the
7047 // best viable function in an overload set) that identifies the
7048 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00007049
7050 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7051 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7052 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00007053
7054 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00007055 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007056 TPOC_Other, 0, From->getLocStart(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00007057 PDiag(),
7058 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00007059 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00007060 PDiag(diag::note_ovl_candidate)
7061 << (unsigned) oc_function_template);
Douglas Gregor78c057e2010-09-12 08:16:09 +00007062 if (Result == MatchesCopy.end())
7063 return 0;
7064
John McCallc373d482010-01-27 01:50:18 +00007065 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00007066 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor9b623632010-10-12 23:32:35 +00007067 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00007068 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallc373d482010-01-27 01:50:18 +00007069 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00007070 }
Mike Stump1eb44332009-09-09 15:08:12 +00007071
Douglas Gregor312a2022009-09-26 03:56:17 +00007072 // [...] any function template specializations in the set are
7073 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00007074 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00007075 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00007076 ++I;
7077 else {
John McCall9aa472c2010-03-19 07:35:19 +00007078 Matches[I] = Matches[--N];
7079 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00007080 }
7081 }
Douglas Gregor312a2022009-09-26 03:56:17 +00007082
Mike Stump1eb44332009-09-09 15:08:12 +00007083 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00007084 // selected function.
John McCallc373d482010-01-27 01:50:18 +00007085 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00007086 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00007087 FoundResult = Matches[0].first;
Douglas Gregor9b623632010-10-12 23:32:35 +00007088 if (Complain)
John McCall9aa472c2010-03-19 07:35:19 +00007089 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
7090 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00007091 }
Mike Stump1eb44332009-09-09 15:08:12 +00007092
Douglas Gregor00aeb522009-07-08 23:33:52 +00007093 // FIXME: We should probably return the same thing that BestViableFunction
7094 // returns (even if we issue the diagnostics here).
Douglas Gregor8e960432010-11-08 03:40:48 +00007095 if (Complain) {
7096 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
7097 << Matches[0].second->getDeclName();
7098 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7099 NoteOverloadCandidate(Matches[I].second);
7100 }
7101
Douglas Gregor904eed32008-11-10 20:40:00 +00007102 return 0;
7103}
7104
Douglas Gregor4b52e252009-12-21 23:17:24 +00007105/// \brief Given an expression that refers to an overloaded function, try to
7106/// resolve that overloaded function expression down to a single function.
7107///
7108/// This routine can only resolve template-ids that refer to a single function
7109/// template, where that template-id refers to a single template whose template
7110/// arguments are either provided by the template-id or have defaults,
7111/// as described in C++0x [temp.arg.explicit]p3.
7112FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
7113 // C++ [over.over]p1:
7114 // [...] [Note: any redundant set of parentheses surrounding the
7115 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00007116 // C++ [over.over]p1:
7117 // [...] The overloaded function name can be preceded by the &
7118 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00007119
7120 if (From->getType() != Context.OverloadTy)
7121 return 0;
7122
John McCall9c72c602010-08-27 09:08:28 +00007123 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor4b52e252009-12-21 23:17:24 +00007124
7125 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00007126 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00007127 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00007128
7129 TemplateArgumentListInfo ExplicitTemplateArgs;
7130 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00007131
7132 // Look through all of the overloaded functions, searching for one
7133 // whose type matches exactly.
7134 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00007135 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7136 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00007137 // C++0x [temp.arg.explicit]p3:
7138 // [...] In contexts where deduction is done and fails, or in contexts
7139 // where deduction is not done, if a template argument list is
7140 // specified and it, along with any default template arguments,
7141 // identifies a single function template specialization, then the
7142 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00007143 FunctionTemplateDecl *FunctionTemplate
7144 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor4b52e252009-12-21 23:17:24 +00007145
7146 // C++ [over.over]p2:
7147 // If the name is a function template, template argument deduction is
7148 // done (14.8.2.2), and if the argument deduction succeeds, the
7149 // resulting template argument list is used to generate a single
7150 // function template specialization, which is added to the set of
7151 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00007152 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00007153 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00007154 if (TemplateDeductionResult Result
7155 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7156 Specialization, Info)) {
7157 // FIXME: make a note of the failed deduction for diagnostics.
7158 (void)Result;
7159 continue;
7160 }
7161
7162 // Multiple matches; we can't resolve to a single declaration.
7163 if (Matched)
7164 return 0;
7165
7166 Matched = Specialization;
7167 }
Douglas Gregor9b623632010-10-12 23:32:35 +00007168
Douglas Gregor4b52e252009-12-21 23:17:24 +00007169 return Matched;
7170}
7171
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007172/// \brief Add a single candidate to the overload set.
7173static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00007174 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00007175 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007176 Expr **Args, unsigned NumArgs,
7177 OverloadCandidateSet &CandidateSet,
7178 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00007179 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00007180 if (isa<UsingShadowDecl>(Callee))
7181 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7182
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007183 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00007184 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00007185 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00007186 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007187 return;
John McCallba135432009-11-21 08:51:07 +00007188 }
7189
7190 if (FunctionTemplateDecl *FuncTemplate
7191 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00007192 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7193 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00007194 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00007195 return;
7196 }
7197
7198 assert(false && "unhandled case in overloaded call candidate");
7199
7200 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007201}
7202
7203/// \brief Add the overload candidates named by callee and/or found by argument
7204/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00007205void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007206 Expr **Args, unsigned NumArgs,
7207 OverloadCandidateSet &CandidateSet,
7208 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00007209
7210#ifndef NDEBUG
7211 // Verify that ArgumentDependentLookup is consistent with the rules
7212 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007213 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007214 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7215 // and let Y be the lookup set produced by argument dependent
7216 // lookup (defined as follows). If X contains
7217 //
7218 // -- a declaration of a class member, or
7219 //
7220 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00007221 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007222 //
7223 // -- a declaration that is neither a function or a function
7224 // template
7225 //
7226 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00007227
John McCall3b4294e2009-12-16 12:17:52 +00007228 if (ULE->requiresADL()) {
7229 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7230 E = ULE->decls_end(); I != E; ++I) {
7231 assert(!(*I)->getDeclContext()->isRecord());
7232 assert(isa<UsingShadowDecl>(*I) ||
7233 !(*I)->getDeclContext()->isFunctionOrMethod());
7234 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00007235 }
7236 }
7237#endif
7238
John McCall3b4294e2009-12-16 12:17:52 +00007239 // It would be nice to avoid this copy.
7240 TemplateArgumentListInfo TABuffer;
7241 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7242 if (ULE->hasExplicitTemplateArgs()) {
7243 ULE->copyTemplateArgumentsInto(TABuffer);
7244 ExplicitTemplateArgs = &TABuffer;
7245 }
7246
7247 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7248 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00007249 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00007250 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007251 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00007252
John McCall3b4294e2009-12-16 12:17:52 +00007253 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00007254 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7255 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007256 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007257 CandidateSet,
7258 PartialOverloading);
7259}
John McCall578b69b2009-12-16 08:11:27 +00007260
7261/// Attempts to recover from a call where no functions were found.
7262///
7263/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00007264static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00007265BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00007266 UnresolvedLookupExpr *ULE,
7267 SourceLocation LParenLoc,
7268 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00007269 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00007270
7271 CXXScopeSpec SS;
7272 if (ULE->getQualifier()) {
7273 SS.setScopeRep(ULE->getQualifier());
7274 SS.setRange(ULE->getQualifierRange());
7275 }
7276
John McCall3b4294e2009-12-16 12:17:52 +00007277 TemplateArgumentListInfo TABuffer;
7278 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7279 if (ULE->hasExplicitTemplateArgs()) {
7280 ULE->copyTemplateArgumentsInto(TABuffer);
7281 ExplicitTemplateArgs = &TABuffer;
7282 }
7283
John McCall578b69b2009-12-16 08:11:27 +00007284 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7285 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00007286 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallf312b1e2010-08-26 23:41:50 +00007287 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00007288
John McCall3b4294e2009-12-16 12:17:52 +00007289 assert(!R.empty() && "lookup results empty despite recovery");
7290
7291 // Build an implicit member call if appropriate. Just drop the
7292 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00007293 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00007294 if ((*R.begin())->isCXXClassMember())
Chandler Carruth6df868e2010-12-12 08:17:55 +00007295 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7296 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00007297 else if (ExplicitTemplateArgs)
7298 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7299 else
7300 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7301
7302 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007303 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00007304
7305 // This shouldn't cause an infinite loop because we're giving it
7306 // an expression with non-empty lookup results, which should never
7307 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00007308 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00007309 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00007310}
Douglas Gregord7a95972010-06-08 17:35:15 +00007311
Douglas Gregorf6b89692008-11-26 05:54:23 +00007312/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00007313/// (which eventually refers to the declaration Func) and the call
7314/// arguments Args/NumArgs, attempt to resolve the function call down
7315/// to a specific function. If overload resolution succeeds, returns
7316/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00007317/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00007318/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00007319ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00007320Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00007321 SourceLocation LParenLoc,
7322 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00007323 SourceLocation RParenLoc) {
7324#ifndef NDEBUG
7325 if (ULE->requiresADL()) {
7326 // To do ADL, we must have found an unqualified name.
7327 assert(!ULE->getQualifier() && "qualified name with ADL");
7328
7329 // We don't perform ADL for implicit declarations of builtins.
7330 // Verify that this was correctly set up.
7331 FunctionDecl *F;
7332 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7333 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7334 F->getBuiltinID() && F->isImplicit())
7335 assert(0 && "performing ADL for builtin");
7336
7337 // We don't perform ADL in C.
7338 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7339 }
7340#endif
7341
John McCall5769d612010-02-08 23:07:23 +00007342 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00007343
John McCall3b4294e2009-12-16 12:17:52 +00007344 // Add the functions denoted by the callee to the set of candidate
7345 // functions, including those from argument-dependent lookup.
7346 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00007347
7348 // If we found nothing, try to recover.
7349 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7350 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00007351 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00007352 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00007353 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00007354
Douglas Gregorf6b89692008-11-26 05:54:23 +00007355 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007356 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00007357 case OR_Success: {
7358 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00007359 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007360 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7361 ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00007362 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007363 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
7364 RParenLoc);
John McCall3b4294e2009-12-16 12:17:52 +00007365 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00007366
7367 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00007368 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00007369 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00007370 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007371 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00007372 break;
7373
7374 case OR_Ambiguous:
7375 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00007376 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007377 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00007378 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007379
7380 case OR_Deleted:
7381 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7382 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00007383 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007384 << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007385 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007386 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00007387 }
7388
Douglas Gregorff331c12010-07-25 18:17:45 +00007389 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00007390 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00007391}
7392
John McCall6e266892010-01-26 03:27:55 +00007393static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00007394 return Functions.size() > 1 ||
7395 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7396}
7397
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007398/// \brief Create a unary operation that may resolve to an overloaded
7399/// operator.
7400///
7401/// \param OpLoc The location of the operator itself (e.g., '*').
7402///
7403/// \param OpcIn The UnaryOperator::Opcode that describes this
7404/// operator.
7405///
7406/// \param Functions The set of non-member functions that will be
7407/// considered by overload resolution. The caller needs to build this
7408/// set based on the context using, e.g.,
7409/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7410/// set should not contain any member functions; those will be added
7411/// by CreateOverloadedUnaryOp().
7412///
7413/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00007414ExprResult
John McCall6e266892010-01-26 03:27:55 +00007415Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7416 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00007417 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007418 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007419
7420 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7421 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7422 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00007423 // TODO: provide better source location info.
7424 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007425
John McCall0e800c92010-12-04 08:14:53 +00007426 if (Input->getObjectKind() == OK_ObjCProperty)
7427 ConvertPropertyForRValue(Input);
7428
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007429 Expr *Args[2] = { Input, 0 };
7430 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00007431
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007432 // For post-increment and post-decrement, add the implicit '0' as
7433 // the second argument, so that we know this is a post-increment or
7434 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00007435 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007436 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007437 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7438 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007439 NumArgs = 2;
7440 }
7441
7442 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00007443 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00007444 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00007445 Opc,
7446 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007447 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00007448 OpLoc));
7449
John McCallc373d482010-01-27 01:50:18 +00007450 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00007451 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00007452 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007453 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007454 /*ADL*/ true, IsOverloaded(Fns),
7455 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007456 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7457 &Args[0], NumArgs,
7458 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007459 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007460 OpLoc));
7461 }
7462
7463 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007464 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007465
7466 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00007467 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007468
7469 // Add operator candidates that are member functions.
7470 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7471
John McCall6e266892010-01-26 03:27:55 +00007472 // Add candidates from ADL.
7473 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00007474 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00007475 /*ExplicitTemplateArgs*/ 0,
7476 CandidateSet);
7477
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007478 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00007479 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007480
7481 // Perform overload resolution.
7482 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007483 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007484 case OR_Success: {
7485 // We found a built-in operator or an overloaded operator.
7486 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00007487
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007488 if (FnDecl) {
7489 // We matched an overloaded operator. Build a call to that
7490 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00007491
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007492 // Convert the arguments.
7493 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00007494 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007495
John McCall6bb80172010-03-30 21:47:33 +00007496 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7497 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007498 return ExprError();
7499 } else {
7500 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007501 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00007502 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007503 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00007504 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00007505 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00007506 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00007507 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007508 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00007509 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007510 }
7511
John McCallb697e082010-05-06 18:15:07 +00007512 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7513
John McCallf89e55a2010-11-18 06:31:45 +00007514 // Determine the result type.
7515 QualType ResultTy = FnDecl->getResultType();
7516 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7517 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00007518
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007519 // Build the actual expression node.
John McCallf89e55a2010-11-18 06:31:45 +00007520 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00007521
Eli Friedman4c3b8962009-11-18 03:58:17 +00007522 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00007523 CallExpr *TheCall =
Anders Carlsson26a2a072009-10-13 21:19:37 +00007524 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCallf89e55a2010-11-18 06:31:45 +00007525 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00007526
John McCall9ae2f072010-08-23 23:25:46 +00007527 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00007528 FnDecl))
7529 return ExprError();
7530
John McCall9ae2f072010-08-23 23:25:46 +00007531 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007532 } else {
7533 // We matched a built-in operator. Convert the arguments, then
7534 // break out so that we will build the appropriate built-in
7535 // operator node.
7536 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007537 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007538 return ExprError();
7539
7540 break;
7541 }
7542 }
7543
7544 case OR_No_Viable_Function:
7545 // No viable function; fall through to handling this as a
7546 // built-in operator, which will produce an error message for us.
7547 break;
7548
7549 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00007550 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007551 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00007552 << Input->getType()
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007553 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007554 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7555 Args, NumArgs,
7556 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007557 return ExprError();
7558
7559 case OR_Deleted:
7560 Diag(OpLoc, diag::err_ovl_deleted_oper)
7561 << Best->Function->isDeleted()
7562 << UnaryOperator::getOpcodeStr(Opc)
7563 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007564 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007565 return ExprError();
7566 }
7567
7568 // Either we found no viable overloaded operator or we matched a
7569 // built-in operator. In either case, fall through to trying to
7570 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00007571 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007572}
7573
Douglas Gregor063daf62009-03-13 18:40:31 +00007574/// \brief Create a binary operation that may resolve to an overloaded
7575/// operator.
7576///
7577/// \param OpLoc The location of the operator itself (e.g., '+').
7578///
7579/// \param OpcIn The BinaryOperator::Opcode that describes this
7580/// operator.
7581///
7582/// \param Functions The set of non-member functions that will be
7583/// considered by overload resolution. The caller needs to build this
7584/// set based on the context using, e.g.,
7585/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7586/// set should not contain any member functions; those will be added
7587/// by CreateOverloadedBinOp().
7588///
7589/// \param LHS Left-hand argument.
7590/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00007591ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00007592Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00007593 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00007594 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00007595 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00007596 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007597 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00007598
7599 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7600 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7601 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7602
7603 // If either side is type-dependent, create an appropriate dependent
7604 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007605 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00007606 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007607 // If there are no functions to store, just build a dependent
7608 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00007609 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007610 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +00007611 Context.DependentTy,
7612 VK_RValue, OK_Ordinary,
7613 OpLoc));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007614
7615 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7616 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007617 VK_LValue,
7618 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007619 Context.DependentTy,
7620 Context.DependentTy,
7621 OpLoc));
7622 }
John McCall6e266892010-01-26 03:27:55 +00007623
7624 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00007625 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007626 // TODO: provide better source location info in DNLoc component.
7627 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00007628 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00007629 = UnresolvedLookupExpr::Create(Context, NamingClass, 0, SourceRange(),
7630 OpNameInfo, /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007631 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00007632 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00007633 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00007634 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007635 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +00007636 OpLoc));
7637 }
7638
John McCall0e800c92010-12-04 08:14:53 +00007639 // Always do property rvalue conversions on the RHS.
7640 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7641 ConvertPropertyForRValue(Args[1]);
7642
7643 // The LHS is more complicated.
7644 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
7645
7646 // There's a tension for assignment operators between primitive
7647 // property assignment and the overloaded operators.
7648 if (BinaryOperator::isAssignmentOp(Opc)) {
7649 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7650
7651 // Is the property "logically" settable?
7652 bool Settable = (PRE->isExplicitProperty() ||
7653 PRE->getImplicitPropertySetter());
7654
7655 // To avoid gratuitously inventing semantics, use the primitive
7656 // unless it isn't. Thoughts in case we ever really care:
7657 // - If the property isn't logically settable, we have to
7658 // load and hope.
7659 // - If the property is settable and this is simple assignment,
7660 // we really should use the primitive.
7661 // - If the property is settable, then we could try overloading
7662 // on a generic lvalue of the appropriate type; if it works
7663 // out to a builtin candidate, we would do that same operation
7664 // on the property, and otherwise just error.
7665 if (Settable)
7666 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7667 }
7668
7669 ConvertPropertyForRValue(Args[0]);
7670 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007671
Sebastian Redl275c2b42009-11-18 23:10:33 +00007672 // If this is the assignment operator, we only perform overload resolution
7673 // if the left-hand side is a class or enumeration type. This is actually
7674 // a hack. The standard requires that we do overload resolution between the
7675 // various built-in candidates, but as DR507 points out, this can lead to
7676 // problems. So we do it this way, which pretty much follows what GCC does.
7677 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00007678 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007679 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007680
John McCall0e800c92010-12-04 08:14:53 +00007681 // If this is the .* operator, which is not overloadable, just
7682 // create a built-in binary operator.
7683 if (Opc == BO_PtrMemD)
7684 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7685
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007686 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007687 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007688
7689 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00007690 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00007691
7692 // Add operator candidates that are member functions.
7693 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7694
John McCall6e266892010-01-26 03:27:55 +00007695 // Add candidates from ADL.
7696 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7697 Args, 2,
7698 /*ExplicitTemplateArgs*/ 0,
7699 CandidateSet);
7700
Douglas Gregor063daf62009-03-13 18:40:31 +00007701 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00007702 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00007703
7704 // Perform overload resolution.
7705 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007706 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007707 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00007708 // We found a built-in operator or an overloaded operator.
7709 FunctionDecl *FnDecl = Best->Function;
7710
7711 if (FnDecl) {
7712 // We matched an overloaded operator. Build a call to that
7713 // operator.
7714
7715 // Convert the arguments.
7716 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00007717 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00007718 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007719
Chandler Carruth6df868e2010-12-12 08:17:55 +00007720 ExprResult Arg1 =
7721 PerformCopyInitialization(
7722 InitializedEntity::InitializeParameter(Context,
7723 FnDecl->getParamDecl(0)),
7724 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007725 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007726 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007727
Douglas Gregor5fccd362010-03-03 23:55:11 +00007728 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007729 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007730 return ExprError();
7731
7732 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007733 } else {
7734 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +00007735 ExprResult Arg0 = PerformCopyInitialization(
7736 InitializedEntity::InitializeParameter(Context,
7737 FnDecl->getParamDecl(0)),
7738 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007739 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007740 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007741
Chandler Carruth6df868e2010-12-12 08:17:55 +00007742 ExprResult Arg1 =
7743 PerformCopyInitialization(
7744 InitializedEntity::InitializeParameter(Context,
7745 FnDecl->getParamDecl(1)),
7746 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007747 if (Arg1.isInvalid())
7748 return ExprError();
7749 Args[0] = LHS = Arg0.takeAs<Expr>();
7750 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007751 }
7752
John McCallb697e082010-05-06 18:15:07 +00007753 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7754
John McCallf89e55a2010-11-18 06:31:45 +00007755 // Determine the result type.
7756 QualType ResultTy = FnDecl->getResultType();
7757 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7758 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00007759
7760 // Build the actual expression node.
John McCallf89e55a2010-11-18 06:31:45 +00007761 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007762
John McCall9ae2f072010-08-23 23:25:46 +00007763 CXXOperatorCallExpr *TheCall =
7764 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCallf89e55a2010-11-18 06:31:45 +00007765 Args, 2, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007766
John McCall9ae2f072010-08-23 23:25:46 +00007767 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00007768 FnDecl))
7769 return ExprError();
7770
John McCall9ae2f072010-08-23 23:25:46 +00007771 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00007772 } else {
7773 // We matched a built-in operator. Convert the arguments, then
7774 // break out so that we will build the appropriate built-in
7775 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007776 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007777 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007778 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007779 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00007780 return ExprError();
7781
7782 break;
7783 }
7784 }
7785
Douglas Gregor33074752009-09-30 21:46:01 +00007786 case OR_No_Viable_Function: {
7787 // C++ [over.match.oper]p9:
7788 // If the operator is the operator , [...] and there are no
7789 // viable functions, then the operator is assumed to be the
7790 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00007791 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00007792 break;
7793
Chandler Carruth6df868e2010-12-12 08:17:55 +00007794 // For class as left operand for assignment or compound assigment
7795 // operator do not fall through to handling in built-in, but report that
7796 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00007797 ExprResult Result = ExprError();
Douglas Gregor33074752009-09-30 21:46:01 +00007798 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00007799 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00007800 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7801 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007802 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00007803 } else {
7804 // No viable function; try to create a built-in operation, which will
7805 // produce an error. Then, show the non-viable candidates.
7806 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00007807 }
Douglas Gregor33074752009-09-30 21:46:01 +00007808 assert(Result.isInvalid() &&
7809 "C++ binary operator overloading is missing candidates!");
7810 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00007811 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7812 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00007813 return move(Result);
7814 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007815
7816 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00007817 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +00007818 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00007819 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007820 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007821 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7822 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007823 return ExprError();
7824
7825 case OR_Deleted:
7826 Diag(OpLoc, diag::err_ovl_deleted_oper)
7827 << Best->Function->isDeleted()
7828 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007829 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007830 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00007831 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00007832 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007833
Douglas Gregor33074752009-09-30 21:46:01 +00007834 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007835 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007836}
7837
John McCall60d7b3a2010-08-24 06:29:42 +00007838ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +00007839Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7840 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007841 Expr *Base, Expr *Idx) {
7842 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +00007843 DeclarationName OpName =
7844 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7845
7846 // If either side is type-dependent, create an appropriate dependent
7847 // expression.
7848 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7849
John McCallc373d482010-01-27 01:50:18 +00007850 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007851 // CHECKME: no 'operator' keyword?
7852 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7853 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00007854 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00007855 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007856 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007857 /*ADL*/ true, /*Overloaded*/ false,
7858 UnresolvedSetIterator(),
7859 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00007860 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00007861
Sebastian Redlf322ed62009-10-29 20:17:01 +00007862 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7863 Args, 2,
7864 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007865 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007866 RLoc));
7867 }
7868
John McCall0e800c92010-12-04 08:14:53 +00007869 if (Args[0]->getObjectKind() == OK_ObjCProperty)
7870 ConvertPropertyForRValue(Args[0]);
7871 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7872 ConvertPropertyForRValue(Args[1]);
7873
Sebastian Redlf322ed62009-10-29 20:17:01 +00007874 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007875 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007876
7877 // Subscript can only be overloaded as a member function.
7878
7879 // Add operator candidates that are member functions.
7880 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7881
7882 // Add builtin operator candidates.
7883 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7884
7885 // Perform overload resolution.
7886 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007887 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00007888 case OR_Success: {
7889 // We found a built-in operator or an overloaded operator.
7890 FunctionDecl *FnDecl = Best->Function;
7891
7892 if (FnDecl) {
7893 // We matched an overloaded operator. Build a call to that
7894 // operator.
7895
John McCall9aa472c2010-03-19 07:35:19 +00007896 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007897 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00007898
Sebastian Redlf322ed62009-10-29 20:17:01 +00007899 // Convert the arguments.
7900 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007901 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007902 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007903 return ExprError();
7904
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007905 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007906 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007907 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007908 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007909 FnDecl->getParamDecl(0)),
7910 SourceLocation(),
7911 Owned(Args[1]));
7912 if (InputInit.isInvalid())
7913 return ExprError();
7914
7915 Args[1] = InputInit.takeAs<Expr>();
7916
Sebastian Redlf322ed62009-10-29 20:17:01 +00007917 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +00007918 QualType ResultTy = FnDecl->getResultType();
7919 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7920 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007921
7922 // Build the actual expression node.
John McCallf89e55a2010-11-18 06:31:45 +00007923 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007924
John McCall9ae2f072010-08-23 23:25:46 +00007925 CXXOperatorCallExpr *TheCall =
7926 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7927 FnExpr, Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +00007928 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007929
John McCall9ae2f072010-08-23 23:25:46 +00007930 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007931 FnDecl))
7932 return ExprError();
7933
John McCall9ae2f072010-08-23 23:25:46 +00007934 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007935 } else {
7936 // We matched a built-in operator. Convert the arguments, then
7937 // break out so that we will build the appropriate built-in
7938 // operator node.
7939 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007940 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00007941 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007942 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007943 return ExprError();
7944
7945 break;
7946 }
7947 }
7948
7949 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00007950 if (CandidateSet.empty())
7951 Diag(LLoc, diag::err_ovl_no_oper)
7952 << Args[0]->getType() << /*subscript*/ 0
7953 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7954 else
7955 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7956 << Args[0]->getType()
7957 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007958 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7959 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +00007960 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00007961 }
7962
7963 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00007964 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
7965 << "[]"
7966 << Args[0]->getType() << Args[1]->getType()
7967 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007968 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7969 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007970 return ExprError();
7971
7972 case OR_Deleted:
7973 Diag(LLoc, diag::err_ovl_deleted_oper)
7974 << Best->Function->isDeleted() << "[]"
7975 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007976 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7977 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007978 return ExprError();
7979 }
7980
7981 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +00007982 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007983}
7984
Douglas Gregor88a35142008-12-22 05:46:06 +00007985/// BuildCallToMemberFunction - Build a call to a member
7986/// function. MemExpr is the expression that refers to the member
7987/// function (and includes the object parameter), Args/NumArgs are the
7988/// arguments to the function call (not including the object
7989/// parameter). The caller needs to validate that the member
7990/// expression refers to a member function or an overloaded member
7991/// function.
John McCall60d7b3a2010-08-24 06:29:42 +00007992ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007993Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7994 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +00007995 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007996 // Dig out the member expression. This holds both the object
7997 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00007998 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7999
John McCall129e2df2009-11-30 22:42:35 +00008000 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00008001 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00008002 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00008003 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00008004 if (isa<MemberExpr>(NakedMemExpr)) {
8005 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00008006 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00008007 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00008008 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00008009 } else {
8010 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00008011 Qualifier = UnresExpr->getQualifier();
8012
John McCall701c89e2009-12-03 04:06:58 +00008013 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00008014 Expr::Classification ObjectClassification
8015 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
8016 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +00008017
Douglas Gregor88a35142008-12-22 05:46:06 +00008018 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00008019 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00008020
John McCallaa81e162009-12-01 22:10:20 +00008021 // FIXME: avoid copy.
8022 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8023 if (UnresExpr->hasExplicitTemplateArgs()) {
8024 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8025 TemplateArgs = &TemplateArgsBuffer;
8026 }
8027
John McCall129e2df2009-11-30 22:42:35 +00008028 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
8029 E = UnresExpr->decls_end(); I != E; ++I) {
8030
John McCall701c89e2009-12-03 04:06:58 +00008031 NamedDecl *Func = *I;
8032 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
8033 if (isa<UsingShadowDecl>(Func))
8034 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
8035
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00008036
Francois Pichetdbee3412011-01-18 05:04:39 +00008037 // Microsoft supports direct constructor calls.
8038 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
8039 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
8040 CandidateSet);
8041 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00008042 // If explicit template arguments were provided, we can't call a
8043 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00008044 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00008045 continue;
8046
John McCall9aa472c2010-03-19 07:35:19 +00008047 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00008048 ObjectClassification,
8049 Args, NumArgs, CandidateSet,
8050 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00008051 } else {
John McCall129e2df2009-11-30 22:42:35 +00008052 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00008053 I.getPair(), ActingDC, TemplateArgs,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00008054 ObjectType, ObjectClassification,
8055 Args, NumArgs, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +00008056 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00008057 }
Douglas Gregordec06662009-08-21 18:42:58 +00008058 }
Mike Stump1eb44332009-09-09 15:08:12 +00008059
John McCall129e2df2009-11-30 22:42:35 +00008060 DeclarationName DeclName = UnresExpr->getMemberName();
8061
Douglas Gregor88a35142008-12-22 05:46:06 +00008062 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008063 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +00008064 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00008065 case OR_Success:
8066 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00008067 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00008068 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008069 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00008070 break;
8071
8072 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00008073 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00008074 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00008075 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008076 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00008077 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00008078 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00008079
8080 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00008081 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00008082 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008083 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00008084 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00008085 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008086
8087 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00008088 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008089 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00008090 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008091 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008092 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00008093 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00008094 }
8095
John McCall6bb80172010-03-30 21:47:33 +00008096 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00008097
John McCallaa81e162009-12-01 22:10:20 +00008098 // If overload resolution picked a static member, build a
8099 // non-member call based on that function.
8100 if (Method->isStatic()) {
8101 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8102 Args, NumArgs, RParenLoc);
8103 }
8104
John McCall129e2df2009-11-30 22:42:35 +00008105 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00008106 }
8107
John McCallf89e55a2010-11-18 06:31:45 +00008108 QualType ResultType = Method->getResultType();
8109 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8110 ResultType = ResultType.getNonLValueExprType(Context);
8111
Douglas Gregor88a35142008-12-22 05:46:06 +00008112 assert(Method && "Member call to something that isn't a method?");
John McCall9ae2f072010-08-23 23:25:46 +00008113 CXXMemberCallExpr *TheCall =
8114 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +00008115 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +00008116
Anders Carlssoneed3e692009-10-10 00:06:20 +00008117 // Check for a valid return type.
8118 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +00008119 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +00008120 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00008121
Douglas Gregor88a35142008-12-22 05:46:06 +00008122 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00008123 // We only need to do this if there was actually an overload; otherwise
8124 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00008125 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00008126 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00008127 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
8128 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00008129 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00008130 MemExpr->setBase(ObjectArg);
8131
8132 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +00008133 const FunctionProtoType *Proto =
8134 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +00008135 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00008136 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00008137 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00008138
John McCall9ae2f072010-08-23 23:25:46 +00008139 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +00008140 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00008141
John McCall9ae2f072010-08-23 23:25:46 +00008142 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +00008143}
8144
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008145/// BuildCallToObjectOfClassType - Build a call to an object of class
8146/// type (C++ [over.call.object]), which can end up invoking an
8147/// overloaded function call operator (@c operator()) or performing a
8148/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +00008149ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00008150Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00008151 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008152 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008153 SourceLocation RParenLoc) {
John McCall0e800c92010-12-04 08:14:53 +00008154 if (Object->getObjectKind() == OK_ObjCProperty)
8155 ConvertPropertyForRValue(Object);
8156
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008157 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00008158 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00008159
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008160 // C++ [over.call.object]p1:
8161 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00008162 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008163 // candidate functions includes at least the function call
8164 // operators of T. The function call operators of T are obtained by
8165 // ordinary lookup of the name operator() in the context of
8166 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00008167 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00008168 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00008169
8170 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008171 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00008172 << Object->getSourceRange()))
8173 return true;
8174
John McCalla24dc2e2009-11-17 02:14:36 +00008175 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8176 LookupQualifiedName(R, Record->getDecl());
8177 R.suppressDiagnostics();
8178
Douglas Gregor593564b2009-11-15 07:48:03 +00008179 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00008180 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00008181 AddMethodCandidate(Oper.getPair(), Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00008182 Object->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00008183 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00008184 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00008185
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008186 // C++ [over.call.object]p2:
8187 // In addition, for each conversion function declared in T of the
8188 // form
8189 //
8190 // operator conversion-type-id () cv-qualifier;
8191 //
8192 // where cv-qualifier is the same cv-qualification as, or a
8193 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00008194 // denotes the type "pointer to function of (P1,...,Pn) returning
8195 // R", or the type "reference to pointer to function of
8196 // (P1,...,Pn) returning R", or the type "reference to function
8197 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008198 // is also considered as a candidate function. Similarly,
8199 // surrogate call functions are added to the set of candidate
8200 // functions for each conversion function declared in an
8201 // accessible base class provided the function is not hidden
8202 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00008203 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00008204 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00008205 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00008206 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00008207 NamedDecl *D = *I;
8208 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8209 if (isa<UsingShadowDecl>(D))
8210 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8211
Douglas Gregor4a27d702009-10-21 06:18:39 +00008212 // Skip over templated conversion functions; they aren't
8213 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00008214 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00008215 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00008216
John McCall701c89e2009-12-03 04:06:58 +00008217 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00008218
Douglas Gregor4a27d702009-10-21 06:18:39 +00008219 // Strip the reference type (if any) and then the pointer type (if
8220 // any) to get down to what might be a function type.
8221 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8222 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8223 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008224
Douglas Gregor4a27d702009-10-21 06:18:39 +00008225 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00008226 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00008227 Object, Args, NumArgs, CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008228 }
Mike Stump1eb44332009-09-09 15:08:12 +00008229
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008230 // Perform overload resolution.
8231 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008232 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
8233 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008234 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008235 // Overload resolution succeeded; we'll build the appropriate call
8236 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008237 break;
8238
8239 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00008240 if (CandidateSet.empty())
8241 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8242 << Object->getType() << /*call*/ 1
8243 << Object->getSourceRange();
8244 else
8245 Diag(Object->getSourceRange().getBegin(),
8246 diag::err_ovl_no_viable_object_call)
8247 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008248 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008249 break;
8250
8251 case OR_Ambiguous:
8252 Diag(Object->getSourceRange().getBegin(),
8253 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00008254 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008255 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008256 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008257
8258 case OR_Deleted:
8259 Diag(Object->getSourceRange().getBegin(),
8260 diag::err_ovl_deleted_object_call)
8261 << Best->Function->isDeleted()
8262 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008263 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008264 break;
Mike Stump1eb44332009-09-09 15:08:12 +00008265 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008266
Douglas Gregorff331c12010-07-25 18:17:45 +00008267 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008268 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008269
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008270 if (Best->Function == 0) {
8271 // Since there is no function declaration, this is one of the
8272 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00008273 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008274 = cast<CXXConversionDecl>(
8275 Best->Conversions[0].UserDefined.ConversionFunction);
8276
John McCall9aa472c2010-03-19 07:35:19 +00008277 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008278 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00008279
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008280 // We selected one of the surrogate functions that converts the
8281 // object parameter to a function pointer. Perform the conversion
8282 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00008283
8284 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00008285 // and then call it.
Douglas Gregorf2ae5262011-01-20 00:18:04 +00008286 ExprResult Call = BuildCXXMemberCallExpr(Object, Best->FoundDecl, Conv);
8287 if (Call.isInvalid())
8288 return ExprError();
8289
8290 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008291 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008292 }
8293
John McCall9aa472c2010-03-19 07:35:19 +00008294 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008295 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00008296
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008297 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8298 // that calls this method, using Object for the implicit object
8299 // parameter and passing along the remaining arguments.
8300 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +00008301 const FunctionProtoType *Proto =
8302 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008303
8304 unsigned NumArgsInProto = Proto->getNumArgs();
8305 unsigned NumArgsToCheck = NumArgs;
8306
8307 // Build the full argument list for the method call (the
8308 // implicit object parameter is placed at the beginning of the
8309 // list).
8310 Expr **MethodArgs;
8311 if (NumArgs < NumArgsInProto) {
8312 NumArgsToCheck = NumArgsInProto;
8313 MethodArgs = new Expr*[NumArgsInProto + 1];
8314 } else {
8315 MethodArgs = new Expr*[NumArgs + 1];
8316 }
8317 MethodArgs[0] = Object;
8318 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8319 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00008320
John McCallf89e55a2010-11-18 06:31:45 +00008321 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008322
8323 // Once we've built TheCall, all of the expressions are properly
8324 // owned.
John McCallf89e55a2010-11-18 06:31:45 +00008325 QualType ResultTy = Method->getResultType();
8326 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8327 ResultTy = ResultTy.getNonLValueExprType(Context);
8328
John McCall9ae2f072010-08-23 23:25:46 +00008329 CXXOperatorCallExpr *TheCall =
8330 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
8331 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +00008332 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008333 delete [] MethodArgs;
8334
John McCall9ae2f072010-08-23 23:25:46 +00008335 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +00008336 Method))
8337 return true;
8338
Douglas Gregor518fda12009-01-13 05:10:00 +00008339 // We may have default arguments. If so, we need to allocate more
8340 // slots in the call for them.
8341 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00008342 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00008343 else if (NumArgs > NumArgsInProto)
8344 NumArgsToCheck = NumArgsInProto;
8345
Chris Lattner312531a2009-04-12 08:11:20 +00008346 bool IsError = false;
8347
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008348 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00008349 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00008350 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008351 TheCall->setArg(0, Object);
8352
Chris Lattner312531a2009-04-12 08:11:20 +00008353
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008354 // Check the argument types.
8355 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008356 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00008357 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008358 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00008359
Douglas Gregor518fda12009-01-13 05:10:00 +00008360 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00008361
John McCall60d7b3a2010-08-24 06:29:42 +00008362 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +00008363 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00008364 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +00008365 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +00008366 SourceLocation(), Arg);
Anders Carlsson3faa4862010-01-29 18:43:53 +00008367
8368 IsError |= InputInit.isInvalid();
8369 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00008370 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00008371 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +00008372 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8373 if (DefArg.isInvalid()) {
8374 IsError = true;
8375 break;
8376 }
8377
8378 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00008379 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008380
8381 TheCall->setArg(i + 1, Arg);
8382 }
8383
8384 // If this is a variadic call, handle args passed through "...".
8385 if (Proto->isVariadic()) {
8386 // Promote the arguments (C99 6.5.2.2p7).
8387 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8388 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00008389 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008390 TheCall->setArg(i + 1, Arg);
8391 }
8392 }
8393
Chris Lattner312531a2009-04-12 08:11:20 +00008394 if (IsError) return true;
8395
John McCall9ae2f072010-08-23 23:25:46 +00008396 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00008397 return true;
8398
John McCall182f7092010-08-24 06:09:16 +00008399 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008400}
8401
Douglas Gregor8ba10742008-11-20 16:27:02 +00008402/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00008403/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00008404/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +00008405ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008406Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008407 assert(Base->getType()->isRecordType() &&
8408 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00008409
John McCall0e800c92010-12-04 08:14:53 +00008410 if (Base->getObjectKind() == OK_ObjCProperty)
8411 ConvertPropertyForRValue(Base);
8412
John McCall5769d612010-02-08 23:07:23 +00008413 SourceLocation Loc = Base->getExprLoc();
8414
Douglas Gregor8ba10742008-11-20 16:27:02 +00008415 // C++ [over.ref]p1:
8416 //
8417 // [...] An expression x->m is interpreted as (x.operator->())->m
8418 // for a class object x of type T if T::operator->() exists and if
8419 // the operator is selected as the best match function by the
8420 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +00008421 DeclarationName OpName =
8422 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00008423 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00008424 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008425
John McCall5769d612010-02-08 23:07:23 +00008426 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00008427 PDiag(diag::err_typecheck_incomplete_tag)
8428 << Base->getSourceRange()))
8429 return ExprError();
8430
John McCalla24dc2e2009-11-17 02:14:36 +00008431 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8432 LookupQualifiedName(R, BaseRecord->getDecl());
8433 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00008434
8435 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00008436 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00008437 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
8438 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00008439 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00008440
8441 // Perform overload resolution.
8442 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008443 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00008444 case OR_Success:
8445 // Overload resolution succeeded; we'll build the call below.
8446 break;
8447
8448 case OR_No_Viable_Function:
8449 if (CandidateSet.empty())
8450 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008451 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00008452 else
8453 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008454 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008455 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008456 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00008457
8458 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00008459 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8460 << "->" << Base->getType() << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008461 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008462 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008463
8464 case OR_Deleted:
8465 Diag(OpLoc, diag::err_ovl_deleted_oper)
8466 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00008467 << "->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008468 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008469 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00008470 }
8471
John McCall9aa472c2010-03-19 07:35:19 +00008472 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008473 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00008474
Douglas Gregor8ba10742008-11-20 16:27:02 +00008475 // Convert the object parameter.
8476 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00008477 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8478 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008479 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00008480
Douglas Gregor8ba10742008-11-20 16:27:02 +00008481 // Build the operator call.
John McCallf89e55a2010-11-18 06:31:45 +00008482 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
Anders Carlsson15ea3782009-10-13 22:43:21 +00008483
John McCallf89e55a2010-11-18 06:31:45 +00008484 QualType ResultTy = Method->getResultType();
8485 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8486 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +00008487 CXXOperatorCallExpr *TheCall =
8488 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008489 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00008490
John McCall9ae2f072010-08-23 23:25:46 +00008491 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00008492 Method))
8493 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00008494 return Owned(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00008495}
8496
Douglas Gregor904eed32008-11-10 20:40:00 +00008497/// FixOverloadedFunctionReference - E is an expression that refers to
8498/// a C++ overloaded function (possibly with some parentheses and
8499/// perhaps a '&' around it). We have resolved the overloaded function
8500/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00008501/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00008502Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00008503 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00008504 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00008505 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8506 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00008507 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008508 return PE;
Douglas Gregor699ee522009-11-20 19:42:02 +00008509
8510 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8511 }
8512
8513 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00008514 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8515 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00008516 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00008517 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00008518 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +00008519 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +00008520 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008521 return ICE;
Douglas Gregor699ee522009-11-20 19:42:02 +00008522
John McCallf871d0c2010-08-07 06:22:56 +00008523 return ImplicitCastExpr::Create(Context, ICE->getType(),
8524 ICE->getCastKind(),
8525 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00008526 ICE->getValueKind());
Douglas Gregor699ee522009-11-20 19:42:02 +00008527 }
8528
8529 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00008530 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00008531 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00008532 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8533 if (Method->isStatic()) {
8534 // Do nothing: static member functions aren't any different
8535 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00008536 } else {
John McCallf7a1a742009-11-24 19:00:30 +00008537 // Fix the sub expression, which really has to be an
8538 // UnresolvedLookupExpr holding an overloaded member function
8539 // or template.
John McCall6bb80172010-03-30 21:47:33 +00008540 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8541 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00008542 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008543 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +00008544
John McCallba135432009-11-21 08:51:07 +00008545 assert(isa<DeclRefExpr>(SubExpr)
8546 && "fixed to something other than a decl ref");
8547 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8548 && "fixed to a member ref with no nested name qualifier");
8549
8550 // We have taken the address of a pointer to member
8551 // function. Perform the computation here so that we get the
8552 // appropriate pointer to member type.
8553 QualType ClassType
8554 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8555 QualType MemPtrType
8556 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8557
John McCallf89e55a2010-11-18 06:31:45 +00008558 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8559 VK_RValue, OK_Ordinary,
8560 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00008561 }
8562 }
John McCall6bb80172010-03-30 21:47:33 +00008563 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8564 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00008565 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008566 return UnOp;
Anders Carlsson96ad5332009-10-21 17:16:23 +00008567
John McCall2de56d12010-08-25 11:45:40 +00008568 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +00008569 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00008570 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +00008571 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00008572 }
John McCallba135432009-11-21 08:51:07 +00008573
8574 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00008575 // FIXME: avoid copy.
8576 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00008577 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00008578 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8579 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00008580 }
8581
John McCallba135432009-11-21 08:51:07 +00008582 return DeclRefExpr::Create(Context,
8583 ULE->getQualifier(),
8584 ULE->getQualifierRange(),
8585 Fn,
8586 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00008587 Fn->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008588 VK_LValue,
John McCallaa81e162009-12-01 22:10:20 +00008589 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00008590 }
8591
John McCall129e2df2009-11-30 22:42:35 +00008592 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00008593 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00008594 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8595 if (MemExpr->hasExplicitTemplateArgs()) {
8596 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8597 TemplateArgs = &TemplateArgsBuffer;
8598 }
John McCalld5532b62009-11-23 01:53:49 +00008599
John McCallaa81e162009-12-01 22:10:20 +00008600 Expr *Base;
8601
John McCallf89e55a2010-11-18 06:31:45 +00008602 // If we're filling in a static method where we used to have an
8603 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +00008604 if (MemExpr->isImplicitAccess()) {
8605 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8606 return DeclRefExpr::Create(Context,
8607 MemExpr->getQualifier(),
8608 MemExpr->getQualifierRange(),
8609 Fn,
8610 MemExpr->getMemberLoc(),
8611 Fn->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008612 VK_LValue,
John McCallaa81e162009-12-01 22:10:20 +00008613 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00008614 } else {
8615 SourceLocation Loc = MemExpr->getMemberLoc();
8616 if (MemExpr->getQualifier())
8617 Loc = MemExpr->getQualifierRange().getBegin();
8618 Base = new (Context) CXXThisExpr(Loc,
8619 MemExpr->getBaseType(),
8620 /*isImplicit=*/true);
8621 }
John McCallaa81e162009-12-01 22:10:20 +00008622 } else
John McCall3fa5cae2010-10-26 07:05:15 +00008623 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +00008624
8625 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00008626 MemExpr->isArrow(),
8627 MemExpr->getQualifier(),
8628 MemExpr->getQualifierRange(),
8629 Fn,
John McCall6bb80172010-03-30 21:47:33 +00008630 Found,
Abramo Bagnara25777432010-08-11 22:01:17 +00008631 MemExpr->getMemberNameInfo(),
John McCallaa81e162009-12-01 22:10:20 +00008632 TemplateArgs,
John McCallf89e55a2010-11-18 06:31:45 +00008633 Fn->getType(),
8634 cast<CXXMethodDecl>(Fn)->isStatic()
8635 ? VK_LValue : VK_RValue,
8636 OK_Ordinary);
Douglas Gregor699ee522009-11-20 19:42:02 +00008637 }
8638
John McCall3fa5cae2010-10-26 07:05:15 +00008639 llvm_unreachable("Invalid reference to overloaded function");
8640 return E;
Douglas Gregor904eed32008-11-10 20:40:00 +00008641}
8642
John McCall60d7b3a2010-08-24 06:29:42 +00008643ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8644 DeclAccessPair Found,
8645 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00008646 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00008647}
8648
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008649} // end namespace clang