blob: 6dcb6b01f3d129286e72474daa749b545c240d68 [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
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000019#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000020#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000021#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000023#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000024#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000025#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000026#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000027#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000029#include <algorithm>
30
31namespace clang {
32
John McCall120d63c2010-08-24 20:38:10 +000033static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
34 bool InOverloadResolution,
35 StandardConversionSequence &SCS);
36static OverloadingResult
37IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
38 UserDefinedConversionSequence& User,
39 OverloadCandidateSet& Conversions,
40 bool AllowExplicit);
41
42
43static ImplicitConversionSequence::CompareKind
44CompareStandardConversionSequences(Sema &S,
45 const StandardConversionSequence& SCS1,
46 const StandardConversionSequence& SCS2);
47
48static ImplicitConversionSequence::CompareKind
49CompareQualificationConversions(Sema &S,
50 const StandardConversionSequence& SCS1,
51 const StandardConversionSequence& SCS2);
52
53static ImplicitConversionSequence::CompareKind
54CompareDerivedToBaseConversions(Sema &S,
55 const StandardConversionSequence& SCS1,
56 const StandardConversionSequence& SCS2);
57
58
59
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000060/// GetConversionCategory - Retrieve the implicit conversion
61/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000062ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000063GetConversionCategory(ImplicitConversionKind Kind) {
64 static const ImplicitConversionCategory
65 Category[(int)ICK_Num_Conversion_Kinds] = {
66 ICC_Identity,
67 ICC_Lvalue_Transformation,
68 ICC_Lvalue_Transformation,
69 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000070 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000071 ICC_Qualification_Adjustment,
72 ICC_Promotion,
73 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000074 ICC_Promotion,
75 ICC_Conversion,
76 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000077 ICC_Conversion,
78 ICC_Conversion,
79 ICC_Conversion,
80 ICC_Conversion,
81 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000082 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000083 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +000084 ICC_Conversion,
85 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000086 ICC_Conversion
87 };
88 return Category[(int)Kind];
89}
90
91/// GetConversionRank - Retrieve the implicit conversion rank
92/// corresponding to the given implicit conversion kind.
93ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
94 static const ImplicitConversionRank
95 Rank[(int)ICK_Num_Conversion_Kinds] = {
96 ICR_Exact_Match,
97 ICR_Exact_Match,
98 ICR_Exact_Match,
99 ICR_Exact_Match,
100 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000101 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000102 ICR_Promotion,
103 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000104 ICR_Promotion,
105 ICR_Conversion,
106 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000107 ICR_Conversion,
108 ICR_Conversion,
109 ICR_Conversion,
110 ICR_Conversion,
111 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000112 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000113 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000114 ICR_Conversion,
115 ICR_Conversion,
Chandler Carruth23a370f2010-02-25 07:20:54 +0000116 ICR_Complex_Real_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000117 };
118 return Rank[(int)Kind];
119}
120
121/// GetImplicitConversionName - Return the name of this kind of
122/// implicit conversion.
123const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000124 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000125 "No conversion",
126 "Lvalue-to-rvalue",
127 "Array-to-pointer",
128 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000129 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000130 "Qualification",
131 "Integral promotion",
132 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000133 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000134 "Integral conversion",
135 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000136 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000137 "Floating-integral conversion",
138 "Pointer conversion",
139 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000140 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000141 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000142 "Derived-to-base conversion",
143 "Vector conversion",
144 "Vector splat",
145 "Complex-real conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000146 };
147 return Name[Kind];
148}
149
Douglas Gregor60d62c22008-10-31 16:23:19 +0000150/// StandardConversionSequence - Set the standard conversion
151/// sequence to the identity conversion.
152void StandardConversionSequence::setAsIdentityConversion() {
153 First = ICK_Identity;
154 Second = ICK_Identity;
155 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000156 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000157 ReferenceBinding = false;
158 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000159 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000160 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000161}
162
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000163/// getRank - Retrieve the rank of this standard conversion sequence
164/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
165/// implicit conversions.
166ImplicitConversionRank StandardConversionSequence::getRank() const {
167 ImplicitConversionRank Rank = ICR_Exact_Match;
168 if (GetConversionRank(First) > Rank)
169 Rank = GetConversionRank(First);
170 if (GetConversionRank(Second) > Rank)
171 Rank = GetConversionRank(Second);
172 if (GetConversionRank(Third) > Rank)
173 Rank = GetConversionRank(Third);
174 return Rank;
175}
176
177/// isPointerConversionToBool - Determines whether this conversion is
178/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000179/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000180/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000181bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182 // Note that FromType has not necessarily been transformed by the
183 // array-to-pointer or function-to-pointer implicit conversions, so
184 // check for their presence as well as checking whether FromType is
185 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000186 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000187 (getFromType()->isPointerType() ||
188 getFromType()->isObjCObjectPointerType() ||
189 getFromType()->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000190 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
191 return true;
192
193 return false;
194}
195
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000196/// isPointerConversionToVoidPointer - Determines whether this
197/// conversion is a conversion of a pointer to a void pointer. This is
198/// used as part of the ranking of standard conversion sequences (C++
199/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000200bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000201StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000202isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000203 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000204 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000205
206 // Note that FromType has not necessarily been transformed by the
207 // array-to-pointer implicit conversion, so check for its presence
208 // and redo the conversion to get a pointer.
209 if (First == ICK_Array_To_Pointer)
210 FromType = Context.getArrayDecayedType(FromType);
211
Douglas Gregor01919692009-12-13 21:37:05 +0000212 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000213 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000214 return ToPtrType->getPointeeType()->isVoidType();
215
216 return false;
217}
218
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000219/// DebugPrint - Print this standard conversion sequence to standard
220/// error. Useful for debugging overloading issues.
221void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000222 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000223 bool PrintedSomething = false;
224 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000225 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000226 PrintedSomething = true;
227 }
228
229 if (Second != ICK_Identity) {
230 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000231 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000232 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000233 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000234
235 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000236 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000237 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000238 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000239 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000240 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000241 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000242 PrintedSomething = true;
243 }
244
245 if (Third != ICK_Identity) {
246 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000247 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000248 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000249 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000250 PrintedSomething = true;
251 }
252
253 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000254 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000255 }
256}
257
258/// DebugPrint - Print this user-defined conversion sequence to standard
259/// error. Useful for debugging overloading issues.
260void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000261 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000262 if (Before.First || Before.Second || Before.Third) {
263 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000264 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000265 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000266 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000267 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000268 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000269 After.DebugPrint();
270 }
271}
272
273/// DebugPrint - Print this implicit conversion sequence to standard
274/// error. Useful for debugging overloading issues.
275void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000276 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000277 switch (ConversionKind) {
278 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000279 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000280 Standard.DebugPrint();
281 break;
282 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000283 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000284 UserDefined.DebugPrint();
285 break;
286 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000287 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000288 break;
John McCall1d318332010-01-12 00:44:57 +0000289 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000290 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000291 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000292 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000293 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000294 break;
295 }
296
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000297 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000298}
299
John McCall1d318332010-01-12 00:44:57 +0000300void AmbiguousConversionSequence::construct() {
301 new (&conversions()) ConversionSet();
302}
303
304void AmbiguousConversionSequence::destruct() {
305 conversions().~ConversionSet();
306}
307
308void
309AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
310 FromTypePtr = O.FromTypePtr;
311 ToTypePtr = O.ToTypePtr;
312 new (&conversions()) ConversionSet(O.conversions());
313}
314
Douglas Gregora9333192010-05-08 17:41:32 +0000315namespace {
316 // Structure used by OverloadCandidate::DeductionFailureInfo to store
317 // template parameter and template argument information.
318 struct DFIParamWithArguments {
319 TemplateParameter Param;
320 TemplateArgument FirstArg;
321 TemplateArgument SecondArg;
322 };
323}
324
325/// \brief Convert from Sema's representation of template deduction information
326/// to the form used in overload-candidate information.
327OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000328static MakeDeductionFailureInfo(ASTContext &Context,
329 Sema::TemplateDeductionResult TDK,
Douglas Gregorec20f462010-05-08 20:07:26 +0000330 Sema::TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000331 OverloadCandidate::DeductionFailureInfo Result;
332 Result.Result = static_cast<unsigned>(TDK);
333 Result.Data = 0;
334 switch (TDK) {
335 case Sema::TDK_Success:
336 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000337 case Sema::TDK_TooManyArguments:
338 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000339 break;
340
341 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000342 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000343 Result.Data = Info.Param.getOpaqueValue();
344 break;
345
Douglas Gregora9333192010-05-08 17:41:32 +0000346 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000347 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000348 // FIXME: Should allocate from normal heap so that we can free this later.
349 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000350 Saved->Param = Info.Param;
351 Saved->FirstArg = Info.FirstArg;
352 Saved->SecondArg = Info.SecondArg;
353 Result.Data = Saved;
354 break;
355 }
356
357 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000358 Result.Data = Info.take();
359 break;
360
Douglas Gregora9333192010-05-08 17:41:32 +0000361 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000362 case Sema::TDK_FailedOverloadResolution:
363 break;
364 }
365
366 return Result;
367}
John McCall1d318332010-01-12 00:44:57 +0000368
Douglas Gregora9333192010-05-08 17:41:32 +0000369void OverloadCandidate::DeductionFailureInfo::Destroy() {
370 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
371 case Sema::TDK_Success:
372 case Sema::TDK_InstantiationDepth:
373 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000374 case Sema::TDK_TooManyArguments:
375 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000376 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000377 break;
378
Douglas Gregora9333192010-05-08 17:41:32 +0000379 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000380 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000381 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000382 Data = 0;
383 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000384
385 case Sema::TDK_SubstitutionFailure:
386 // FIXME: Destroy the template arugment list?
387 Data = 0;
388 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000389
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000390 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000391 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000392 case Sema::TDK_FailedOverloadResolution:
393 break;
394 }
395}
396
397TemplateParameter
398OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
399 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
400 case Sema::TDK_Success:
401 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000402 case Sema::TDK_TooManyArguments:
403 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000404 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000405 return TemplateParameter();
406
407 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000408 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000409 return TemplateParameter::getFromOpaqueValue(Data);
410
411 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000412 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000413 return static_cast<DFIParamWithArguments*>(Data)->Param;
414
415 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000416 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000417 case Sema::TDK_FailedOverloadResolution:
418 break;
419 }
420
421 return TemplateParameter();
422}
Douglas Gregorec20f462010-05-08 20:07:26 +0000423
424TemplateArgumentList *
425OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
426 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
427 case Sema::TDK_Success:
428 case Sema::TDK_InstantiationDepth:
429 case Sema::TDK_TooManyArguments:
430 case Sema::TDK_TooFewArguments:
431 case Sema::TDK_Incomplete:
432 case Sema::TDK_InvalidExplicitArguments:
433 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000434 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000435 return 0;
436
437 case Sema::TDK_SubstitutionFailure:
438 return static_cast<TemplateArgumentList*>(Data);
439
440 // Unhandled
441 case Sema::TDK_NonDeducedMismatch:
442 case Sema::TDK_FailedOverloadResolution:
443 break;
444 }
445
446 return 0;
447}
448
Douglas Gregora9333192010-05-08 17:41:32 +0000449const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
450 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
451 case Sema::TDK_Success:
452 case Sema::TDK_InstantiationDepth:
453 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000454 case Sema::TDK_TooManyArguments:
455 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000456 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000457 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000458 return 0;
459
Douglas Gregora9333192010-05-08 17:41:32 +0000460 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000461 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000462 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
463
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000464 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000465 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000466 case Sema::TDK_FailedOverloadResolution:
467 break;
468 }
469
470 return 0;
471}
472
473const TemplateArgument *
474OverloadCandidate::DeductionFailureInfo::getSecondArg() {
475 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
476 case Sema::TDK_Success:
477 case Sema::TDK_InstantiationDepth:
478 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000479 case Sema::TDK_TooManyArguments:
480 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000481 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000482 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000483 return 0;
484
Douglas Gregora9333192010-05-08 17:41:32 +0000485 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000486 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000487 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
488
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000489 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000490 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000491 case Sema::TDK_FailedOverloadResolution:
492 break;
493 }
494
495 return 0;
496}
497
498void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000499 inherited::clear();
500 Functions.clear();
501}
502
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000503// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000504// overload of the declarations in Old. This routine returns false if
505// New and Old cannot be overloaded, e.g., if New has the same
506// signature as some function in Old (C++ 1.3.10) or if the Old
507// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000508// it does return false, MatchedDecl will point to the decl that New
509// cannot be overloaded with. This decl may be a UsingShadowDecl on
510// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000511//
512// Example: Given the following input:
513//
514// void f(int, float); // #1
515// void f(int, int); // #2
516// int f(int, int); // #3
517//
518// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000519// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000520//
John McCall51fa86f2009-12-02 08:47:38 +0000521// When we process #2, Old contains only the FunctionDecl for #1. By
522// comparing the parameter types, we see that #1 and #2 are overloaded
523// (since they have different signatures), so this routine returns
524// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000525//
John McCall51fa86f2009-12-02 08:47:38 +0000526// When we process #3, Old is an overload set containing #1 and #2. We
527// compare the signatures of #3 to #1 (they're overloaded, so we do
528// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
529// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000530// signature), IsOverload returns false and MatchedDecl will be set to
531// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000532//
533// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
534// into a class by a using declaration. The rules for whether to hide
535// shadow declarations ignore some properties which otherwise figure
536// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000537Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000538Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
539 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000540 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000541 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000542 NamedDecl *OldD = *I;
543
544 bool OldIsUsingDecl = false;
545 if (isa<UsingShadowDecl>(OldD)) {
546 OldIsUsingDecl = true;
547
548 // We can always introduce two using declarations into the same
549 // context, even if they have identical signatures.
550 if (NewIsUsingDecl) continue;
551
552 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
553 }
554
555 // If either declaration was introduced by a using declaration,
556 // we'll need to use slightly different rules for matching.
557 // Essentially, these rules are the normal rules, except that
558 // function templates hide function templates with different
559 // return types or template parameter lists.
560 bool UseMemberUsingDeclRules =
561 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
562
John McCall51fa86f2009-12-02 08:47:38 +0000563 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000564 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
565 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
566 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
567 continue;
568 }
569
John McCall871b2e72009-12-09 03:35:25 +0000570 Match = *I;
571 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000572 }
John McCall51fa86f2009-12-02 08:47:38 +0000573 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000574 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
575 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
576 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
577 continue;
578 }
579
John McCall871b2e72009-12-09 03:35:25 +0000580 Match = *I;
581 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000582 }
John McCall9f54ad42009-12-10 09:41:52 +0000583 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
584 // We can overload with these, which can show up when doing
585 // redeclaration checks for UsingDecls.
586 assert(Old.getLookupKind() == LookupUsingDeclName);
587 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
588 // Optimistically assume that an unresolved using decl will
589 // overload; if it doesn't, we'll have to diagnose during
590 // template instantiation.
591 } else {
John McCall68263142009-11-18 22:49:29 +0000592 // (C++ 13p1):
593 // Only function declarations can be overloaded; object and type
594 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000595 Match = *I;
596 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000597 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000598 }
John McCall68263142009-11-18 22:49:29 +0000599
John McCall871b2e72009-12-09 03:35:25 +0000600 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000601}
602
John McCallad00b772010-06-16 08:42:20 +0000603bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
604 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000605 // If both of the functions are extern "C", then they are not
606 // overloads.
607 if (Old->isExternC() && New->isExternC())
608 return false;
609
John McCall68263142009-11-18 22:49:29 +0000610 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
611 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
612
613 // C++ [temp.fct]p2:
614 // A function template can be overloaded with other function templates
615 // and with normal (non-template) functions.
616 if ((OldTemplate == 0) != (NewTemplate == 0))
617 return true;
618
619 // Is the function New an overload of the function Old?
620 QualType OldQType = Context.getCanonicalType(Old->getType());
621 QualType NewQType = Context.getCanonicalType(New->getType());
622
623 // Compare the signatures (C++ 1.3.10) of the two functions to
624 // determine whether they are overloads. If we find any mismatch
625 // in the signature, they are overloads.
626
627 // If either of these functions is a K&R-style function (no
628 // prototype), then we consider them to have matching signatures.
629 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
630 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
631 return false;
632
633 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
634 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
635
636 // The signature of a function includes the types of its
637 // parameters (C++ 1.3.10), which includes the presence or absence
638 // of the ellipsis; see C++ DR 357).
639 if (OldQType != NewQType &&
640 (OldType->getNumArgs() != NewType->getNumArgs() ||
641 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000642 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000643 return true;
644
645 // C++ [temp.over.link]p4:
646 // The signature of a function template consists of its function
647 // signature, its return type and its template parameter list. The names
648 // of the template parameters are significant only for establishing the
649 // relationship between the template parameters and the rest of the
650 // signature.
651 //
652 // We check the return type and template parameter lists for function
653 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000654 //
655 // However, we don't consider either of these when deciding whether
656 // a member introduced by a shadow declaration is hidden.
657 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000658 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
659 OldTemplate->getTemplateParameters(),
660 false, TPL_TemplateMatch) ||
661 OldType->getResultType() != NewType->getResultType()))
662 return true;
663
664 // If the function is a class member, its signature includes the
665 // cv-qualifiers (if any) on the function itself.
666 //
667 // As part of this, also check whether one of the member functions
668 // is static, in which case they are not overloads (C++
669 // 13.1p2). While not part of the definition of the signature,
670 // this check is important to determine whether these functions
671 // can be overloaded.
672 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
673 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
674 if (OldMethod && NewMethod &&
675 !OldMethod->isStatic() && !NewMethod->isStatic() &&
676 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
677 return true;
678
679 // The signatures match; this is not an overload.
680 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000681}
682
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000683/// TryImplicitConversion - Attempt to perform an implicit conversion
684/// from the given expression (Expr) to the given type (ToType). This
685/// function returns an implicit conversion sequence that can be used
686/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000687///
688/// void f(float f);
689/// void g(int i) { f(i); }
690///
691/// this routine would produce an implicit conversion sequence to
692/// describe the initialization of f from i, which will be a standard
693/// conversion sequence containing an lvalue-to-rvalue conversion (C++
694/// 4.1) followed by a floating-integral conversion (C++ 4.9).
695//
696/// Note that this routine only determines how the conversion can be
697/// performed; it does not actually perform the conversion. As such,
698/// it will not produce any diagnostics if no conversion is available,
699/// but will instead return an implicit conversion sequence of kind
700/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000701///
702/// If @p SuppressUserConversions, then user-defined conversions are
703/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000704/// If @p AllowExplicit, then explicit user-defined conversions are
705/// permitted.
John McCall120d63c2010-08-24 20:38:10 +0000706static ImplicitConversionSequence
707TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
708 bool SuppressUserConversions,
709 bool AllowExplicit,
710 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000711 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +0000712 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
713 ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000714 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000715 return ICS;
716 }
717
John McCall120d63c2010-08-24 20:38:10 +0000718 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000719 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000720 return ICS;
721 }
722
Douglas Gregor604eb652010-08-11 02:15:33 +0000723 // C++ [over.ics.user]p4:
724 // A conversion of an expression of class type to the same class
725 // type is given Exact Match rank, and a conversion of an
726 // expression of class type to a base class of that type is
727 // given Conversion rank, in spite of the fact that a copy/move
728 // constructor (i.e., a user-defined conversion function) is
729 // called for those cases.
730 QualType FromType = From->getType();
731 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +0000732 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
733 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000734 ICS.setStandard();
735 ICS.Standard.setAsIdentityConversion();
736 ICS.Standard.setFromType(FromType);
737 ICS.Standard.setAllToTypes(ToType);
738
739 // We don't actually check at this point whether there is a valid
740 // copy/move constructor, since overloading just assumes that it
741 // exists. When we actually perform initialization, we'll find the
742 // appropriate constructor to copy the returned object, if needed.
743 ICS.Standard.CopyConstructor = 0;
Douglas Gregor604eb652010-08-11 02:15:33 +0000744
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000745 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +0000746 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000747 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor604eb652010-08-11 02:15:33 +0000748
749 return ICS;
750 }
751
752 if (SuppressUserConversions) {
753 // We're not in the case above, so there is no conversion that
754 // we can perform.
755 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000756 return ICS;
757 }
758
759 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000760 OverloadCandidateSet Conversions(From->getExprLoc());
761 OverloadingResult UserDefResult
John McCall120d63c2010-08-24 20:38:10 +0000762 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000763 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000764
765 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000766 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000767 // C++ [over.ics.user]p4:
768 // A conversion of an expression of class type to the same class
769 // type is given Exact Match rank, and a conversion of an
770 // expression of class type to a base class of that type is
771 // given Conversion rank, in spite of the fact that a copy
772 // constructor (i.e., a user-defined conversion function) is
773 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000774 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000775 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000776 QualType FromCanon
John McCall120d63c2010-08-24 20:38:10 +0000777 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
778 QualType ToCanon
779 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000780 if (Constructor->isCopyConstructor() &&
John McCall120d63c2010-08-24 20:38:10 +0000781 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000782 // Turn this into a "standard" conversion sequence, so that it
783 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000784 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000785 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000786 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000787 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000788 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000789 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000790 ICS.Standard.Second = ICK_Derived_To_Base;
791 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000792 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000793
794 // C++ [over.best.ics]p4:
795 // However, when considering the argument of a user-defined
796 // conversion function that is a candidate by 13.3.1.3 when
797 // invoked for the copying of the temporary in the second step
798 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
799 // 13.3.1.6 in all cases, only standard conversion sequences and
800 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000801 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000802 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000803 }
John McCallcefd3ad2010-01-13 22:30:33 +0000804 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000805 ICS.setAmbiguous();
806 ICS.Ambiguous.setFromType(From->getType());
807 ICS.Ambiguous.setToType(ToType);
808 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
809 Cand != Conversions.end(); ++Cand)
810 if (Cand->Viable)
811 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000812 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000813 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000814 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000815
816 return ICS;
817}
818
John McCall120d63c2010-08-24 20:38:10 +0000819bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
820 const InitializedEntity &Entity,
821 Expr *Initializer,
822 bool SuppressUserConversions,
823 bool AllowExplicitConversions,
824 bool InOverloadResolution) {
825 ImplicitConversionSequence ICS
826 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
827 SuppressUserConversions,
828 AllowExplicitConversions,
829 InOverloadResolution);
830 if (ICS.isBad()) return true;
831
832 // Perform the actual conversion.
833 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
834 return false;
835}
836
Douglas Gregor575c63a2010-04-16 22:27:05 +0000837/// PerformImplicitConversion - Perform an implicit conversion of the
838/// expression From to the type ToType. Returns true if there was an
839/// error, false otherwise. The expression From is replaced with the
840/// converted expression. Flavor is the kind of conversion we're
841/// performing, used in the error message. If @p AllowExplicit,
842/// explicit user-defined conversions are permitted.
843bool
844Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
845 AssignmentAction Action, bool AllowExplicit) {
846 ImplicitConversionSequence ICS;
847 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
848}
849
850bool
851Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
852 AssignmentAction Action, bool AllowExplicit,
853 ImplicitConversionSequence& ICS) {
John McCall120d63c2010-08-24 20:38:10 +0000854 ICS = clang::TryImplicitConversion(*this, From, ToType,
855 /*SuppressUserConversions=*/false,
856 AllowExplicit,
857 /*InOverloadResolution=*/false);
Douglas Gregor575c63a2010-04-16 22:27:05 +0000858 return PerformImplicitConversion(From, ToType, ICS, Action);
859}
860
Douglas Gregor43c79c22009-12-09 00:47:37 +0000861/// \brief Determine whether the conversion from FromType to ToType is a valid
862/// conversion that strips "noreturn" off the nested function type.
863static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
864 QualType ToType, QualType &ResultTy) {
865 if (Context.hasSameUnqualifiedType(FromType, ToType))
866 return false;
867
868 // Strip the noreturn off the type we're converting from; noreturn can
869 // safely be removed.
870 FromType = Context.getNoReturnType(FromType, false);
871 if (!Context.hasSameUnqualifiedType(FromType, ToType))
872 return false;
873
874 ResultTy = FromType;
875 return true;
876}
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000877
878/// \brief Determine whether the conversion from FromType to ToType is a valid
879/// vector conversion.
880///
881/// \param ICK Will be set to the vector conversion kind, if this is a vector
882/// conversion.
883static bool IsVectorConversion(ASTContext &Context, QualType FromType,
884 QualType ToType, ImplicitConversionKind &ICK) {
885 // We need at least one of these types to be a vector type to have a vector
886 // conversion.
887 if (!ToType->isVectorType() && !FromType->isVectorType())
888 return false;
889
890 // Identical types require no conversions.
891 if (Context.hasSameUnqualifiedType(FromType, ToType))
892 return false;
893
894 // There are no conversions between extended vector types, only identity.
895 if (ToType->isExtVectorType()) {
896 // There are no conversions between extended vector types other than the
897 // identity conversion.
898 if (FromType->isExtVectorType())
899 return false;
900
901 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +0000902 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000903 ICK = ICK_Vector_Splat;
904 return true;
905 }
906 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000907
908 // We can perform the conversion between vector types in the following cases:
909 // 1)vector types are equivalent AltiVec and GCC vector types
910 // 2)lax vector conversions are permitted and the vector types are of the
911 // same size
912 if (ToType->isVectorType() && FromType->isVectorType()) {
913 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +0000914 (Context.getLangOptions().LaxVectorConversions &&
915 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +0000916 ICK = ICK_Vector_Conversion;
917 return true;
918 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000919 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000920
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000921 return false;
922}
Douglas Gregor43c79c22009-12-09 00:47:37 +0000923
Douglas Gregor60d62c22008-10-31 16:23:19 +0000924/// IsStandardConversion - Determines whether there is a standard
925/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
926/// expression From to the type ToType. Standard conversion sequences
927/// only consider non-class types; for conversions that involve class
928/// types, use TryImplicitConversion. If a conversion exists, SCS will
929/// contain the standard conversion sequence required to perform this
930/// conversion and this routine will return true. Otherwise, this
931/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +0000932static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
933 bool InOverloadResolution,
934 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000935 QualType FromType = From->getType();
John McCall120d63c2010-08-24 20:38:10 +0000936
Douglas Gregor60d62c22008-10-31 16:23:19 +0000937 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000938 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000939 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000940 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000941 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000942 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000943
Douglas Gregorf9201e02009-02-11 23:02:49 +0000944 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000945 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000946 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +0000947 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000948 return false;
949
Mike Stump1eb44332009-09-09 15:08:12 +0000950 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000951 }
952
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000953 // The first conversion can be an lvalue-to-rvalue conversion,
954 // array-to-pointer conversion, or function-to-pointer conversion
955 // (C++ 4p1).
956
John McCall120d63c2010-08-24 20:38:10 +0000957 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000958 DeclAccessPair AccessPair;
959 if (FunctionDecl *Fn
John McCall120d63c2010-08-24 20:38:10 +0000960 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
961 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000962 // We were able to resolve the address of the overloaded function,
963 // so we can convert to the type of that function.
964 FromType = Fn->getType();
965 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
966 if (!Method->isStatic()) {
967 Type *ClassType
John McCall120d63c2010-08-24 20:38:10 +0000968 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
969 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000970 }
971 }
972
973 // If the "from" expression takes the address of the overloaded
974 // function, update the type of the resulting expression accordingly.
975 if (FromType->getAs<FunctionType>())
976 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
977 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
John McCall120d63c2010-08-24 20:38:10 +0000978 FromType = S.Context.getPointerType(FromType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000979
980 // Check that we've computed the proper type after overload resolution.
John McCall120d63c2010-08-24 20:38:10 +0000981 assert(S.Context.hasSameType(FromType,
982 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000983 } else {
984 return false;
985 }
986 }
Mike Stump1eb44332009-09-09 15:08:12 +0000987 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000988 // An lvalue (3.10) of a non-function, non-array type T can be
989 // converted to an rvalue.
John McCall120d63c2010-08-24 20:38:10 +0000990 Expr::isLvalueResult argIsLvalue = From->isLvalue(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000991 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000992 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +0000993 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000994 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000995
996 // If T is a non-class type, the type of the rvalue is the
997 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000998 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
999 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001000 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001001 } else if (FromType->isArrayType()) {
1002 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001003 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001004
1005 // An lvalue or rvalue of type "array of N T" or "array of unknown
1006 // bound of T" can be converted to an rvalue of type "pointer to
1007 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001008 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001009
John McCall120d63c2010-08-24 20:38:10 +00001010 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001011 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001012 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001013
1014 // For the purpose of ranking in overload resolution
1015 // (13.3.3.1.1), this conversion is considered an
1016 // array-to-pointer conversion followed by a qualification
1017 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001018 SCS.Second = ICK_Identity;
1019 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +00001020 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001021 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001022 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001023 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
1024 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001025 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001026
1027 // An lvalue of function type T can be converted to an rvalue of
1028 // type "pointer to T." The result is a pointer to the
1029 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001030 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001031 } else {
1032 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001033 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001034 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001035 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001036
1037 // The second conversion can be an integral promotion, floating
1038 // point promotion, integral conversion, floating point conversion,
1039 // floating-integral conversion, pointer conversion,
1040 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001041 // For overloading in C, this can also be a "compatible-type"
1042 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001043 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001044 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001045 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001046 // The unqualified versions of the types are the same: there's no
1047 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001048 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001049 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001050 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001051 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001052 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001053 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001054 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001055 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001056 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001057 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001058 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001059 SCS.Second = ICK_Complex_Promotion;
1060 FromType = ToType.getUnqualifiedType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001061 } else if (FromType->isIntegralOrEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001062 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001063 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001064 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001065 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001066 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1067 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001068 SCS.Second = ICK_Complex_Conversion;
1069 FromType = ToType.getUnqualifiedType();
Chandler Carruth23a370f2010-02-25 07:20:54 +00001070 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1071 (ToType->isComplexType() && FromType->isArithmeticType())) {
1072 // Complex-real conversions (C99 6.3.1.7)
1073 SCS.Second = ICK_Complex_Real;
1074 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001075 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001076 // Floating point conversions (C++ 4.8).
1077 SCS.Second = ICK_Floating_Conversion;
1078 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001079 } else if ((FromType->isRealFloatingType() &&
John McCall120d63c2010-08-24 20:38:10 +00001080 ToType->isIntegralType(S.Context) && !ToType->isBooleanType()) ||
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001081 (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001082 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001083 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001084 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001085 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001086 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1087 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001088 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001089 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001090 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall120d63c2010-08-24 20:38:10 +00001091 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1092 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001093 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001094 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001095 } else if (ToType->isBooleanType() &&
1096 (FromType->isArithmeticType() ||
1097 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +00001098 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001099 FromType->isBlockPointerType() ||
1100 FromType->isMemberPointerType() ||
Douglas Gregor00619622010-06-22 23:41:02 +00001101 FromType->isNullPtrType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001102 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001103 SCS.Second = ICK_Boolean_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001104 FromType = S.Context.BoolTy;
1105 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001106 SCS.Second = SecondICK;
1107 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001108 } else if (!S.getLangOptions().CPlusPlus &&
1109 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001110 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001111 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001112 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001113 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001114 // Treat a conversion that strips "noreturn" as an identity conversion.
1115 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001116 } else {
1117 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001118 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001119 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001120 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001121
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001122 QualType CanonFrom;
1123 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001124 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall120d63c2010-08-24 20:38:10 +00001125 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001126 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001127 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001128 CanonFrom = S.Context.getCanonicalType(FromType);
1129 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001130 } else {
1131 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001132 SCS.Third = ICK_Identity;
1133
Mike Stump1eb44332009-09-09 15:08:12 +00001134 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001135 // [...] Any difference in top-level cv-qualification is
1136 // subsumed by the initialization itself and does not constitute
1137 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001138 CanonFrom = S.Context.getCanonicalType(FromType);
1139 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001140 if (CanonFrom.getLocalUnqualifiedType()
1141 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001142 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1143 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001144 FromType = ToType;
1145 CanonFrom = CanonTo;
1146 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001147 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001148 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001149
1150 // If we have not converted the argument type to the parameter type,
1151 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001152 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001153 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001154
Douglas Gregor60d62c22008-10-31 16:23:19 +00001155 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001156}
1157
1158/// IsIntegralPromotion - Determines whether the conversion from the
1159/// expression From (whose potentially-adjusted type is FromType) to
1160/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1161/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001162bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001163 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001164 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001165 if (!To) {
1166 return false;
1167 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001168
1169 // An rvalue of type char, signed char, unsigned char, short int, or
1170 // unsigned short int can be converted to an rvalue of type int if
1171 // int can represent all the values of the source type; otherwise,
1172 // the source rvalue can be converted to an rvalue of type unsigned
1173 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001174 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1175 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001176 if (// We can promote any signed, promotable integer type to an int
1177 (FromType->isSignedIntegerType() ||
1178 // We can promote any unsigned integer type whose size is
1179 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001180 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001181 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001182 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001183 }
1184
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001185 return To->getKind() == BuiltinType::UInt;
1186 }
1187
1188 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1189 // can be converted to an rvalue of the first of the following types
1190 // that can represent all the values of its underlying type: int,
1191 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +00001192
1193 // We pre-calculate the promotion type for enum types.
1194 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1195 if (ToType->isIntegerType())
1196 return Context.hasSameUnqualifiedType(ToType,
1197 FromEnumType->getDecl()->getPromotionType());
1198
1199 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001200 // Determine whether the type we're converting from is signed or
1201 // unsigned.
1202 bool FromIsSigned;
1203 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +00001204
1205 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1206 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001207
1208 // The types we'll try to promote to, in the appropriate
1209 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001210 QualType PromoteTypes[6] = {
1211 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001212 Context.LongTy, Context.UnsignedLongTy ,
1213 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001214 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001215 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001216 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1217 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001218 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001219 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1220 // We found the type that we can promote to. If this is the
1221 // type we wanted, we have a promotion. Otherwise, no
1222 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001223 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001224 }
1225 }
1226 }
1227
1228 // An rvalue for an integral bit-field (9.6) can be converted to an
1229 // rvalue of type int if int can represent all the values of the
1230 // bit-field; otherwise, it can be converted to unsigned int if
1231 // unsigned int can represent all the values of the bit-field. If
1232 // the bit-field is larger yet, no integral promotion applies to
1233 // it. If the bit-field has an enumerated type, it is treated as any
1234 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001235 // FIXME: We should delay checking of bit-fields until we actually perform the
1236 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001237 using llvm::APSInt;
1238 if (From)
1239 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001240 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001241 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001242 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1243 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1244 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Douglas Gregor86f19402008-12-20 23:49:58 +00001246 // Are we promoting to an int from a bitfield that fits in an int?
1247 if (BitWidth < ToSize ||
1248 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1249 return To->getKind() == BuiltinType::Int;
1250 }
Mike Stump1eb44332009-09-09 15:08:12 +00001251
Douglas Gregor86f19402008-12-20 23:49:58 +00001252 // Are we promoting to an unsigned int from an unsigned bitfield
1253 // that fits into an unsigned int?
1254 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1255 return To->getKind() == BuiltinType::UInt;
1256 }
Mike Stump1eb44332009-09-09 15:08:12 +00001257
Douglas Gregor86f19402008-12-20 23:49:58 +00001258 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001259 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001260 }
Mike Stump1eb44332009-09-09 15:08:12 +00001261
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001262 // An rvalue of type bool can be converted to an rvalue of type int,
1263 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001264 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001265 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001266 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001267
1268 return false;
1269}
1270
1271/// IsFloatingPointPromotion - Determines whether the conversion from
1272/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1273/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001274bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001275 /// An rvalue of type float can be converted to an rvalue of type
1276 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001277 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1278 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001279 if (FromBuiltin->getKind() == BuiltinType::Float &&
1280 ToBuiltin->getKind() == BuiltinType::Double)
1281 return true;
1282
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001283 // C99 6.3.1.5p1:
1284 // When a float is promoted to double or long double, or a
1285 // double is promoted to long double [...].
1286 if (!getLangOptions().CPlusPlus &&
1287 (FromBuiltin->getKind() == BuiltinType::Float ||
1288 FromBuiltin->getKind() == BuiltinType::Double) &&
1289 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1290 return true;
1291 }
1292
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001293 return false;
1294}
1295
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001296/// \brief Determine if a conversion is a complex promotion.
1297///
1298/// A complex promotion is defined as a complex -> complex conversion
1299/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001300/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001301bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001302 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001303 if (!FromComplex)
1304 return false;
1305
John McCall183700f2009-09-21 23:43:11 +00001306 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001307 if (!ToComplex)
1308 return false;
1309
1310 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001311 ToComplex->getElementType()) ||
1312 IsIntegralPromotion(0, FromComplex->getElementType(),
1313 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001314}
1315
Douglas Gregorcb7de522008-11-26 23:31:11 +00001316/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1317/// the pointer type FromPtr to a pointer to type ToPointee, with the
1318/// same type qualifiers as FromPtr has on its pointee type. ToType,
1319/// if non-empty, will be a pointer to ToType that may or may not have
1320/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001321static QualType
1322BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001323 QualType ToPointee, QualType ToType,
1324 ASTContext &Context) {
1325 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1326 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001327 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001328
1329 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001330 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001331 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001332 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001333 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001334
1335 // Build a pointer to ToPointee. It has the right qualifiers
1336 // already.
1337 return Context.getPointerType(ToPointee);
1338 }
1339
1340 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +00001341 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +00001342 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1343 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +00001344}
1345
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001346/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1347/// the FromType, which is an objective-c pointer, to ToType, which may or may
1348/// not have the right set of qualifiers.
1349static QualType
1350BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1351 QualType ToType,
1352 ASTContext &Context) {
1353 QualType CanonFromType = Context.getCanonicalType(FromType);
1354 QualType CanonToType = Context.getCanonicalType(ToType);
1355 Qualifiers Quals = CanonFromType.getQualifiers();
1356
1357 // Exact qualifier match -> return the pointer type we're converting to.
1358 if (CanonToType.getLocalQualifiers() == Quals)
1359 return ToType;
1360
1361 // Just build a canonical type that has the right qualifiers.
1362 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1363}
1364
Mike Stump1eb44332009-09-09 15:08:12 +00001365static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001366 bool InOverloadResolution,
1367 ASTContext &Context) {
1368 // Handle value-dependent integral null pointer constants correctly.
1369 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1370 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001371 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001372 return !InOverloadResolution;
1373
Douglas Gregorce940492009-09-25 04:25:58 +00001374 return Expr->isNullPointerConstant(Context,
1375 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1376 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001377}
Mike Stump1eb44332009-09-09 15:08:12 +00001378
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001379/// IsPointerConversion - Determines whether the conversion of the
1380/// expression From, which has the (possibly adjusted) type FromType,
1381/// can be converted to the type ToType via a pointer conversion (C++
1382/// 4.10). If so, returns true and places the converted type (that
1383/// might differ from ToType in its cv-qualifiers at some level) into
1384/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001385///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001386/// This routine also supports conversions to and from block pointers
1387/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1388/// pointers to interfaces. FIXME: Once we've determined the
1389/// appropriate overloading rules for Objective-C, we may want to
1390/// split the Objective-C checks into a different routine; however,
1391/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001392/// conversions, so for now they live here. IncompatibleObjC will be
1393/// set if the conversion is an allowed Objective-C conversion that
1394/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001395bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001396 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001397 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001398 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001399 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001400 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1401 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001402
Mike Stump1eb44332009-09-09 15:08:12 +00001403 // Conversion from a null pointer constant to any Objective-C pointer type.
1404 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001405 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001406 ConvertedType = ToType;
1407 return true;
1408 }
1409
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001410 // Blocks: Block pointers can be converted to void*.
1411 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001412 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001413 ConvertedType = ToType;
1414 return true;
1415 }
1416 // Blocks: A null pointer constant can be converted to a block
1417 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001418 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001419 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001420 ConvertedType = ToType;
1421 return true;
1422 }
1423
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001424 // If the left-hand-side is nullptr_t, the right side can be a null
1425 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001426 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001427 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001428 ConvertedType = ToType;
1429 return true;
1430 }
1431
Ted Kremenek6217b802009-07-29 21:53:49 +00001432 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001433 if (!ToTypePtr)
1434 return false;
1435
1436 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001437 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001438 ConvertedType = ToType;
1439 return true;
1440 }
Sebastian Redl07779722008-10-31 14:43:28 +00001441
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001442 // Beyond this point, both types need to be pointers
1443 // , including objective-c pointers.
1444 QualType ToPointeeType = ToTypePtr->getPointeeType();
1445 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1446 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1447 ToType, Context);
1448 return true;
1449
1450 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001451 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001452 if (!FromTypePtr)
1453 return false;
1454
1455 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001456
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001457 // If the unqualified pointee types are the same, this can't be a
1458 // pointer conversion, so don't do all of the work below.
1459 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1460 return false;
1461
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001462 // An rvalue of type "pointer to cv T," where T is an object type,
1463 // can be converted to an rvalue of type "pointer to cv void" (C++
1464 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001465 if (FromPointeeType->isIncompleteOrObjectType() &&
1466 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001467 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001468 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001469 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001470 return true;
1471 }
1472
Douglas Gregorf9201e02009-02-11 23:02:49 +00001473 // When we're overloading in C, we allow a special kind of pointer
1474 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001475 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001476 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001477 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001478 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001479 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001480 return true;
1481 }
1482
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001483 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001484 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001485 // An rvalue of type "pointer to cv D," where D is a class type,
1486 // can be converted to an rvalue of type "pointer to cv B," where
1487 // B is a base class (clause 10) of D. If B is an inaccessible
1488 // (clause 11) or ambiguous (10.2) base class of D, a program that
1489 // necessitates this conversion is ill-formed. The result of the
1490 // conversion is a pointer to the base class sub-object of the
1491 // derived class object. The null pointer value is converted to
1492 // the null pointer value of the destination type.
1493 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001494 // Note that we do not check for ambiguity or inaccessibility
1495 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001496 if (getLangOptions().CPlusPlus &&
1497 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001498 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001499 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001500 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001501 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001502 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001503 ToType, Context);
1504 return true;
1505 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001506
Douglas Gregorc7887512008-12-19 19:13:09 +00001507 return false;
1508}
1509
1510/// isObjCPointerConversion - Determines whether this is an
1511/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1512/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001513bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001514 QualType& ConvertedType,
1515 bool &IncompatibleObjC) {
1516 if (!getLangOptions().ObjC1)
1517 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001518
Steve Naroff14108da2009-07-10 23:34:53 +00001519 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001520 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001521 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001522 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001523
Steve Naroff14108da2009-07-10 23:34:53 +00001524 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001525 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001526 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001527 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001528 ConvertedType = ToType;
1529 return true;
1530 }
1531 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001532 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001533 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001534 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001535 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001536 ConvertedType = ToType;
1537 return true;
1538 }
1539 // Objective C++: We're able to convert from a pointer to an
1540 // interface to a pointer to a different interface.
1541 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001542 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1543 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1544 if (getLangOptions().CPlusPlus && LHS && RHS &&
1545 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1546 FromObjCPtr->getPointeeType()))
1547 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00001548 ConvertedType = ToType;
1549 return true;
1550 }
1551
1552 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1553 // Okay: this is some kind of implicit downcast of Objective-C
1554 // interfaces, which is permitted. However, we're going to
1555 // complain about it.
1556 IncompatibleObjC = true;
1557 ConvertedType = FromType;
1558 return true;
1559 }
Mike Stump1eb44332009-09-09 15:08:12 +00001560 }
Steve Naroff14108da2009-07-10 23:34:53 +00001561 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001562 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001563 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001564 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001565 else if (const BlockPointerType *ToBlockPtr =
1566 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001567 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001568 // to a block pointer type.
1569 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1570 ConvertedType = ToType;
1571 return true;
1572 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001573 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001574 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001575 else if (FromType->getAs<BlockPointerType>() &&
1576 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1577 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001578 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001579 ConvertedType = ToType;
1580 return true;
1581 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001582 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001583 return false;
1584
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001585 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001586 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001587 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001588 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001589 FromPointeeType = FromBlockPtr->getPointeeType();
1590 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001591 return false;
1592
Douglas Gregorc7887512008-12-19 19:13:09 +00001593 // If we have pointers to pointers, recursively check whether this
1594 // is an Objective-C conversion.
1595 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1596 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1597 IncompatibleObjC)) {
1598 // We always complain about this conversion.
1599 IncompatibleObjC = true;
1600 ConvertedType = ToType;
1601 return true;
1602 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001603 // Allow conversion of pointee being objective-c pointer to another one;
1604 // as in I* to id.
1605 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1606 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1607 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1608 IncompatibleObjC)) {
1609 ConvertedType = ToType;
1610 return true;
1611 }
1612
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001613 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001614 // differences in the argument and result types are in Objective-C
1615 // pointer conversions. If so, we permit the conversion (but
1616 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001617 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001618 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001619 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001620 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001621 if (FromFunctionType && ToFunctionType) {
1622 // If the function types are exactly the same, this isn't an
1623 // Objective-C pointer conversion.
1624 if (Context.getCanonicalType(FromPointeeType)
1625 == Context.getCanonicalType(ToPointeeType))
1626 return false;
1627
1628 // Perform the quick checks that will tell us whether these
1629 // function types are obviously different.
1630 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1631 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1632 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1633 return false;
1634
1635 bool HasObjCConversion = false;
1636 if (Context.getCanonicalType(FromFunctionType->getResultType())
1637 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1638 // Okay, the types match exactly. Nothing to do.
1639 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1640 ToFunctionType->getResultType(),
1641 ConvertedType, IncompatibleObjC)) {
1642 // Okay, we have an Objective-C pointer conversion.
1643 HasObjCConversion = true;
1644 } else {
1645 // Function types are too different. Abort.
1646 return false;
1647 }
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Douglas Gregorc7887512008-12-19 19:13:09 +00001649 // Check argument types.
1650 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1651 ArgIdx != NumArgs; ++ArgIdx) {
1652 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1653 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1654 if (Context.getCanonicalType(FromArgType)
1655 == Context.getCanonicalType(ToArgType)) {
1656 // Okay, the types match exactly. Nothing to do.
1657 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1658 ConvertedType, IncompatibleObjC)) {
1659 // Okay, we have an Objective-C pointer conversion.
1660 HasObjCConversion = true;
1661 } else {
1662 // Argument types are too different. Abort.
1663 return false;
1664 }
1665 }
1666
1667 if (HasObjCConversion) {
1668 // We had an Objective-C conversion. Allow this pointer
1669 // conversion, but complain about it.
1670 ConvertedType = ToType;
1671 IncompatibleObjC = true;
1672 return true;
1673 }
1674 }
1675
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001676 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001677}
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001678
1679/// FunctionArgTypesAreEqual - This routine checks two function proto types
1680/// for equlity of their argument types. Caller has already checked that
1681/// they have same number of arguments. This routine assumes that Objective-C
1682/// pointer types which only differ in their protocol qualifiers are equal.
1683bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1684 FunctionProtoType* NewType){
1685 if (!getLangOptions().ObjC1)
1686 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1687 NewType->arg_type_begin());
1688
1689 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1690 N = NewType->arg_type_begin(),
1691 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1692 QualType ToType = (*O);
1693 QualType FromType = (*N);
1694 if (ToType != FromType) {
1695 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1696 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001697 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1698 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1699 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1700 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001701 continue;
1702 }
John McCallc12c5bb2010-05-15 11:32:37 +00001703 else if (const ObjCObjectPointerType *PTTo =
1704 ToType->getAs<ObjCObjectPointerType>()) {
1705 if (const ObjCObjectPointerType *PTFr =
1706 FromType->getAs<ObjCObjectPointerType>())
1707 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1708 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001709 }
1710 return false;
1711 }
1712 }
1713 return true;
1714}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001715
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001716/// CheckPointerConversion - Check the pointer conversion from the
1717/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001718/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001719/// conversions for which IsPointerConversion has already returned
1720/// true. It returns true and produces a diagnostic if there was an
1721/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001722bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001723 CastExpr::CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001724 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001725 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001726 QualType FromType = From->getType();
1727
Douglas Gregord7a95972010-06-08 17:35:15 +00001728 if (CXXBoolLiteralExpr* LitBool
1729 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1730 if (LitBool->getValue() == false)
1731 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1732 << ToType;
1733
Ted Kremenek6217b802009-07-29 21:53:49 +00001734 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1735 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001736 QualType FromPointeeType = FromPtrType->getPointeeType(),
1737 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001738
Douglas Gregor5fccd362010-03-03 23:55:11 +00001739 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1740 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001741 // We must have a derived-to-base conversion. Check an
1742 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001743 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1744 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001745 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001746 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001747 return true;
1748
1749 // The conversion was successful.
1750 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001751 }
1752 }
Mike Stump1eb44332009-09-09 15:08:12 +00001753 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001754 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001755 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001756 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001757 // Objective-C++ conversions are always okay.
1758 // FIXME: We should have a different class of conversions for the
1759 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001760 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001761 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001762
Steve Naroff14108da2009-07-10 23:34:53 +00001763 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001764 return false;
1765}
1766
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001767/// IsMemberPointerConversion - Determines whether the conversion of the
1768/// expression From, which has the (possibly adjusted) type FromType, can be
1769/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1770/// If so, returns true and places the converted type (that might differ from
1771/// ToType in its cv-qualifiers at some level) into ConvertedType.
1772bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001773 QualType ToType,
1774 bool InOverloadResolution,
1775 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001776 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001777 if (!ToTypePtr)
1778 return false;
1779
1780 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001781 if (From->isNullPointerConstant(Context,
1782 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1783 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001784 ConvertedType = ToType;
1785 return true;
1786 }
1787
1788 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001789 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001790 if (!FromTypePtr)
1791 return false;
1792
1793 // A pointer to member of B can be converted to a pointer to member of D,
1794 // where D is derived from B (C++ 4.11p2).
1795 QualType FromClass(FromTypePtr->getClass(), 0);
1796 QualType ToClass(ToTypePtr->getClass(), 0);
1797 // FIXME: What happens when these are dependent? Is this function even called?
1798
1799 if (IsDerivedFrom(ToClass, FromClass)) {
1800 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1801 ToClass.getTypePtr());
1802 return true;
1803 }
1804
1805 return false;
1806}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001807
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001808/// CheckMemberPointerConversion - Check the member pointer conversion from the
1809/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001810/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001811/// for which IsMemberPointerConversion has already returned true. It returns
1812/// true and produces a diagnostic if there was an error, or returns false
1813/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001814bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001815 CastExpr::CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001816 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001817 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001818 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001819 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001820 if (!FromPtrType) {
1821 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001822 assert(From->isNullPointerConstant(Context,
1823 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001824 "Expr must be null pointer constant!");
1825 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001826 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001827 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001828
Ted Kremenek6217b802009-07-29 21:53:49 +00001829 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001830 assert(ToPtrType && "No member pointer cast has a target type "
1831 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001832
Sebastian Redl21593ac2009-01-28 18:33:18 +00001833 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1834 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001835
Sebastian Redl21593ac2009-01-28 18:33:18 +00001836 // FIXME: What about dependent types?
1837 assert(FromClass->isRecordType() && "Pointer into non-class.");
1838 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001839
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001840 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001841 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001842 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1843 assert(DerivationOkay &&
1844 "Should not have been called if derivation isn't OK.");
1845 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001846
Sebastian Redl21593ac2009-01-28 18:33:18 +00001847 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1848 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001849 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1850 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1851 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1852 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001853 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001854
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001855 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001856 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1857 << FromClass << ToClass << QualType(VBase, 0)
1858 << From->getSourceRange();
1859 return true;
1860 }
1861
John McCall6b2accb2010-02-10 09:31:12 +00001862 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001863 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1864 Paths.front(),
1865 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001866
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001867 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001868 BuildBasePathArray(Paths, BasePath);
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001869 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001870 return false;
1871}
1872
Douglas Gregor98cd5992008-10-21 23:43:52 +00001873/// IsQualificationConversion - Determines whether the conversion from
1874/// an rvalue of type FromType to ToType is a qualification conversion
1875/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001876bool
1877Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001878 FromType = Context.getCanonicalType(FromType);
1879 ToType = Context.getCanonicalType(ToType);
1880
1881 // If FromType and ToType are the same type, this is not a
1882 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001883 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001884 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001885
Douglas Gregor98cd5992008-10-21 23:43:52 +00001886 // (C++ 4.4p4):
1887 // A conversion can add cv-qualifiers at levels other than the first
1888 // in multi-level pointers, subject to the following rules: [...]
1889 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001890 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001891 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001892 // Within each iteration of the loop, we check the qualifiers to
1893 // determine if this still looks like a qualification
1894 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001895 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001896 // until there are no more pointers or pointers-to-members left to
1897 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001898 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001899
1900 // -- for every j > 0, if const is in cv 1,j then const is in cv
1901 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001902 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001903 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Douglas Gregor98cd5992008-10-21 23:43:52 +00001905 // -- if the cv 1,j and cv 2,j are different, then const is in
1906 // every cv for 0 < k < j.
1907 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001908 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001909 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Douglas Gregor98cd5992008-10-21 23:43:52 +00001911 // Keep track of whether all prior cv-qualifiers in the "to" type
1912 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001913 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001914 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001915 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001916
1917 // We are left with FromType and ToType being the pointee types
1918 // after unwrapping the original FromType and ToType the same number
1919 // of types. If we unwrapped any pointers, and if FromType and
1920 // ToType have the same unqualified type (since we checked
1921 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001922 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001923}
1924
Douglas Gregor734d9862009-01-30 23:27:23 +00001925/// Determines whether there is a user-defined conversion sequence
1926/// (C++ [over.ics.user]) that converts expression From to the type
1927/// ToType. If such a conversion exists, User will contain the
1928/// user-defined conversion sequence that performs such a conversion
1929/// and this routine will return true. Otherwise, this routine returns
1930/// false and User is unspecified.
1931///
Douglas Gregor734d9862009-01-30 23:27:23 +00001932/// \param AllowExplicit true if the conversion should consider C++0x
1933/// "explicit" conversion functions as well as non-explicit conversion
1934/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00001935static OverloadingResult
1936IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1937 UserDefinedConversionSequence& User,
1938 OverloadCandidateSet& CandidateSet,
1939 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001940 // Whether we will only visit constructors.
1941 bool ConstructorsOnly = false;
1942
1943 // If the type we are conversion to is a class type, enumerate its
1944 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00001945 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001946 // C++ [over.match.ctor]p1:
1947 // When objects of class type are direct-initialized (8.5), or
1948 // copy-initialized from an expression of the same or a
1949 // derived class type (8.5), overload resolution selects the
1950 // constructor. [...] For copy-initialization, the candidate
1951 // functions are all the converting constructors (12.3.1) of
1952 // that class. The argument list is the expression-list within
1953 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00001954 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001955 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001956 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001957 ConstructorsOnly = true;
1958
John McCall120d63c2010-08-24 20:38:10 +00001959 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001960 // We're not going to find any constructors.
1961 } else if (CXXRecordDecl *ToRecordDecl
1962 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001963 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00001964 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001965 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00001966 NamedDecl *D = *Con;
1967 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1968
Douglas Gregordec06662009-08-21 18:42:58 +00001969 // Find the constructor (which may be a template).
1970 CXXConstructorDecl *Constructor = 0;
1971 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00001972 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00001973 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001974 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001975 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1976 else
John McCall9aa472c2010-03-19 07:35:19 +00001977 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001978
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001979 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001980 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001981 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00001982 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
1983 /*ExplicitArgs*/ 0,
1984 &From, 1, CandidateSet,
1985 /*SuppressUserConversions=*/
1986 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001987 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001988 // Allow one user-defined conversion when user specifies a
1989 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00001990 S.AddOverloadCandidate(Constructor, FoundDecl,
1991 &From, 1, CandidateSet,
1992 /*SuppressUserConversions=*/
1993 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001994 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001995 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001996 }
1997 }
1998
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001999 // Enumerate conversion functions, if we're allowed to.
2000 if (ConstructorsOnly) {
John McCall120d63c2010-08-24 20:38:10 +00002001 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2002 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002003 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002004 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002005 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002006 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002007 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2008 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002009 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002010 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002011 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002012 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002013 DeclAccessPair FoundDecl = I.getPair();
2014 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002015 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2016 if (isa<UsingShadowDecl>(D))
2017 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2018
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002019 CXXConversionDecl *Conv;
2020 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002021 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2022 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002023 else
John McCall32daa422010-03-31 01:36:47 +00002024 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002025
2026 if (AllowExplicit || !Conv->isExplicit()) {
2027 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002028 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2029 ActingContext, From, ToType,
2030 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002031 else
John McCall120d63c2010-08-24 20:38:10 +00002032 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2033 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002034 }
2035 }
2036 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002037 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002038
2039 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00002040 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best)) {
2041 case OR_Success:
2042 // Record the standard conversion we used and the conversion function.
2043 if (CXXConstructorDecl *Constructor
2044 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2045 // C++ [over.ics.user]p1:
2046 // If the user-defined conversion is specified by a
2047 // constructor (12.3.1), the initial standard conversion
2048 // sequence converts the source type to the type required by
2049 // the argument of the constructor.
2050 //
2051 QualType ThisType = Constructor->getThisType(S.Context);
2052 if (Best->Conversions[0].isEllipsis())
2053 User.EllipsisConversion = true;
2054 else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002055 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002056 User.EllipsisConversion = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002057 }
John McCall120d63c2010-08-24 20:38:10 +00002058 User.ConversionFunction = Constructor;
2059 User.After.setAsIdentityConversion();
2060 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2061 User.After.setAllToTypes(ToType);
2062 return OR_Success;
2063 } else if (CXXConversionDecl *Conversion
2064 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2065 // C++ [over.ics.user]p1:
2066 //
2067 // [...] If the user-defined conversion is specified by a
2068 // conversion function (12.3.2), the initial standard
2069 // conversion sequence converts the source type to the
2070 // implicit object parameter of the conversion function.
2071 User.Before = Best->Conversions[0].Standard;
2072 User.ConversionFunction = Conversion;
2073 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002074
John McCall120d63c2010-08-24 20:38:10 +00002075 // C++ [over.ics.user]p2:
2076 // The second standard conversion sequence converts the
2077 // result of the user-defined conversion to the target type
2078 // for the sequence. Since an implicit conversion sequence
2079 // is an initialization, the special rules for
2080 // initialization by user-defined conversion apply when
2081 // selecting the best user-defined conversion for a
2082 // user-defined conversion sequence (see 13.3.3 and
2083 // 13.3.3.1).
2084 User.After = Best->FinalConversion;
2085 return OR_Success;
2086 } else {
2087 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002088 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002089 }
2090
John McCall120d63c2010-08-24 20:38:10 +00002091 case OR_No_Viable_Function:
2092 return OR_No_Viable_Function;
2093 case OR_Deleted:
2094 // No conversion here! We're done.
2095 return OR_Deleted;
2096
2097 case OR_Ambiguous:
2098 return OR_Ambiguous;
2099 }
2100
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002101 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002102}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002103
2104bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002105Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002106 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002107 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002108 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00002109 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002110 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002111 if (OvResult == OR_Ambiguous)
2112 Diag(From->getSourceRange().getBegin(),
2113 diag::err_typecheck_ambiguous_condition)
2114 << From->getType() << ToType << From->getSourceRange();
2115 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2116 Diag(From->getSourceRange().getBegin(),
2117 diag::err_typecheck_nonviable_condition)
2118 << From->getType() << ToType << From->getSourceRange();
2119 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002120 return false;
John McCall120d63c2010-08-24 20:38:10 +00002121 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002122 return true;
2123}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002124
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002125/// CompareImplicitConversionSequences - Compare two implicit
2126/// conversion sequences to determine whether one is better than the
2127/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00002128static ImplicitConversionSequence::CompareKind
2129CompareImplicitConversionSequences(Sema &S,
2130 const ImplicitConversionSequence& ICS1,
2131 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002132{
2133 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2134 // conversion sequences (as defined in 13.3.3.1)
2135 // -- a standard conversion sequence (13.3.3.1.1) is a better
2136 // conversion sequence than a user-defined conversion sequence or
2137 // an ellipsis conversion sequence, and
2138 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2139 // conversion sequence than an ellipsis conversion sequence
2140 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002141 //
John McCall1d318332010-01-12 00:44:57 +00002142 // C++0x [over.best.ics]p10:
2143 // For the purpose of ranking implicit conversion sequences as
2144 // described in 13.3.3.2, the ambiguous conversion sequence is
2145 // treated as a user-defined sequence that is indistinguishable
2146 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002147 if (ICS1.getKindRank() < ICS2.getKindRank())
2148 return ImplicitConversionSequence::Better;
2149 else if (ICS2.getKindRank() < ICS1.getKindRank())
2150 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002151
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002152 // The following checks require both conversion sequences to be of
2153 // the same kind.
2154 if (ICS1.getKind() != ICS2.getKind())
2155 return ImplicitConversionSequence::Indistinguishable;
2156
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002157 // Two implicit conversion sequences of the same form are
2158 // indistinguishable conversion sequences unless one of the
2159 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002160 if (ICS1.isStandard())
John McCall120d63c2010-08-24 20:38:10 +00002161 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002162 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002163 // User-defined conversion sequence U1 is a better conversion
2164 // sequence than another user-defined conversion sequence U2 if
2165 // they contain the same user-defined conversion function or
2166 // constructor and if the second standard conversion sequence of
2167 // U1 is better than the second standard conversion sequence of
2168 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002169 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002170 ICS2.UserDefined.ConversionFunction)
John McCall120d63c2010-08-24 20:38:10 +00002171 return CompareStandardConversionSequences(S,
2172 ICS1.UserDefined.After,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002173 ICS2.UserDefined.After);
2174 }
2175
2176 return ImplicitConversionSequence::Indistinguishable;
2177}
2178
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002179static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2180 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2181 Qualifiers Quals;
2182 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2183 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2184 }
2185
2186 return Context.hasSameUnqualifiedType(T1, T2);
2187}
2188
Douglas Gregorad323a82010-01-27 03:51:04 +00002189// Per 13.3.3.2p3, compare the given standard conversion sequences to
2190// determine if one is a proper subset of the other.
2191static ImplicitConversionSequence::CompareKind
2192compareStandardConversionSubsets(ASTContext &Context,
2193 const StandardConversionSequence& SCS1,
2194 const StandardConversionSequence& SCS2) {
2195 ImplicitConversionSequence::CompareKind Result
2196 = ImplicitConversionSequence::Indistinguishable;
2197
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002198 // the identity conversion sequence is considered to be a subsequence of
2199 // any non-identity conversion sequence
2200 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2201 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2202 return ImplicitConversionSequence::Better;
2203 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2204 return ImplicitConversionSequence::Worse;
2205 }
2206
Douglas Gregorad323a82010-01-27 03:51:04 +00002207 if (SCS1.Second != SCS2.Second) {
2208 if (SCS1.Second == ICK_Identity)
2209 Result = ImplicitConversionSequence::Better;
2210 else if (SCS2.Second == ICK_Identity)
2211 Result = ImplicitConversionSequence::Worse;
2212 else
2213 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002214 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002215 return ImplicitConversionSequence::Indistinguishable;
2216
2217 if (SCS1.Third == SCS2.Third) {
2218 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2219 : ImplicitConversionSequence::Indistinguishable;
2220 }
2221
2222 if (SCS1.Third == ICK_Identity)
2223 return Result == ImplicitConversionSequence::Worse
2224 ? ImplicitConversionSequence::Indistinguishable
2225 : ImplicitConversionSequence::Better;
2226
2227 if (SCS2.Third == ICK_Identity)
2228 return Result == ImplicitConversionSequence::Better
2229 ? ImplicitConversionSequence::Indistinguishable
2230 : ImplicitConversionSequence::Worse;
2231
2232 return ImplicitConversionSequence::Indistinguishable;
2233}
2234
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002235/// CompareStandardConversionSequences - Compare two standard
2236/// conversion sequences to determine whether one is better than the
2237/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00002238static ImplicitConversionSequence::CompareKind
2239CompareStandardConversionSequences(Sema &S,
2240 const StandardConversionSequence& SCS1,
2241 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002242{
2243 // Standard conversion sequence S1 is a better conversion sequence
2244 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2245
2246 // -- S1 is a proper subsequence of S2 (comparing the conversion
2247 // sequences in the canonical form defined by 13.3.3.1.1,
2248 // excluding any Lvalue Transformation; the identity conversion
2249 // sequence is considered to be a subsequence of any
2250 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002251 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00002252 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00002253 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002254
2255 // -- the rank of S1 is better than the rank of S2 (by the rules
2256 // defined below), or, if not that,
2257 ImplicitConversionRank Rank1 = SCS1.getRank();
2258 ImplicitConversionRank Rank2 = SCS2.getRank();
2259 if (Rank1 < Rank2)
2260 return ImplicitConversionSequence::Better;
2261 else if (Rank2 < Rank1)
2262 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002263
Douglas Gregor57373262008-10-22 14:17:15 +00002264 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2265 // are indistinguishable unless one of the following rules
2266 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002267
Douglas Gregor57373262008-10-22 14:17:15 +00002268 // A conversion that is not a conversion of a pointer, or
2269 // pointer to member, to bool is better than another conversion
2270 // that is such a conversion.
2271 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2272 return SCS2.isPointerConversionToBool()
2273 ? ImplicitConversionSequence::Better
2274 : ImplicitConversionSequence::Worse;
2275
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002276 // C++ [over.ics.rank]p4b2:
2277 //
2278 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002279 // conversion of B* to A* is better than conversion of B* to
2280 // void*, and conversion of A* to void* is better than conversion
2281 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002282 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002283 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002284 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002285 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002286 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2287 // Exactly one of the conversion sequences is a conversion to
2288 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002289 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2290 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002291 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2292 // Neither conversion sequence converts to a void pointer; compare
2293 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002294 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00002295 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002296 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002297 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2298 // Both conversion sequences are conversions to void
2299 // pointers. Compare the source types to determine if there's an
2300 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002301 QualType FromType1 = SCS1.getFromType();
2302 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002303
2304 // Adjust the types we're converting from via the array-to-pointer
2305 // conversion, if we need to.
2306 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002307 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002308 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002309 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002310
Douglas Gregor01919692009-12-13 21:37:05 +00002311 QualType FromPointee1
2312 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2313 QualType FromPointee2
2314 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002315
John McCall120d63c2010-08-24 20:38:10 +00002316 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00002317 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002318 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00002319 return ImplicitConversionSequence::Worse;
2320
2321 // Objective-C++: If one interface is more specific than the
2322 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002323 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2324 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002325 if (FromIface1 && FromIface1) {
John McCall120d63c2010-08-24 20:38:10 +00002326 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor01919692009-12-13 21:37:05 +00002327 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002328 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor01919692009-12-13 21:37:05 +00002329 return ImplicitConversionSequence::Worse;
2330 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002331 }
Douglas Gregor57373262008-10-22 14:17:15 +00002332
2333 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2334 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002335 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00002336 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002337 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002338
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002339 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002340 // C++0x [over.ics.rank]p3b4:
2341 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2342 // implicit object parameter of a non-static member function declared
2343 // without a ref-qualifier, and S1 binds an rvalue reference to an
2344 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00002345 // FIXME: We don't know if we're dealing with the implicit object parameter,
2346 // or if the member function in this case has a ref qualifier.
2347 // (Of course, we don't have ref qualifiers yet.)
2348 if (SCS1.RRefBinding != SCS2.RRefBinding)
2349 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2350 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002351
2352 // C++ [over.ics.rank]p3b4:
2353 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2354 // which the references refer are the same type except for
2355 // top-level cv-qualifiers, and the type to which the reference
2356 // initialized by S2 refers is more cv-qualified than the type
2357 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002358 QualType T1 = SCS1.getToType(2);
2359 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002360 T1 = S.Context.getCanonicalType(T1);
2361 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002362 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002363 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2364 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002365 if (UnqualT1 == UnqualT2) {
2366 // If the type is an array type, promote the element qualifiers to the type
2367 // for comparison.
2368 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002369 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002370 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002371 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002372 if (T2.isMoreQualifiedThan(T1))
2373 return ImplicitConversionSequence::Better;
2374 else if (T1.isMoreQualifiedThan(T2))
2375 return ImplicitConversionSequence::Worse;
2376 }
2377 }
Douglas Gregor57373262008-10-22 14:17:15 +00002378
2379 return ImplicitConversionSequence::Indistinguishable;
2380}
2381
2382/// CompareQualificationConversions - Compares two standard conversion
2383/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002384/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2385ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002386CompareQualificationConversions(Sema &S,
2387 const StandardConversionSequence& SCS1,
2388 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002389 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002390 // -- S1 and S2 differ only in their qualification conversion and
2391 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2392 // cv-qualification signature of type T1 is a proper subset of
2393 // the cv-qualification signature of type T2, and S1 is not the
2394 // deprecated string literal array-to-pointer conversion (4.2).
2395 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2396 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2397 return ImplicitConversionSequence::Indistinguishable;
2398
2399 // FIXME: the example in the standard doesn't use a qualification
2400 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002401 QualType T1 = SCS1.getToType(2);
2402 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002403 T1 = S.Context.getCanonicalType(T1);
2404 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002405 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002406 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2407 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002408
2409 // If the types are the same, we won't learn anything by unwrapped
2410 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002411 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002412 return ImplicitConversionSequence::Indistinguishable;
2413
Chandler Carruth28e318c2009-12-29 07:16:59 +00002414 // If the type is an array type, promote the element qualifiers to the type
2415 // for comparison.
2416 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002417 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002418 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002419 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002420
Mike Stump1eb44332009-09-09 15:08:12 +00002421 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002422 = ImplicitConversionSequence::Indistinguishable;
John McCall120d63c2010-08-24 20:38:10 +00002423 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002424 // Within each iteration of the loop, we check the qualifiers to
2425 // determine if this still looks like a qualification
2426 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002427 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002428 // until there are no more pointers or pointers-to-members left
2429 // to unwrap. This essentially mimics what
2430 // IsQualificationConversion does, but here we're checking for a
2431 // strict subset of qualifiers.
2432 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2433 // The qualifiers are the same, so this doesn't tell us anything
2434 // about how the sequences rank.
2435 ;
2436 else if (T2.isMoreQualifiedThan(T1)) {
2437 // T1 has fewer qualifiers, so it could be the better sequence.
2438 if (Result == ImplicitConversionSequence::Worse)
2439 // Neither has qualifiers that are a subset of the other's
2440 // qualifiers.
2441 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002442
Douglas Gregor57373262008-10-22 14:17:15 +00002443 Result = ImplicitConversionSequence::Better;
2444 } else if (T1.isMoreQualifiedThan(T2)) {
2445 // T2 has fewer qualifiers, so it could be the better sequence.
2446 if (Result == ImplicitConversionSequence::Better)
2447 // Neither has qualifiers that are a subset of the other's
2448 // qualifiers.
2449 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002450
Douglas Gregor57373262008-10-22 14:17:15 +00002451 Result = ImplicitConversionSequence::Worse;
2452 } else {
2453 // Qualifiers are disjoint.
2454 return ImplicitConversionSequence::Indistinguishable;
2455 }
2456
2457 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00002458 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002459 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002460 }
2461
Douglas Gregor57373262008-10-22 14:17:15 +00002462 // Check that the winning standard conversion sequence isn't using
2463 // the deprecated string literal array to pointer conversion.
2464 switch (Result) {
2465 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002466 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002467 Result = ImplicitConversionSequence::Indistinguishable;
2468 break;
2469
2470 case ImplicitConversionSequence::Indistinguishable:
2471 break;
2472
2473 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002474 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002475 Result = ImplicitConversionSequence::Indistinguishable;
2476 break;
2477 }
2478
2479 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002480}
2481
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002482/// CompareDerivedToBaseConversions - Compares two standard conversion
2483/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002484/// various kinds of derived-to-base conversions (C++
2485/// [over.ics.rank]p4b3). As part of these checks, we also look at
2486/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002487ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002488CompareDerivedToBaseConversions(Sema &S,
2489 const StandardConversionSequence& SCS1,
2490 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002491 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002492 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002493 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002494 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002495
2496 // Adjust the types we're converting from via the array-to-pointer
2497 // conversion, if we need to.
2498 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002499 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002500 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002501 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002502
2503 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00002504 FromType1 = S.Context.getCanonicalType(FromType1);
2505 ToType1 = S.Context.getCanonicalType(ToType1);
2506 FromType2 = S.Context.getCanonicalType(FromType2);
2507 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002508
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002509 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002510 //
2511 // If class B is derived directly or indirectly from class A and
2512 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002513 //
2514 // For Objective-C, we let A, B, and C also be Objective-C
2515 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002516
2517 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002518 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002519 SCS2.Second == ICK_Pointer_Conversion &&
2520 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2521 FromType1->isPointerType() && FromType2->isPointerType() &&
2522 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002523 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002524 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002525 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002526 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002527 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002528 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002529 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002530 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002531
John McCallc12c5bb2010-05-15 11:32:37 +00002532 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2533 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2534 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2535 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002536
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002537 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002538 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002539 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002540 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002541 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002542 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002543
2544 if (ToIface1 && ToIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002545 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002546 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002547 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002548 return ImplicitConversionSequence::Worse;
2549 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002550 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002551
2552 // -- conversion of B* to A* is better than conversion of C* to A*,
2553 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002554 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002555 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002556 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002557 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002558
Douglas Gregorcb7de522008-11-26 23:31:11 +00002559 if (FromIface1 && FromIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002560 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002561 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002562 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002563 return ImplicitConversionSequence::Worse;
2564 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002565 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002566 }
2567
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002568 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002569 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2570 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2571 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2572 const MemberPointerType * FromMemPointer1 =
2573 FromType1->getAs<MemberPointerType>();
2574 const MemberPointerType * ToMemPointer1 =
2575 ToType1->getAs<MemberPointerType>();
2576 const MemberPointerType * FromMemPointer2 =
2577 FromType2->getAs<MemberPointerType>();
2578 const MemberPointerType * ToMemPointer2 =
2579 ToType2->getAs<MemberPointerType>();
2580 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2581 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2582 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2583 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2584 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2585 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2586 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2587 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002588 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002589 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002590 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002591 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00002592 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002593 return ImplicitConversionSequence::Better;
2594 }
2595 // conversion of B::* to C::* is better than conversion of A::* to C::*
2596 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002597 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002598 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002599 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002600 return ImplicitConversionSequence::Worse;
2601 }
2602 }
2603
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002604 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002605 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002606 // -- binding of an expression of type C to a reference of type
2607 // B& is better than binding an expression of type C to a
2608 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002609 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2610 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2611 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002612 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002613 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002614 return ImplicitConversionSequence::Worse;
2615 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002616
Douglas Gregor225c41e2008-11-03 19:09:14 +00002617 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002618 // -- binding of an expression of type B to a reference of type
2619 // A& is better than binding an expression of type C to a
2620 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002621 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2622 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2623 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002624 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002625 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002626 return ImplicitConversionSequence::Worse;
2627 }
2628 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002629
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002630 return ImplicitConversionSequence::Indistinguishable;
2631}
2632
Douglas Gregorabe183d2010-04-13 16:31:36 +00002633/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2634/// determine whether they are reference-related,
2635/// reference-compatible, reference-compatible with added
2636/// qualification, or incompatible, for use in C++ initialization by
2637/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2638/// type, and the first type (T1) is the pointee type of the reference
2639/// type being initialized.
2640Sema::ReferenceCompareResult
2641Sema::CompareReferenceRelationship(SourceLocation Loc,
2642 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00002643 bool &DerivedToBase,
2644 bool &ObjCConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002645 assert(!OrigT1->isReferenceType() &&
2646 "T1 must be the pointee type of the reference type");
2647 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2648
2649 QualType T1 = Context.getCanonicalType(OrigT1);
2650 QualType T2 = Context.getCanonicalType(OrigT2);
2651 Qualifiers T1Quals, T2Quals;
2652 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2653 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2654
2655 // C++ [dcl.init.ref]p4:
2656 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2657 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2658 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00002659 DerivedToBase = false;
2660 ObjCConversion = false;
2661 if (UnqualT1 == UnqualT2) {
2662 // Nothing to do.
2663 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002664 IsDerivedFrom(UnqualT2, UnqualT1))
2665 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00002666 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2667 UnqualT2->isObjCObjectOrInterfaceType() &&
2668 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2669 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002670 else
2671 return Ref_Incompatible;
2672
2673 // At this point, we know that T1 and T2 are reference-related (at
2674 // least).
2675
2676 // If the type is an array type, promote the element qualifiers to the type
2677 // for comparison.
2678 if (isa<ArrayType>(T1) && T1Quals)
2679 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2680 if (isa<ArrayType>(T2) && T2Quals)
2681 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2682
2683 // C++ [dcl.init.ref]p4:
2684 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2685 // reference-related to T2 and cv1 is the same cv-qualification
2686 // as, or greater cv-qualification than, cv2. For purposes of
2687 // overload resolution, cases for which cv1 is greater
2688 // cv-qualification than cv2 are identified as
2689 // reference-compatible with added qualification (see 13.3.3.2).
2690 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2691 return Ref_Compatible;
2692 else if (T1.isMoreQualifiedThan(T2))
2693 return Ref_Compatible_With_Added_Qualification;
2694 else
2695 return Ref_Related;
2696}
2697
Douglas Gregor604eb652010-08-11 02:15:33 +00002698/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00002699/// with DeclType. Return true if something definite is found.
2700static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00002701FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2702 QualType DeclType, SourceLocation DeclLoc,
2703 Expr *Init, QualType T2, bool AllowRvalues,
2704 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002705 assert(T2->isRecordType() && "Can only find conversions of record types.");
2706 CXXRecordDecl *T2RecordDecl
2707 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2708
Douglas Gregor604eb652010-08-11 02:15:33 +00002709 QualType ToType
2710 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2711 : DeclType;
2712
Sebastian Redl4680bf22010-06-30 18:13:39 +00002713 OverloadCandidateSet CandidateSet(DeclLoc);
2714 const UnresolvedSetImpl *Conversions
2715 = T2RecordDecl->getVisibleConversionFunctions();
2716 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2717 E = Conversions->end(); I != E; ++I) {
2718 NamedDecl *D = *I;
2719 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2720 if (isa<UsingShadowDecl>(D))
2721 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2722
2723 FunctionTemplateDecl *ConvTemplate
2724 = dyn_cast<FunctionTemplateDecl>(D);
2725 CXXConversionDecl *Conv;
2726 if (ConvTemplate)
2727 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2728 else
2729 Conv = cast<CXXConversionDecl>(D);
2730
Douglas Gregor604eb652010-08-11 02:15:33 +00002731 // If this is an explicit conversion, and we're not allowed to consider
2732 // explicit conversions, skip it.
2733 if (!AllowExplicit && Conv->isExplicit())
2734 continue;
2735
2736 if (AllowRvalues) {
2737 bool DerivedToBase = false;
2738 bool ObjCConversion = false;
2739 if (!ConvTemplate &&
2740 S.CompareReferenceRelationship(DeclLoc,
2741 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2742 DeclType.getNonReferenceType().getUnqualifiedType(),
2743 DerivedToBase, ObjCConversion)
2744 == Sema::Ref_Incompatible)
2745 continue;
2746 } else {
2747 // If the conversion function doesn't return a reference type,
2748 // it can't be considered for this conversion. An rvalue reference
2749 // is only acceptable if its referencee is a function type.
2750
2751 const ReferenceType *RefType =
2752 Conv->getConversionType()->getAs<ReferenceType>();
2753 if (!RefType ||
2754 (!RefType->isLValueReferenceType() &&
2755 !RefType->getPointeeType()->isFunctionType()))
2756 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002757 }
Douglas Gregor604eb652010-08-11 02:15:33 +00002758
2759 if (ConvTemplate)
2760 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2761 Init, ToType, CandidateSet);
2762 else
2763 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2764 ToType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002765 }
2766
2767 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00002768 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002769 case OR_Success:
2770 // C++ [over.ics.ref]p1:
2771 //
2772 // [...] If the parameter binds directly to the result of
2773 // applying a conversion function to the argument
2774 // expression, the implicit conversion sequence is a
2775 // user-defined conversion sequence (13.3.3.1.2), with the
2776 // second standard conversion sequence either an identity
2777 // conversion or, if the conversion function returns an
2778 // entity of a type that is a derived class of the parameter
2779 // type, a derived-to-base Conversion.
2780 if (!Best->FinalConversion.DirectBinding)
2781 return false;
2782
2783 ICS.setUserDefined();
2784 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2785 ICS.UserDefined.After = Best->FinalConversion;
2786 ICS.UserDefined.ConversionFunction = Best->Function;
2787 ICS.UserDefined.EllipsisConversion = false;
2788 assert(ICS.UserDefined.After.ReferenceBinding &&
2789 ICS.UserDefined.After.DirectBinding &&
2790 "Expected a direct reference binding!");
2791 return true;
2792
2793 case OR_Ambiguous:
2794 ICS.setAmbiguous();
2795 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2796 Cand != CandidateSet.end(); ++Cand)
2797 if (Cand->Viable)
2798 ICS.Ambiguous.addConversion(Cand->Function);
2799 return true;
2800
2801 case OR_No_Viable_Function:
2802 case OR_Deleted:
2803 // There was no suitable conversion, or we found a deleted
2804 // conversion; continue with other checks.
2805 return false;
2806 }
Eric Christopher1c3d5022010-06-30 18:36:32 +00002807
2808 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002809}
2810
Douglas Gregorabe183d2010-04-13 16:31:36 +00002811/// \brief Compute an implicit conversion sequence for reference
2812/// initialization.
2813static ImplicitConversionSequence
2814TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2815 SourceLocation DeclLoc,
2816 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002817 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002818 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2819
2820 // Most paths end in a failed conversion.
2821 ImplicitConversionSequence ICS;
2822 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2823
2824 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2825 QualType T2 = Init->getType();
2826
2827 // If the initializer is the address of an overloaded function, try
2828 // to resolve the overloaded function. If all goes well, T2 is the
2829 // type of the resulting function.
2830 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2831 DeclAccessPair Found;
2832 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2833 false, Found))
2834 T2 = Fn->getType();
2835 }
2836
2837 // Compute some basic properties of the types and the initializer.
2838 bool isRValRef = DeclType->isRValueReferenceType();
2839 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002840 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002841 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002842 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002843 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2844 ObjCConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002845
Douglas Gregorabe183d2010-04-13 16:31:36 +00002846
Sebastian Redl4680bf22010-06-30 18:13:39 +00002847 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00002848 // A reference to type "cv1 T1" is initialized by an expression
2849 // of type "cv2 T2" as follows:
2850
Sebastian Redl4680bf22010-06-30 18:13:39 +00002851 // -- If reference is an lvalue reference and the initializer expression
2852 // The next bullet point (T1 is a function) is pretty much equivalent to this
2853 // one, so it's handled here.
2854 if (!isRValRef || T1->isFunctionType()) {
2855 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2856 // reference-compatible with "cv2 T2," or
2857 //
2858 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2859 if (InitCategory.isLValue() &&
2860 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002861 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00002862 // When a parameter of reference type binds directly (8.5.3)
2863 // to an argument expression, the implicit conversion sequence
2864 // is the identity conversion, unless the argument expression
2865 // has a type that is a derived class of the parameter type,
2866 // in which case the implicit conversion sequence is a
2867 // derived-to-base Conversion (13.3.3.1).
2868 ICS.setStandard();
2869 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00002870 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2871 : ObjCConversion? ICK_Compatible_Conversion
2872 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002873 ICS.Standard.Third = ICK_Identity;
2874 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2875 ICS.Standard.setToType(0, T2);
2876 ICS.Standard.setToType(1, T1);
2877 ICS.Standard.setToType(2, T1);
2878 ICS.Standard.ReferenceBinding = true;
2879 ICS.Standard.DirectBinding = true;
2880 ICS.Standard.RRefBinding = isRValRef;
2881 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002882
Sebastian Redl4680bf22010-06-30 18:13:39 +00002883 // Nothing more to do: the inaccessibility/ambiguity check for
2884 // derived-to-base conversions is suppressed when we're
2885 // computing the implicit conversion sequence (C++
2886 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002887 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002888 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00002889
Sebastian Redl4680bf22010-06-30 18:13:39 +00002890 // -- has a class type (i.e., T2 is a class type), where T1 is
2891 // not reference-related to T2, and can be implicitly
2892 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2893 // is reference-compatible with "cv3 T3" 92) (this
2894 // conversion is selected by enumerating the applicable
2895 // conversion functions (13.3.1.6) and choosing the best
2896 // one through overload resolution (13.3)),
2897 if (!SuppressUserConversions && T2->isRecordType() &&
2898 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2899 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00002900 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2901 Init, T2, /*AllowRvalues=*/false,
2902 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00002903 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002904 }
2905 }
2906
Sebastian Redl4680bf22010-06-30 18:13:39 +00002907 // -- Otherwise, the reference shall be an lvalue reference to a
2908 // non-volatile const type (i.e., cv1 shall be const), or the reference
2909 // shall be an rvalue reference and the initializer expression shall be
2910 // an rvalue or have a function type.
Douglas Gregor66821b52010-04-18 09:22:00 +00002911 //
2912 // We actually handle one oddity of C++ [over.ics.ref] at this
2913 // point, which is that, due to p2 (which short-circuits reference
2914 // binding by only attempting a simple conversion for non-direct
2915 // bindings) and p3's strange wording, we allow a const volatile
2916 // reference to bind to an rvalue. Hence the check for the presence
2917 // of "const" rather than checking for "const" being the only
2918 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00002919 // This is also the point where rvalue references and lvalue inits no longer
2920 // go together.
2921 if ((!isRValRef && !T1.isConstQualified()) ||
2922 (isRValRef && InitCategory.isLValue()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00002923 return ICS;
2924
Sebastian Redl4680bf22010-06-30 18:13:39 +00002925 // -- If T1 is a function type, then
2926 // -- if T2 is the same type as T1, the reference is bound to the
2927 // initializer expression lvalue;
2928 // -- if T2 is a class type and the initializer expression can be
2929 // implicitly converted to an lvalue of type T1 [...], the
2930 // reference is bound to the function lvalue that is the result
2931 // of the conversion;
2932 // This is the same as for the lvalue case above, so it was handled there.
2933 // -- otherwise, the program is ill-formed.
2934 // This is the one difference to the lvalue case.
2935 if (T1->isFunctionType())
2936 return ICS;
2937
2938 // -- Otherwise, if T2 is a class type and
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002939 // -- the initializer expression is an rvalue and "cv1 T1"
2940 // is reference-compatible with "cv2 T2," or
Douglas Gregorabe183d2010-04-13 16:31:36 +00002941 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002942 // -- T1 is not reference-related to T2 and the initializer
2943 // expression can be implicitly converted to an rvalue
2944 // of type "cv3 T3" (this conversion is selected by
2945 // enumerating the applicable conversion functions
2946 // (13.3.1.6) and choosing the best one through overload
2947 // resolution (13.3)),
Douglas Gregorabe183d2010-04-13 16:31:36 +00002948 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002949 // then the reference is bound to the initializer
2950 // expression rvalue in the first case and to the object
2951 // that is the result of the conversion in the second case
2952 // (or, in either case, to the appropriate base class
2953 // subobject of the object).
Douglas Gregor604eb652010-08-11 02:15:33 +00002954 if (T2->isRecordType()) {
2955 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2956 // direct binding in C++0x but not in C++03.
2957 if (InitCategory.isRValue() &&
2958 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2959 ICS.setStandard();
2960 ICS.Standard.First = ICK_Identity;
2961 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2962 : ObjCConversion? ICK_Compatible_Conversion
2963 : ICK_Identity;
2964 ICS.Standard.Third = ICK_Identity;
2965 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2966 ICS.Standard.setToType(0, T2);
2967 ICS.Standard.setToType(1, T1);
2968 ICS.Standard.setToType(2, T1);
2969 ICS.Standard.ReferenceBinding = true;
2970 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
2971 ICS.Standard.RRefBinding = isRValRef;
2972 ICS.Standard.CopyConstructor = 0;
2973 return ICS;
2974 }
2975
2976 // Second case: not reference-related.
2977 if (RefRelationship == Sema::Ref_Incompatible &&
2978 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2979 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2980 Init, T2, /*AllowRvalues=*/true,
2981 AllowExplicit))
2982 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002983 }
Douglas Gregor604eb652010-08-11 02:15:33 +00002984
Douglas Gregorabe183d2010-04-13 16:31:36 +00002985 // -- Otherwise, a temporary of type "cv1 T1" is created and
2986 // initialized from the initializer expression using the
2987 // rules for a non-reference copy initialization (8.5). The
2988 // reference is then bound to the temporary. If T1 is
2989 // reference-related to T2, cv1 must be the same
2990 // cv-qualification as, or greater cv-qualification than,
2991 // cv2; otherwise, the program is ill-formed.
2992 if (RefRelationship == Sema::Ref_Related) {
2993 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2994 // we would be reference-compatible or reference-compatible with
2995 // added qualification. But that wasn't the case, so the reference
2996 // initialization fails.
2997 return ICS;
2998 }
2999
3000 // If at least one of the types is a class type, the types are not
3001 // related, and we aren't allowed any user conversions, the
3002 // reference binding fails. This case is important for breaking
3003 // recursion, since TryImplicitConversion below will attempt to
3004 // create a temporary through the use of a copy constructor.
3005 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3006 (T1->isRecordType() || T2->isRecordType()))
3007 return ICS;
3008
3009 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00003010 // When a parameter of reference type is not bound directly to
3011 // an argument expression, the conversion sequence is the one
3012 // required to convert the argument expression to the
3013 // underlying type of the reference according to
3014 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3015 // to copy-initializing a temporary of the underlying type with
3016 // the argument expression. Any difference in top-level
3017 // cv-qualification is subsumed by the initialization itself
3018 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00003019 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3020 /*AllowExplicit=*/false,
3021 /*InOverloadResolution=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003022
3023 // Of course, that's still a reference binding.
3024 if (ICS.isStandard()) {
3025 ICS.Standard.ReferenceBinding = true;
3026 ICS.Standard.RRefBinding = isRValRef;
3027 } else if (ICS.isUserDefined()) {
3028 ICS.UserDefined.After.ReferenceBinding = true;
3029 ICS.UserDefined.After.RRefBinding = isRValRef;
3030 }
3031 return ICS;
3032}
3033
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003034/// TryCopyInitialization - Try to copy-initialize a value of type
3035/// ToType from the expression From. Return the implicit conversion
3036/// sequence required to pass this argument, which may be a bad
3037/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00003038/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00003039/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00003040static ImplicitConversionSequence
3041TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00003042 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00003043 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003044 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00003045 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003046 /*FIXME:*/From->getLocStart(),
3047 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003048 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003049
John McCall120d63c2010-08-24 20:38:10 +00003050 return TryImplicitConversion(S, From, ToType,
3051 SuppressUserConversions,
3052 /*AllowExplicit=*/false,
3053 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003054}
3055
Douglas Gregor96176b32008-11-18 23:14:02 +00003056/// TryObjectArgumentInitialization - Try to initialize the object
3057/// parameter of the given member function (@c Method) from the
3058/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00003059static ImplicitConversionSequence
3060TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3061 CXXMethodDecl *Method,
3062 CXXRecordDecl *ActingContext) {
3063 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003064 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3065 // const volatile object.
3066 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3067 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00003068 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00003069
3070 // Set up the conversion sequence as a "bad" conversion, to allow us
3071 // to exit early.
3072 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00003073
3074 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00003075 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00003076 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00003077 FromType = PT->getPointeeType();
3078
3079 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00003080
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003081 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00003082 // where X is the class of which the function is a member
3083 // (C++ [over.match.funcs]p4). However, when finding an implicit
3084 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00003085 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00003086 // (C++ [over.match.funcs]p5). We perform a simplified version of
3087 // reference binding here, that allows class rvalues to bind to
3088 // non-constant references.
3089
3090 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3091 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall120d63c2010-08-24 20:38:10 +00003092 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00003093 if (ImplicitParamType.getCVRQualifiers()
3094 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00003095 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00003096 ICS.setBad(BadConversionSequence::bad_qualifiers,
3097 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003098 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003099 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003100
3101 // Check that we have either the same type or a derived type. It
3102 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00003103 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00003104 ImplicitConversionKind SecondKind;
3105 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3106 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00003107 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00003108 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00003109 else {
John McCallb1bdc622010-02-25 01:37:24 +00003110 ICS.setBad(BadConversionSequence::unrelated_class,
3111 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003112 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003113 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003114
3115 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00003116 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003117 ICS.Standard.setAsIdentityConversion();
3118 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003119 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003120 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003121 ICS.Standard.ReferenceBinding = true;
3122 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00003123 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003124 return ICS;
3125}
3126
3127/// PerformObjectArgumentInitialization - Perform initialization of
3128/// the implicit object parameter for the given Method with the given
3129/// expression.
3130bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00003131Sema::PerformObjectArgumentInitialization(Expr *&From,
3132 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003133 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003134 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003135 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003136 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003137 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003138
Ted Kremenek6217b802009-07-29 21:53:49 +00003139 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003140 FromRecordType = PT->getPointeeType();
3141 DestType = Method->getThisType(Context);
3142 } else {
3143 FromRecordType = From->getType();
3144 DestType = ImplicitParamRecordType;
3145 }
3146
John McCall701c89e2009-12-03 04:06:58 +00003147 // Note that we always use the true parent context when performing
3148 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003149 ImplicitConversionSequence ICS
John McCall120d63c2010-08-24 20:38:10 +00003150 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall701c89e2009-12-03 04:06:58 +00003151 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00003152 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00003153 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003154 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003155 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003156
Douglas Gregor5fccd362010-03-03 23:55:11 +00003157 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00003158 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00003159
Douglas Gregor5fccd362010-03-03 23:55:11 +00003160 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlssonf1b48b72010-04-24 16:57:13 +00003161 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +00003162 From->getType()->isPointerType() ?
3163 ImplicitCastExpr::RValue : ImplicitCastExpr::LValue);
Douglas Gregor96176b32008-11-18 23:14:02 +00003164 return false;
3165}
3166
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003167/// TryContextuallyConvertToBool - Attempt to contextually convert the
3168/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00003169static ImplicitConversionSequence
3170TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003171 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00003172 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003173 // FIXME: Are these flags correct?
3174 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003175 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00003176 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003177}
3178
3179/// PerformContextuallyConvertToBool - Perform a contextual conversion
3180/// of the expression From to bool (C++0x [conv]p3).
3181bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall120d63c2010-08-24 20:38:10 +00003182 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00003183 if (!ICS.isBad())
3184 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003185
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003186 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003187 return Diag(From->getSourceRange().getBegin(),
3188 diag::err_typecheck_bool_condition)
3189 << From->getType() << From->getSourceRange();
3190 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003191}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003192
3193/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3194/// expression From to 'id'.
John McCall120d63c2010-08-24 20:38:10 +00003195static ImplicitConversionSequence
3196TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3197 QualType Ty = S.Context.getObjCIdType();
3198 return TryImplicitConversion(S, From, Ty,
3199 // FIXME: Are these flags correct?
3200 /*SuppressUserConversions=*/false,
3201 /*AllowExplicit=*/true,
3202 /*InOverloadResolution=*/false);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003203}
John McCall120d63c2010-08-24 20:38:10 +00003204
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003205/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3206/// of the expression From to 'id'.
3207bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003208 QualType Ty = Context.getObjCIdType();
John McCall120d63c2010-08-24 20:38:10 +00003209 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003210 if (!ICS.isBad())
3211 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3212 return true;
3213}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003214
Douglas Gregorc30614b2010-06-29 23:17:37 +00003215/// \brief Attempt to convert the given expression to an integral or
3216/// enumeration type.
3217///
3218/// This routine will attempt to convert an expression of class type to an
3219/// integral or enumeration type, if that class type only has a single
3220/// conversion to an integral or enumeration type.
3221///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003222/// \param Loc The source location of the construct that requires the
3223/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003224///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003225/// \param FromE The expression we're converting from.
3226///
3227/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3228/// have integral or enumeration type.
3229///
3230/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3231/// incomplete class type.
3232///
3233/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3234/// explicit conversion function (because no implicit conversion functions
3235/// were available). This is a recovery mode.
3236///
3237/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3238/// showing which conversion was picked.
3239///
3240/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3241/// conversion function that could convert to integral or enumeration type.
3242///
3243/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3244/// usable conversion function.
3245///
3246/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3247/// function, which may be an extension in this case.
3248///
3249/// \returns The expression, converted to an integral or enumeration type if
3250/// successful.
John McCall60d7b3a2010-08-24 06:29:42 +00003251ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003252Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003253 const PartialDiagnostic &NotIntDiag,
3254 const PartialDiagnostic &IncompleteDiag,
3255 const PartialDiagnostic &ExplicitConvDiag,
3256 const PartialDiagnostic &ExplicitConvNote,
3257 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003258 const PartialDiagnostic &AmbigNote,
3259 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00003260 // We can't perform any more checking for type-dependent expressions.
3261 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00003262 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003263
3264 // If the expression already has integral or enumeration type, we're golden.
3265 QualType T = From->getType();
3266 if (T->isIntegralOrEnumerationType())
John McCall9ae2f072010-08-23 23:25:46 +00003267 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003268
3269 // FIXME: Check for missing '()' if T is a function type?
3270
3271 // If we don't have a class type in C++, there's no way we can get an
3272 // expression of integral or enumeration type.
3273 const RecordType *RecordTy = T->getAs<RecordType>();
3274 if (!RecordTy || !getLangOptions().CPlusPlus) {
3275 Diag(Loc, NotIntDiag)
3276 << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00003277 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003278 }
3279
3280 // We must have a complete class type.
3281 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00003282 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003283
3284 // Look for a conversion to an integral or enumeration type.
3285 UnresolvedSet<4> ViableConversions;
3286 UnresolvedSet<4> ExplicitConversions;
3287 const UnresolvedSetImpl *Conversions
3288 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3289
3290 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3291 E = Conversions->end();
3292 I != E;
3293 ++I) {
3294 if (CXXConversionDecl *Conversion
3295 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3296 if (Conversion->getConversionType().getNonReferenceType()
3297 ->isIntegralOrEnumerationType()) {
3298 if (Conversion->isExplicit())
3299 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3300 else
3301 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3302 }
3303 }
3304
3305 switch (ViableConversions.size()) {
3306 case 0:
3307 if (ExplicitConversions.size() == 1) {
3308 DeclAccessPair Found = ExplicitConversions[0];
3309 CXXConversionDecl *Conversion
3310 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3311
3312 // The user probably meant to invoke the given explicit
3313 // conversion; use it.
3314 QualType ConvTy
3315 = Conversion->getConversionType().getNonReferenceType();
3316 std::string TypeStr;
3317 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3318
3319 Diag(Loc, ExplicitConvDiag)
3320 << T << ConvTy
3321 << FixItHint::CreateInsertion(From->getLocStart(),
3322 "static_cast<" + TypeStr + ">(")
3323 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3324 ")");
3325 Diag(Conversion->getLocation(), ExplicitConvNote)
3326 << ConvTy->isEnumeralType() << ConvTy;
3327
3328 // If we aren't in a SFINAE context, build a call to the
3329 // explicit conversion function.
3330 if (isSFINAEContext())
3331 return ExprError();
3332
3333 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCall9ae2f072010-08-23 23:25:46 +00003334 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003335 }
3336
3337 // We'll complain below about a non-integral condition type.
3338 break;
3339
3340 case 1: {
3341 // Apply this conversion.
3342 DeclAccessPair Found = ViableConversions[0];
3343 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003344
3345 CXXConversionDecl *Conversion
3346 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3347 QualType ConvTy
3348 = Conversion->getConversionType().getNonReferenceType();
3349 if (ConvDiag.getDiagID()) {
3350 if (isSFINAEContext())
3351 return ExprError();
3352
3353 Diag(Loc, ConvDiag)
3354 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3355 }
3356
John McCall9ae2f072010-08-23 23:25:46 +00003357 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003358 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorc30614b2010-06-29 23:17:37 +00003359 break;
3360 }
3361
3362 default:
3363 Diag(Loc, AmbigDiag)
3364 << T << From->getSourceRange();
3365 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3366 CXXConversionDecl *Conv
3367 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3368 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3369 Diag(Conv->getLocation(), AmbigNote)
3370 << ConvTy->isEnumeralType() << ConvTy;
3371 }
John McCall9ae2f072010-08-23 23:25:46 +00003372 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003373 }
3374
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003375 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00003376 Diag(Loc, NotIntDiag)
3377 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003378
John McCall9ae2f072010-08-23 23:25:46 +00003379 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003380}
3381
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003382/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003383/// candidate functions, using the given function call arguments. If
3384/// @p SuppressUserConversions, then don't allow user-defined
3385/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003386///
3387/// \para PartialOverloading true if we are performing "partial" overloading
3388/// based on an incomplete set of function arguments. This feature is used by
3389/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003390void
3391Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003392 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003393 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003394 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003395 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003396 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003397 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003398 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003399 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003400 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00003401 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003402
Douglas Gregor88a35142008-12-22 05:46:06 +00003403 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003404 if (!isa<CXXConstructorDecl>(Method)) {
3405 // If we get here, it's because we're calling a member function
3406 // that is named without a member access expression (e.g.,
3407 // "this->f") that was either written explicitly or created
3408 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003409 // function, e.g., X::f(). We use an empty type for the implied
3410 // object argument (C++ [over.call.func]p3), and the acting context
3411 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003412 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00003413 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003414 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003415 return;
3416 }
3417 // We treat a constructor like a non-member function, since its object
3418 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003419 }
3420
Douglas Gregorfd476482009-11-13 23:59:09 +00003421 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003422 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003423
Douglas Gregor7edfb692009-11-23 12:27:39 +00003424 // Overload resolution is always an unevaluated context.
3425 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3426
Douglas Gregor66724ea2009-11-14 01:20:54 +00003427 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3428 // C++ [class.copy]p3:
3429 // A member function template is never instantiated to perform the copy
3430 // of a class object to an object of its class type.
3431 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3432 if (NumArgs == 1 &&
3433 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003434 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3435 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003436 return;
3437 }
3438
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003439 // Add this candidate
3440 CandidateSet.push_back(OverloadCandidate());
3441 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003442 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003443 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003444 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003445 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003446 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003447
3448 unsigned NumArgsInProto = Proto->getNumArgs();
3449
3450 // (C++ 13.3.2p2): A candidate function having fewer than m
3451 // parameters is viable only if it has an ellipsis in its parameter
3452 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003453 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3454 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003455 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003456 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003457 return;
3458 }
3459
3460 // (C++ 13.3.2p2): A candidate function having more than m parameters
3461 // is viable only if the (m+1)st parameter has a default argument
3462 // (8.3.6). For the purposes of overload resolution, the
3463 // parameter list is truncated on the right, so that there are
3464 // exactly m parameters.
3465 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003466 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003467 // Not enough arguments.
3468 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003469 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003470 return;
3471 }
3472
3473 // Determine the implicit conversion sequences for each of the
3474 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003475 Candidate.Conversions.resize(NumArgs);
3476 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3477 if (ArgIdx < NumArgsInProto) {
3478 // (C++ 13.3.2p3): for F to be a viable function, there shall
3479 // exist for each argument an implicit conversion sequence
3480 // (13.3.3.1) that converts that argument to the corresponding
3481 // parameter of F.
3482 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003483 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003484 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003485 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003486 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003487 if (Candidate.Conversions[ArgIdx].isBad()) {
3488 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003489 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003490 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003491 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003492 } else {
3493 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3494 // argument for which there is no corresponding parameter is
3495 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003496 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003497 }
3498 }
3499}
3500
Douglas Gregor063daf62009-03-13 18:40:31 +00003501/// \brief Add all of the function declarations in the given function set to
3502/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003503void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003504 Expr **Args, unsigned NumArgs,
3505 OverloadCandidateSet& CandidateSet,
3506 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003507 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003508 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3509 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003510 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003511 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003512 cast<CXXMethodDecl>(FD)->getParent(),
3513 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003514 CandidateSet, SuppressUserConversions);
3515 else
John McCall9aa472c2010-03-19 07:35:19 +00003516 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003517 SuppressUserConversions);
3518 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003519 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003520 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3521 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003522 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003523 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003524 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00003525 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003526 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003527 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003528 else
John McCall9aa472c2010-03-19 07:35:19 +00003529 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003530 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003531 Args, NumArgs, CandidateSet,
3532 SuppressUserConversions);
3533 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003534 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003535}
3536
John McCall314be4e2009-11-17 07:50:12 +00003537/// AddMethodCandidate - Adds a named decl (which is some kind of
3538/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003539void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003540 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00003541 Expr **Args, unsigned NumArgs,
3542 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003543 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003544 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003545 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003546
3547 if (isa<UsingShadowDecl>(Decl))
3548 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3549
3550 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3551 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3552 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003553 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3554 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00003555 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003556 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003557 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003558 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003559 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00003560 ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003561 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003562 }
3563}
3564
Douglas Gregor96176b32008-11-18 23:14:02 +00003565/// AddMethodCandidate - Adds the given C++ member function to the set
3566/// of candidate functions, using the given function call arguments
3567/// and the object argument (@c Object). For example, in a call
3568/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3569/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3570/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003571/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003572void
John McCall9aa472c2010-03-19 07:35:19 +00003573Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003574 CXXRecordDecl *ActingContext, QualType ObjectType,
3575 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003576 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003577 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003578 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003579 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003580 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003581 assert(!isa<CXXConstructorDecl>(Method) &&
3582 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003583
Douglas Gregor3f396022009-09-28 04:47:19 +00003584 if (!CandidateSet.isNewCandidate(Method))
3585 return;
3586
Douglas Gregor7edfb692009-11-23 12:27:39 +00003587 // Overload resolution is always an unevaluated context.
3588 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3589
Douglas Gregor96176b32008-11-18 23:14:02 +00003590 // Add this candidate
3591 CandidateSet.push_back(OverloadCandidate());
3592 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003593 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003594 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003595 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003596 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003597
3598 unsigned NumArgsInProto = Proto->getNumArgs();
3599
3600 // (C++ 13.3.2p2): A candidate function having fewer than m
3601 // parameters is viable only if it has an ellipsis in its parameter
3602 // list (8.3.5).
3603 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3604 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003605 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003606 return;
3607 }
3608
3609 // (C++ 13.3.2p2): A candidate function having more than m parameters
3610 // is viable only if the (m+1)st parameter has a default argument
3611 // (8.3.6). For the purposes of overload resolution, the
3612 // parameter list is truncated on the right, so that there are
3613 // exactly m parameters.
3614 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3615 if (NumArgs < MinRequiredArgs) {
3616 // Not enough arguments.
3617 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003618 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003619 return;
3620 }
3621
3622 Candidate.Viable = true;
3623 Candidate.Conversions.resize(NumArgs + 1);
3624
John McCall701c89e2009-12-03 04:06:58 +00003625 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003626 // The implicit object argument is ignored.
3627 Candidate.IgnoreObjectArgument = true;
3628 else {
3629 // Determine the implicit conversion sequence for the object
3630 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003631 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003632 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3633 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003634 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003635 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003636 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003637 return;
3638 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003639 }
3640
3641 // Determine the implicit conversion sequences for each of the
3642 // arguments.
3643 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3644 if (ArgIdx < NumArgsInProto) {
3645 // (C++ 13.3.2p3): for F to be a viable function, there shall
3646 // exist for each argument an implicit conversion sequence
3647 // (13.3.3.1) that converts that argument to the corresponding
3648 // parameter of F.
3649 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003650 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003651 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003652 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003653 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003654 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003655 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003656 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003657 break;
3658 }
3659 } else {
3660 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3661 // argument for which there is no corresponding parameter is
3662 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003663 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003664 }
3665 }
3666}
Douglas Gregora9333192010-05-08 17:41:32 +00003667
Douglas Gregor6b906862009-08-21 00:16:32 +00003668/// \brief Add a C++ member function template as a candidate to the candidate
3669/// set, using template argument deduction to produce an appropriate member
3670/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003671void
Douglas Gregor6b906862009-08-21 00:16:32 +00003672Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003673 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003674 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003675 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003676 QualType ObjectType,
3677 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003678 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003679 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003680 if (!CandidateSet.isNewCandidate(MethodTmpl))
3681 return;
3682
Douglas Gregor6b906862009-08-21 00:16:32 +00003683 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003684 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003685 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003686 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003687 // candidate functions in the usual way.113) A given name can refer to one
3688 // or more function templates and also to a set of overloaded non-template
3689 // functions. In such a case, the candidate functions generated from each
3690 // function template are combined with the set of non-template candidate
3691 // functions.
John McCall5769d612010-02-08 23:07:23 +00003692 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003693 FunctionDecl *Specialization = 0;
3694 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003695 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003696 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003697 CandidateSet.push_back(OverloadCandidate());
3698 OverloadCandidate &Candidate = CandidateSet.back();
3699 Candidate.FoundDecl = FoundDecl;
3700 Candidate.Function = MethodTmpl->getTemplatedDecl();
3701 Candidate.Viable = false;
3702 Candidate.FailureKind = ovl_fail_bad_deduction;
3703 Candidate.IsSurrogate = false;
3704 Candidate.IgnoreObjectArgument = false;
3705 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3706 Info);
3707 return;
3708 }
Mike Stump1eb44332009-09-09 15:08:12 +00003709
Douglas Gregor6b906862009-08-21 00:16:32 +00003710 // Add the function template specialization produced by template argument
3711 // deduction as a candidate.
3712 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003713 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003714 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003715 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003716 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003717 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003718}
3719
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003720/// \brief Add a C++ function template specialization as a candidate
3721/// in the candidate set, using template argument deduction to produce
3722/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003723void
Douglas Gregore53060f2009-06-25 22:08:12 +00003724Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003725 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003726 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003727 Expr **Args, unsigned NumArgs,
3728 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003729 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003730 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3731 return;
3732
Douglas Gregore53060f2009-06-25 22:08:12 +00003733 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003734 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003735 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003736 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003737 // candidate functions in the usual way.113) A given name can refer to one
3738 // or more function templates and also to a set of overloaded non-template
3739 // functions. In such a case, the candidate functions generated from each
3740 // function template are combined with the set of non-template candidate
3741 // functions.
John McCall5769d612010-02-08 23:07:23 +00003742 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003743 FunctionDecl *Specialization = 0;
3744 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003745 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003746 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003747 CandidateSet.push_back(OverloadCandidate());
3748 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003749 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003750 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3751 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003752 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003753 Candidate.IsSurrogate = false;
3754 Candidate.IgnoreObjectArgument = false;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003755 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3756 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003757 return;
3758 }
Mike Stump1eb44332009-09-09 15:08:12 +00003759
Douglas Gregore53060f2009-06-25 22:08:12 +00003760 // Add the function template specialization produced by template argument
3761 // deduction as a candidate.
3762 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003763 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003764 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003765}
Mike Stump1eb44332009-09-09 15:08:12 +00003766
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003767/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003768/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003769/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003770/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003771/// (which may or may not be the same type as the type that the
3772/// conversion function produces).
3773void
3774Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003775 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003776 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003777 Expr *From, QualType ToType,
3778 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003779 assert(!Conversion->getDescribedFunctionTemplate() &&
3780 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003781 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003782 if (!CandidateSet.isNewCandidate(Conversion))
3783 return;
3784
Douglas Gregor7edfb692009-11-23 12:27:39 +00003785 // Overload resolution is always an unevaluated context.
3786 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3787
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003788 // Add this candidate
3789 CandidateSet.push_back(OverloadCandidate());
3790 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003791 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003792 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003793 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003794 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003795 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003796 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003797 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003798 Candidate.Viable = true;
3799 Candidate.Conversions.resize(1);
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003800
Douglas Gregorbca39322010-08-19 15:37:02 +00003801 // C++ [over.match.funcs]p4:
3802 // For conversion functions, the function is considered to be a member of
3803 // the class of the implicit implied object argument for the purpose of
3804 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003805 //
3806 // Determine the implicit conversion sequence for the implicit
3807 // object parameter.
3808 QualType ImplicitParamType = From->getType();
3809 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3810 ImplicitParamType = FromPtrType->getPointeeType();
3811 CXXRecordDecl *ConversionContext
3812 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3813
3814 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003815 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003816 ConversionContext);
3817
John McCall1d318332010-01-12 00:44:57 +00003818 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003819 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003820 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003821 return;
3822 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003823
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003824 // We won't go through a user-define type conversion function to convert a
3825 // derived to base as such conversions are given Conversion Rank. They only
3826 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3827 QualType FromCanon
3828 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3829 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3830 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3831 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003832 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003833 return;
3834 }
3835
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003836 // To determine what the conversion from the result of calling the
3837 // conversion function to the type we're eventually trying to
3838 // convert to (ToType), we need to synthesize a call to the
3839 // conversion function and attempt copy initialization from it. This
3840 // makes sure that we get the right semantics with respect to
3841 // lvalues/rvalues and the type. Fortunately, we can allocate this
3842 // call on the stack and we don't need its arguments to be
3843 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003844 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003845 From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00003846 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3847 Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00003848 CastExpr::CK_FunctionToPointerDecay,
John McCallf871d0c2010-08-07 06:22:56 +00003849 &ConversionRef, ImplicitCastExpr::RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00003850
3851 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003852 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3853 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00003854 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor63982352010-07-13 18:40:04 +00003855 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003856 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003857 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00003858 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003859 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003860 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003861
John McCall1d318332010-01-12 00:44:57 +00003862 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003863 case ImplicitConversionSequence::StandardConversion:
3864 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003865
3866 // C++ [over.ics.user]p3:
3867 // If the user-defined conversion is specified by a specialization of a
3868 // conversion function template, the second standard conversion sequence
3869 // shall have exact match rank.
3870 if (Conversion->getPrimaryTemplate() &&
3871 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3872 Candidate.Viable = false;
3873 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3874 }
3875
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003876 break;
3877
3878 case ImplicitConversionSequence::BadConversion:
3879 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003880 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003881 break;
3882
3883 default:
Mike Stump1eb44332009-09-09 15:08:12 +00003884 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003885 "Can only end up with a standard conversion sequence or failure");
3886 }
3887}
3888
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003889/// \brief Adds a conversion function template specialization
3890/// candidate to the overload set, using template argument deduction
3891/// to deduce the template arguments of the conversion function
3892/// template from the type that we are converting to (C++
3893/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00003894void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003895Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003896 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003897 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003898 Expr *From, QualType ToType,
3899 OverloadCandidateSet &CandidateSet) {
3900 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3901 "Only conversion function templates permitted here");
3902
Douglas Gregor3f396022009-09-28 04:47:19 +00003903 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3904 return;
3905
John McCall5769d612010-02-08 23:07:23 +00003906 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003907 CXXConversionDecl *Specialization = 0;
3908 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00003909 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003910 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003911 CandidateSet.push_back(OverloadCandidate());
3912 OverloadCandidate &Candidate = CandidateSet.back();
3913 Candidate.FoundDecl = FoundDecl;
3914 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3915 Candidate.Viable = false;
3916 Candidate.FailureKind = ovl_fail_bad_deduction;
3917 Candidate.IsSurrogate = false;
3918 Candidate.IgnoreObjectArgument = false;
3919 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3920 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003921 return;
3922 }
Mike Stump1eb44332009-09-09 15:08:12 +00003923
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003924 // Add the conversion function template specialization produced by
3925 // template argument deduction as a candidate.
3926 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003927 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00003928 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003929}
3930
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003931/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3932/// converts the given @c Object to a function pointer via the
3933/// conversion function @c Conversion, and then attempts to call it
3934/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3935/// the type of function that we'll eventually be calling.
3936void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003937 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003938 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00003939 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00003940 QualType ObjectType,
3941 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003942 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003943 if (!CandidateSet.isNewCandidate(Conversion))
3944 return;
3945
Douglas Gregor7edfb692009-11-23 12:27:39 +00003946 // Overload resolution is always an unevaluated context.
3947 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3948
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003949 CandidateSet.push_back(OverloadCandidate());
3950 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003951 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003952 Candidate.Function = 0;
3953 Candidate.Surrogate = Conversion;
3954 Candidate.Viable = true;
3955 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003956 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003957 Candidate.Conversions.resize(NumArgs + 1);
3958
3959 // Determine the implicit conversion sequence for the implicit
3960 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003961 ImplicitConversionSequence ObjectInit
John McCall120d63c2010-08-24 20:38:10 +00003962 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
3963 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003964 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003965 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003966 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00003967 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003968 return;
3969 }
3970
3971 // The first conversion is actually a user-defined conversion whose
3972 // first conversion is ObjectInit's standard conversion (which is
3973 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00003974 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003975 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00003976 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003977 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00003978 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003979 = Candidate.Conversions[0].UserDefined.Before;
3980 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3981
Mike Stump1eb44332009-09-09 15:08:12 +00003982 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003983 unsigned NumArgsInProto = Proto->getNumArgs();
3984
3985 // (C++ 13.3.2p2): A candidate function having fewer than m
3986 // parameters is viable only if it has an ellipsis in its parameter
3987 // list (8.3.5).
3988 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3989 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003990 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003991 return;
3992 }
3993
3994 // Function types don't have any default arguments, so just check if
3995 // we have enough arguments.
3996 if (NumArgs < NumArgsInProto) {
3997 // Not enough arguments.
3998 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003999 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004000 return;
4001 }
4002
4003 // Determine the implicit conversion sequences for each of the
4004 // arguments.
4005 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4006 if (ArgIdx < NumArgsInProto) {
4007 // (C++ 13.3.2p3): for F to be a viable function, there shall
4008 // exist for each argument an implicit conversion sequence
4009 // (13.3.3.1) that converts that argument to the corresponding
4010 // parameter of F.
4011 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004012 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004013 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004014 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004015 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00004016 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004017 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004018 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004019 break;
4020 }
4021 } else {
4022 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4023 // argument for which there is no corresponding parameter is
4024 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004025 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004026 }
4027 }
4028}
4029
Douglas Gregor063daf62009-03-13 18:40:31 +00004030/// \brief Add overload candidates for overloaded operators that are
4031/// member functions.
4032///
4033/// Add the overloaded operator candidates that are member functions
4034/// for the operator Op that was used in an operator expression such
4035/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4036/// CandidateSet will store the added overload candidates. (C++
4037/// [over.match.oper]).
4038void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4039 SourceLocation OpLoc,
4040 Expr **Args, unsigned NumArgs,
4041 OverloadCandidateSet& CandidateSet,
4042 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004043 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4044
4045 // C++ [over.match.oper]p3:
4046 // For a unary operator @ with an operand of a type whose
4047 // cv-unqualified version is T1, and for a binary operator @ with
4048 // a left operand of a type whose cv-unqualified version is T1 and
4049 // a right operand of a type whose cv-unqualified version is T2,
4050 // three sets of candidate functions, designated member
4051 // candidates, non-member candidates and built-in candidates, are
4052 // constructed as follows:
4053 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00004054
4055 // -- If T1 is a class type, the set of member candidates is the
4056 // result of the qualified lookup of T1::operator@
4057 // (13.3.1.1.1); otherwise, the set of member candidates is
4058 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00004059 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004060 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004061 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004062 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004063
John McCalla24dc2e2009-11-17 02:14:36 +00004064 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4065 LookupQualifiedName(Operators, T1Rec->getDecl());
4066 Operators.suppressDiagnostics();
4067
Mike Stump1eb44332009-09-09 15:08:12 +00004068 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004069 OperEnd = Operators.end();
4070 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00004071 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00004072 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00004073 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00004074 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00004075 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004076}
4077
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004078/// AddBuiltinCandidate - Add a candidate for a built-in
4079/// operator. ResultTy and ParamTys are the result and parameter types
4080/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004081/// arguments being passed to the candidate. IsAssignmentOperator
4082/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004083/// operator. NumContextualBoolArguments is the number of arguments
4084/// (at the beginning of the argument list) that will be contextually
4085/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00004086void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004087 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004088 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004089 bool IsAssignmentOperator,
4090 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00004091 // Overload resolution is always an unevaluated context.
4092 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
4093
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004094 // Add this candidate
4095 CandidateSet.push_back(OverloadCandidate());
4096 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004097 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004098 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004099 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004100 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004101 Candidate.BuiltinTypes.ResultTy = ResultTy;
4102 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4103 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4104
4105 // Determine the implicit conversion sequences for each of the
4106 // arguments.
4107 Candidate.Viable = true;
4108 Candidate.Conversions.resize(NumArgs);
4109 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004110 // C++ [over.match.oper]p4:
4111 // For the built-in assignment operators, conversions of the
4112 // left operand are restricted as follows:
4113 // -- no temporaries are introduced to hold the left operand, and
4114 // -- no user-defined conversions are applied to the left
4115 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00004116 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004117 //
4118 // We block these conversions by turning off user-defined
4119 // conversions, since that is the only way that initialization of
4120 // a reference to a non-class type can occur from something that
4121 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004122 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004123 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004124 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00004125 Candidate.Conversions[ArgIdx]
4126 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004127 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004128 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004129 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004130 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004131 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004132 }
John McCall1d318332010-01-12 00:44:57 +00004133 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004134 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004135 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004136 break;
4137 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004138 }
4139}
4140
4141/// BuiltinCandidateTypeSet - A set of types that will be used for the
4142/// candidate operator functions for built-in operators (C++
4143/// [over.built]). The types are separated into pointer types and
4144/// enumeration types.
4145class BuiltinCandidateTypeSet {
4146 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004147 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004148
4149 /// PointerTypes - The set of pointer types that will be used in the
4150 /// built-in candidates.
4151 TypeSet PointerTypes;
4152
Sebastian Redl78eb8742009-04-19 21:53:20 +00004153 /// MemberPointerTypes - The set of member pointer types that will be
4154 /// used in the built-in candidates.
4155 TypeSet MemberPointerTypes;
4156
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004157 /// EnumerationTypes - The set of enumeration types that will be
4158 /// used in the built-in candidates.
4159 TypeSet EnumerationTypes;
4160
Douglas Gregor26bcf672010-05-19 03:21:00 +00004161 /// \brief The set of vector types that will be used in the built-in
4162 /// candidates.
4163 TypeSet VectorTypes;
4164
Douglas Gregor5842ba92009-08-24 15:23:48 +00004165 /// Sema - The semantic analysis instance where we are building the
4166 /// candidate type set.
4167 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004168
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004169 /// Context - The AST context in which we will build the type sets.
4170 ASTContext &Context;
4171
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004172 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4173 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00004174 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004175
4176public:
4177 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004178 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004179
Mike Stump1eb44332009-09-09 15:08:12 +00004180 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00004181 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004182
Douglas Gregor573d9c32009-10-21 23:19:44 +00004183 void AddTypesConvertedFrom(QualType Ty,
4184 SourceLocation Loc,
4185 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004186 bool AllowExplicitConversions,
4187 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004188
4189 /// pointer_begin - First pointer type found;
4190 iterator pointer_begin() { return PointerTypes.begin(); }
4191
Sebastian Redl78eb8742009-04-19 21:53:20 +00004192 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004193 iterator pointer_end() { return PointerTypes.end(); }
4194
Sebastian Redl78eb8742009-04-19 21:53:20 +00004195 /// member_pointer_begin - First member pointer type found;
4196 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4197
4198 /// member_pointer_end - Past the last member pointer type found;
4199 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4200
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004201 /// enumeration_begin - First enumeration type found;
4202 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4203
Sebastian Redl78eb8742009-04-19 21:53:20 +00004204 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004205 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004206
4207 iterator vector_begin() { return VectorTypes.begin(); }
4208 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004209};
4210
Sebastian Redl78eb8742009-04-19 21:53:20 +00004211/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004212/// the set of pointer types along with any more-qualified variants of
4213/// that type. For example, if @p Ty is "int const *", this routine
4214/// will add "int const *", "int const volatile *", "int const
4215/// restrict *", and "int const volatile restrict *" to the set of
4216/// pointer types. Returns true if the add of @p Ty itself succeeded,
4217/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004218///
4219/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004220bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00004221BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4222 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00004223
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004224 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004225 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004226 return false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004227
4228 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00004229 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004230 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004231 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004232 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004233 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004234 buildObjCPtr = true;
4235 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004236 else
4237 assert(false && "type was not a pointer type!");
4238 }
4239 else
4240 PointeeTy = PointerTy->getPointeeType();
4241
Sebastian Redla9efada2009-11-18 20:39:26 +00004242 // Don't add qualified variants of arrays. For one, they're not allowed
4243 // (the qualifier would sink to the element type), and for another, the
4244 // only overload situation where it matters is subscript or pointer +- int,
4245 // and those shouldn't have qualifier variants anyway.
4246 if (PointeeTy->isArrayType())
4247 return true;
John McCall0953e762009-09-24 19:53:00 +00004248 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00004249 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00004250 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004251 bool hasVolatile = VisibleQuals.hasVolatile();
4252 bool hasRestrict = VisibleQuals.hasRestrict();
4253
John McCall0953e762009-09-24 19:53:00 +00004254 // Iterate through all strict supersets of BaseCVR.
4255 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4256 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004257 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4258 // in the types.
4259 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4260 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00004261 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004262 if (!buildObjCPtr)
4263 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4264 else
4265 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004266 }
4267
4268 return true;
4269}
4270
Sebastian Redl78eb8742009-04-19 21:53:20 +00004271/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4272/// to the set of pointer types along with any more-qualified variants of
4273/// that type. For example, if @p Ty is "int const *", this routine
4274/// will add "int const *", "int const volatile *", "int const
4275/// restrict *", and "int const volatile restrict *" to the set of
4276/// pointer types. Returns true if the add of @p Ty itself succeeded,
4277/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004278///
4279/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004280bool
4281BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4282 QualType Ty) {
4283 // Insert this type.
4284 if (!MemberPointerTypes.insert(Ty))
4285 return false;
4286
John McCall0953e762009-09-24 19:53:00 +00004287 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4288 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00004289
John McCall0953e762009-09-24 19:53:00 +00004290 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004291 // Don't add qualified variants of arrays. For one, they're not allowed
4292 // (the qualifier would sink to the element type), and for another, the
4293 // only overload situation where it matters is subscript or pointer +- int,
4294 // and those shouldn't have qualifier variants anyway.
4295 if (PointeeTy->isArrayType())
4296 return true;
John McCall0953e762009-09-24 19:53:00 +00004297 const Type *ClassTy = PointerTy->getClass();
4298
4299 // Iterate through all strict supersets of the pointee type's CVR
4300 // qualifiers.
4301 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4302 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4303 if ((CVR | BaseCVR) != CVR) continue;
4304
4305 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4306 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00004307 }
4308
4309 return true;
4310}
4311
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004312/// AddTypesConvertedFrom - Add each of the types to which the type @p
4313/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00004314/// primarily interested in pointer types and enumeration types. We also
4315/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004316/// AllowUserConversions is true if we should look at the conversion
4317/// functions of a class type, and AllowExplicitConversions if we
4318/// should also include the explicit conversion functions of a class
4319/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004320void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004321BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004322 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004323 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004324 bool AllowExplicitConversions,
4325 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004326 // Only deal with canonical types.
4327 Ty = Context.getCanonicalType(Ty);
4328
4329 // Look through reference types; they aren't part of the type of an
4330 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004331 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004332 Ty = RefTy->getPointeeType();
4333
4334 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004335 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004336
Sebastian Redla65b5512009-11-05 16:36:20 +00004337 // If we're dealing with an array type, decay to the pointer.
4338 if (Ty->isArrayType())
4339 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004340 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4341 PointerTypes.insert(Ty);
4342 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004343 // Insert our type, and its more-qualified variants, into the set
4344 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004345 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004346 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00004347 } else if (Ty->isMemberPointerType()) {
4348 // Member pointers are far easier, since the pointee can't be converted.
4349 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4350 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004351 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00004352 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004353 } else if (Ty->isVectorType()) {
4354 VectorTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004355 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004356 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004357 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00004358 // No conversion functions in incomplete types.
4359 return;
4360 }
Mike Stump1eb44332009-09-09 15:08:12 +00004361
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004362 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00004363 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00004364 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004365 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004366 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004367 NamedDecl *D = I.getDecl();
4368 if (isa<UsingShadowDecl>(D))
4369 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004370
Mike Stump1eb44332009-09-09 15:08:12 +00004371 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004372 // about which builtin types we can convert to.
John McCall32daa422010-03-31 01:36:47 +00004373 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004374 continue;
4375
John McCall32daa422010-03-31 01:36:47 +00004376 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004377 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004378 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004379 VisibleQuals);
4380 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004381 }
4382 }
4383 }
4384}
4385
Douglas Gregor19b7b152009-08-24 13:43:27 +00004386/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4387/// the volatile- and non-volatile-qualified assignment operators for the
4388/// given type to the candidate set.
4389static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4390 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004391 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004392 unsigned NumArgs,
4393 OverloadCandidateSet &CandidateSet) {
4394 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004395
Douglas Gregor19b7b152009-08-24 13:43:27 +00004396 // T& operator=(T&, T)
4397 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4398 ParamTypes[1] = T;
4399 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4400 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004401
Douglas Gregor19b7b152009-08-24 13:43:27 +00004402 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4403 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004404 ParamTypes[0]
4405 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004406 ParamTypes[1] = T;
4407 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004408 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004409 }
4410}
Mike Stump1eb44332009-09-09 15:08:12 +00004411
Sebastian Redl9994a342009-10-25 17:03:50 +00004412/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4413/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004414static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4415 Qualifiers VRQuals;
4416 const RecordType *TyRec;
4417 if (const MemberPointerType *RHSMPType =
4418 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004419 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004420 else
4421 TyRec = ArgExpr->getType()->getAs<RecordType>();
4422 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004423 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004424 VRQuals.addVolatile();
4425 VRQuals.addRestrict();
4426 return VRQuals;
4427 }
4428
4429 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004430 if (!ClassDecl->hasDefinition())
4431 return VRQuals;
4432
John McCalleec51cf2010-01-20 00:46:10 +00004433 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004434 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004435
John McCalleec51cf2010-01-20 00:46:10 +00004436 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004437 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004438 NamedDecl *D = I.getDecl();
4439 if (isa<UsingShadowDecl>(D))
4440 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4441 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004442 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4443 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4444 CanTy = ResTypeRef->getPointeeType();
4445 // Need to go down the pointer/mempointer chain and add qualifiers
4446 // as see them.
4447 bool done = false;
4448 while (!done) {
4449 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4450 CanTy = ResTypePtr->getPointeeType();
4451 else if (const MemberPointerType *ResTypeMPtr =
4452 CanTy->getAs<MemberPointerType>())
4453 CanTy = ResTypeMPtr->getPointeeType();
4454 else
4455 done = true;
4456 if (CanTy.isVolatileQualified())
4457 VRQuals.addVolatile();
4458 if (CanTy.isRestrictQualified())
4459 VRQuals.addRestrict();
4460 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4461 return VRQuals;
4462 }
4463 }
4464 }
4465 return VRQuals;
4466}
4467
Douglas Gregor74253732008-11-19 15:42:04 +00004468/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4469/// operator overloads to the candidate set (C++ [over.built]), based
4470/// on the operator @p Op and the arguments given. For example, if the
4471/// operator is a binary '+', this routine might add "int
4472/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004473void
Mike Stump1eb44332009-09-09 15:08:12 +00004474Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004475 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00004476 Expr **Args, unsigned NumArgs,
4477 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004478 // The set of "promoted arithmetic types", which are the arithmetic
4479 // types are that preserved by promotion (C++ [over.built]p2). Note
4480 // that the first few of these types are the promoted integral
4481 // types; these types need to be first.
4482 // FIXME: What about complex?
4483 const unsigned FirstIntegralType = 0;
4484 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00004485 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004486 LastPromotedIntegralType = 13;
4487 const unsigned FirstPromotedArithmeticType = 7,
4488 LastPromotedArithmeticType = 16;
4489 const unsigned NumArithmeticTypes = 16;
4490 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00004491 Context.BoolTy, Context.CharTy, Context.WCharTy,
4492// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004493 Context.SignedCharTy, Context.ShortTy,
4494 Context.UnsignedCharTy, Context.UnsignedShortTy,
4495 Context.IntTy, Context.LongTy, Context.LongLongTy,
4496 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4497 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4498 };
Douglas Gregor652371a2009-10-21 22:01:30 +00004499 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4500 "Invalid first promoted integral type");
4501 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4502 == Context.UnsignedLongLongTy &&
4503 "Invalid last promoted integral type");
4504 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4505 "Invalid first promoted arithmetic type");
4506 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4507 == Context.LongDoubleTy &&
4508 "Invalid last promoted arithmetic type");
4509
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004510 // Find all of the types that the arguments can convert to, but only
4511 // if the operator we're looking at has built-in operator candidates
4512 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004513 Qualifiers VisibleTypeConversionsQuals;
4514 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004515 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4516 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4517
Douglas Gregor5842ba92009-08-24 15:23:48 +00004518 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004519 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4520 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4521 OpLoc,
4522 true,
4523 (Op == OO_Exclaim ||
4524 Op == OO_AmpAmp ||
4525 Op == OO_PipePipe),
4526 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004527
4528 bool isComparison = false;
4529 switch (Op) {
4530 case OO_None:
4531 case NUM_OVERLOADED_OPERATORS:
4532 assert(false && "Expected an overloaded operator");
4533 break;
4534
Douglas Gregor74253732008-11-19 15:42:04 +00004535 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00004536 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00004537 goto UnaryStar;
4538 else
4539 goto BinaryStar;
4540 break;
4541
4542 case OO_Plus: // '+' is either unary or binary
4543 if (NumArgs == 1)
4544 goto UnaryPlus;
4545 else
4546 goto BinaryPlus;
4547 break;
4548
4549 case OO_Minus: // '-' is either unary or binary
4550 if (NumArgs == 1)
4551 goto UnaryMinus;
4552 else
4553 goto BinaryMinus;
4554 break;
4555
4556 case OO_Amp: // '&' is either unary or binary
4557 if (NumArgs == 1)
4558 goto UnaryAmp;
4559 else
4560 goto BinaryAmp;
4561
4562 case OO_PlusPlus:
4563 case OO_MinusMinus:
4564 // C++ [over.built]p3:
4565 //
4566 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4567 // is either volatile or empty, there exist candidate operator
4568 // functions of the form
4569 //
4570 // VQ T& operator++(VQ T&);
4571 // T operator++(VQ T&, int);
4572 //
4573 // C++ [over.built]p4:
4574 //
4575 // For every pair (T, VQ), where T is an arithmetic type other
4576 // than bool, and VQ is either volatile or empty, there exist
4577 // candidate operator functions of the form
4578 //
4579 // VQ T& operator--(VQ T&);
4580 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00004581 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00004582 Arith < NumArithmeticTypes; ++Arith) {
4583 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00004584 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004585 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00004586
4587 // Non-volatile version.
4588 if (NumArgs == 1)
4589 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4590 else
4591 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004592 // heuristic to reduce number of builtin candidates in the set.
4593 // Add volatile version only if there are conversions to a volatile type.
4594 if (VisibleTypeConversionsQuals.hasVolatile()) {
4595 // Volatile version
4596 ParamTypes[0]
4597 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4598 if (NumArgs == 1)
4599 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4600 else
4601 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4602 }
Douglas Gregor74253732008-11-19 15:42:04 +00004603 }
4604
4605 // C++ [over.built]p5:
4606 //
4607 // For every pair (T, VQ), where T is a cv-qualified or
4608 // cv-unqualified object type, and VQ is either volatile or
4609 // empty, there exist candidate operator functions of the form
4610 //
4611 // T*VQ& operator++(T*VQ&);
4612 // T*VQ& operator--(T*VQ&);
4613 // T* operator++(T*VQ&, int);
4614 // T* operator--(T*VQ&, int);
4615 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4616 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4617 // Skip pointer types that aren't pointers to object types.
Eli Friedman13578692010-08-05 02:49:48 +00004618 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00004619 continue;
4620
Mike Stump1eb44332009-09-09 15:08:12 +00004621 QualType ParamTypes[2] = {
4622 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00004623 };
Mike Stump1eb44332009-09-09 15:08:12 +00004624
Douglas Gregor74253732008-11-19 15:42:04 +00004625 // Without volatile
4626 if (NumArgs == 1)
4627 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4628 else
4629 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4630
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004631 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4632 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004633 // With volatile
John McCall0953e762009-09-24 19:53:00 +00004634 ParamTypes[0]
4635 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00004636 if (NumArgs == 1)
4637 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4638 else
4639 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4640 }
4641 }
4642 break;
4643
4644 UnaryStar:
4645 // C++ [over.built]p6:
4646 // For every cv-qualified or cv-unqualified object type T, there
4647 // exist candidate operator functions of the form
4648 //
4649 // T& operator*(T*);
4650 //
4651 // C++ [over.built]p7:
4652 // For every function type T, there exist candidate operator
4653 // functions of the form
4654 // T& operator*(T*);
4655 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4656 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4657 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00004658 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004659 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00004660 &ParamTy, Args, 1, CandidateSet);
4661 }
4662 break;
4663
4664 UnaryPlus:
4665 // C++ [over.built]p8:
4666 // For every type T, there exist candidate operator functions of
4667 // the form
4668 //
4669 // T* operator+(T*);
4670 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4671 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4672 QualType ParamTy = *Ptr;
4673 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4674 }
Mike Stump1eb44332009-09-09 15:08:12 +00004675
Douglas Gregor74253732008-11-19 15:42:04 +00004676 // Fall through
4677
4678 UnaryMinus:
4679 // C++ [over.built]p9:
4680 // For every promoted arithmetic type T, there exist candidate
4681 // operator functions of the form
4682 //
4683 // T operator+(T);
4684 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004685 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00004686 Arith < LastPromotedArithmeticType; ++Arith) {
4687 QualType ArithTy = ArithmeticTypes[Arith];
4688 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4689 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004690
4691 // Extension: We also add these operators for vector types.
4692 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4693 VecEnd = CandidateTypes.vector_end();
4694 Vec != VecEnd; ++Vec) {
4695 QualType VecTy = *Vec;
4696 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4697 }
Douglas Gregor74253732008-11-19 15:42:04 +00004698 break;
4699
4700 case OO_Tilde:
4701 // C++ [over.built]p10:
4702 // For every promoted integral type T, there exist candidate
4703 // operator functions of the form
4704 //
4705 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004706 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00004707 Int < LastPromotedIntegralType; ++Int) {
4708 QualType IntTy = ArithmeticTypes[Int];
4709 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4710 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004711
4712 // Extension: We also add this operator for vector types.
4713 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4714 VecEnd = CandidateTypes.vector_end();
4715 Vec != VecEnd; ++Vec) {
4716 QualType VecTy = *Vec;
4717 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4718 }
Douglas Gregor74253732008-11-19 15:42:04 +00004719 break;
4720
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004721 case OO_New:
4722 case OO_Delete:
4723 case OO_Array_New:
4724 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004725 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00004726 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004727 break;
4728
4729 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00004730 UnaryAmp:
4731 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004732 // C++ [over.match.oper]p3:
4733 // -- For the operator ',', the unary operator '&', or the
4734 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004735 break;
4736
Douglas Gregor19b7b152009-08-24 13:43:27 +00004737 case OO_EqualEqual:
4738 case OO_ExclaimEqual:
4739 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00004740 // For every pointer to member type T, there exist candidate operator
4741 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00004742 //
4743 // bool operator==(T,T);
4744 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00004745 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00004746 MemPtr = CandidateTypes.member_pointer_begin(),
4747 MemPtrEnd = CandidateTypes.member_pointer_end();
4748 MemPtr != MemPtrEnd;
4749 ++MemPtr) {
4750 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4751 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4752 }
Mike Stump1eb44332009-09-09 15:08:12 +00004753
Douglas Gregor19b7b152009-08-24 13:43:27 +00004754 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00004755
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004756 case OO_Less:
4757 case OO_Greater:
4758 case OO_LessEqual:
4759 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004760 // C++ [over.built]p15:
4761 //
4762 // For every pointer or enumeration type T, there exist
4763 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004764 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004765 // bool operator<(T, T);
4766 // bool operator>(T, T);
4767 // bool operator<=(T, T);
4768 // bool operator>=(T, T);
4769 // bool operator==(T, T);
4770 // bool operator!=(T, T);
4771 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4772 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4773 QualType ParamTypes[2] = { *Ptr, *Ptr };
4774 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4775 }
Mike Stump1eb44332009-09-09 15:08:12 +00004776 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004777 = CandidateTypes.enumeration_begin();
4778 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4779 QualType ParamTypes[2] = { *Enum, *Enum };
4780 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4781 }
4782
4783 // Fall through.
4784 isComparison = true;
4785
Douglas Gregor74253732008-11-19 15:42:04 +00004786 BinaryPlus:
4787 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004788 if (!isComparison) {
4789 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4790
4791 // C++ [over.built]p13:
4792 //
4793 // For every cv-qualified or cv-unqualified object type T
4794 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004795 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004796 // T* operator+(T*, ptrdiff_t);
4797 // T& operator[](T*, ptrdiff_t); [BELOW]
4798 // T* operator-(T*, ptrdiff_t);
4799 // T* operator+(ptrdiff_t, T*);
4800 // T& operator[](ptrdiff_t, T*); [BELOW]
4801 //
4802 // C++ [over.built]p14:
4803 //
4804 // For every T, where T is a pointer to object type, there
4805 // exist candidate operator functions of the form
4806 //
4807 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00004808 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004809 = CandidateTypes.pointer_begin();
4810 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4811 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4812
4813 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4814 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4815
4816 if (Op == OO_Plus) {
4817 // T* operator+(ptrdiff_t, T*);
4818 ParamTypes[0] = ParamTypes[1];
4819 ParamTypes[1] = *Ptr;
4820 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4821 } else {
4822 // ptrdiff_t operator-(T, T);
4823 ParamTypes[1] = *Ptr;
4824 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4825 Args, 2, CandidateSet);
4826 }
4827 }
4828 }
4829 // Fall through
4830
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004831 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00004832 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004833 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004834 // C++ [over.built]p12:
4835 //
4836 // For every pair of promoted arithmetic types L and R, there
4837 // exist candidate operator functions of the form
4838 //
4839 // LR operator*(L, R);
4840 // LR operator/(L, R);
4841 // LR operator+(L, R);
4842 // LR operator-(L, R);
4843 // bool operator<(L, R);
4844 // bool operator>(L, R);
4845 // bool operator<=(L, R);
4846 // bool operator>=(L, R);
4847 // bool operator==(L, R);
4848 // bool operator!=(L, R);
4849 //
4850 // where LR is the result of the usual arithmetic conversions
4851 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004852 //
4853 // C++ [over.built]p24:
4854 //
4855 // For every pair of promoted arithmetic types L and R, there exist
4856 // candidate operator functions of the form
4857 //
4858 // LR operator?(bool, L, R);
4859 //
4860 // where LR is the result of the usual arithmetic conversions
4861 // between types L and R.
4862 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004863 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004864 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004865 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004866 Right < LastPromotedArithmeticType; ++Right) {
4867 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00004868 QualType Result
4869 = isComparison
4870 ? Context.BoolTy
4871 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004872 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4873 }
4874 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004875
4876 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4877 // conditional operator for vector types.
4878 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4879 Vec1End = CandidateTypes.vector_end();
4880 Vec1 != Vec1End; ++Vec1)
4881 for (BuiltinCandidateTypeSet::iterator
4882 Vec2 = CandidateTypes.vector_begin(),
4883 Vec2End = CandidateTypes.vector_end();
4884 Vec2 != Vec2End; ++Vec2) {
4885 QualType LandR[2] = { *Vec1, *Vec2 };
4886 QualType Result;
4887 if (isComparison)
4888 Result = Context.BoolTy;
4889 else {
4890 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4891 Result = *Vec1;
4892 else
4893 Result = *Vec2;
4894 }
4895
4896 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4897 }
4898
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004899 break;
4900
4901 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00004902 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004903 case OO_Caret:
4904 case OO_Pipe:
4905 case OO_LessLess:
4906 case OO_GreaterGreater:
4907 // C++ [over.built]p17:
4908 //
4909 // For every pair of promoted integral types L and R, there
4910 // exist candidate operator functions of the form
4911 //
4912 // LR operator%(L, R);
4913 // LR operator&(L, R);
4914 // LR operator^(L, R);
4915 // LR operator|(L, R);
4916 // L operator<<(L, R);
4917 // L operator>>(L, R);
4918 //
4919 // where LR is the result of the usual arithmetic conversions
4920 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00004921 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004922 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004923 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004924 Right < LastPromotedIntegralType; ++Right) {
4925 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4926 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4927 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00004928 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004929 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4930 }
4931 }
4932 break;
4933
4934 case OO_Equal:
4935 // C++ [over.built]p20:
4936 //
4937 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00004938 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004939 // empty, there exist candidate operator functions of the form
4940 //
4941 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004942 for (BuiltinCandidateTypeSet::iterator
4943 Enum = CandidateTypes.enumeration_begin(),
4944 EnumEnd = CandidateTypes.enumeration_end();
4945 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00004946 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004947 CandidateSet);
4948 for (BuiltinCandidateTypeSet::iterator
4949 MemPtr = CandidateTypes.member_pointer_begin(),
4950 MemPtrEnd = CandidateTypes.member_pointer_end();
4951 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00004952 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004953 CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004954
4955 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004956
4957 case OO_PlusEqual:
4958 case OO_MinusEqual:
4959 // C++ [over.built]p19:
4960 //
4961 // For every pair (T, VQ), where T is any type and VQ is either
4962 // volatile or empty, there exist candidate operator functions
4963 // of the form
4964 //
4965 // T*VQ& operator=(T*VQ&, T*);
4966 //
4967 // C++ [over.built]p21:
4968 //
4969 // For every pair (T, VQ), where T is a cv-qualified or
4970 // cv-unqualified object type and VQ is either volatile or
4971 // empty, there exist candidate operator functions of the form
4972 //
4973 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4974 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4975 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4976 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4977 QualType ParamTypes[2];
4978 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4979
4980 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004981 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004982 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4983 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004984
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004985 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4986 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004987 // volatile version
John McCall0953e762009-09-24 19:53:00 +00004988 ParamTypes[0]
4989 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004990 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4991 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00004992 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004993 }
4994 // Fall through.
4995
4996 case OO_StarEqual:
4997 case OO_SlashEqual:
4998 // C++ [over.built]p18:
4999 //
5000 // For every triple (L, VQ, R), where L is an arithmetic type,
5001 // VQ is either volatile or empty, and R is a promoted
5002 // arithmetic type, there exist candidate operator functions of
5003 // the form
5004 //
5005 // VQ L& operator=(VQ L&, R);
5006 // VQ L& operator*=(VQ L&, R);
5007 // VQ L& operator/=(VQ L&, R);
5008 // VQ L& operator+=(VQ L&, R);
5009 // VQ L& operator-=(VQ L&, R);
5010 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005011 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005012 Right < LastPromotedArithmeticType; ++Right) {
5013 QualType ParamTypes[2];
5014 ParamTypes[1] = ArithmeticTypes[Right];
5015
5016 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005017 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005018 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5019 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005020
5021 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005022 if (VisibleTypeConversionsQuals.hasVolatile()) {
5023 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
5024 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5025 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5026 /*IsAssigmentOperator=*/Op == OO_Equal);
5027 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005028 }
5029 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00005030
5031 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5032 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
5033 Vec1End = CandidateTypes.vector_end();
5034 Vec1 != Vec1End; ++Vec1)
5035 for (BuiltinCandidateTypeSet::iterator
5036 Vec2 = CandidateTypes.vector_begin(),
5037 Vec2End = CandidateTypes.vector_end();
5038 Vec2 != Vec2End; ++Vec2) {
5039 QualType ParamTypes[2];
5040 ParamTypes[1] = *Vec2;
5041 // Add this built-in operator as a candidate (VQ is empty).
5042 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
5043 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5044 /*IsAssigmentOperator=*/Op == OO_Equal);
5045
5046 // Add this built-in operator as a candidate (VQ is 'volatile').
5047 if (VisibleTypeConversionsQuals.hasVolatile()) {
5048 ParamTypes[0] = Context.getVolatileType(*Vec1);
5049 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5050 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5051 /*IsAssigmentOperator=*/Op == OO_Equal);
5052 }
5053 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005054 break;
5055
5056 case OO_PercentEqual:
5057 case OO_LessLessEqual:
5058 case OO_GreaterGreaterEqual:
5059 case OO_AmpEqual:
5060 case OO_CaretEqual:
5061 case OO_PipeEqual:
5062 // C++ [over.built]p22:
5063 //
5064 // For every triple (L, VQ, R), where L is an integral type, VQ
5065 // is either volatile or empty, and R is a promoted integral
5066 // type, there exist candidate operator functions of the form
5067 //
5068 // VQ L& operator%=(VQ L&, R);
5069 // VQ L& operator<<=(VQ L&, R);
5070 // VQ L& operator>>=(VQ L&, R);
5071 // VQ L& operator&=(VQ L&, R);
5072 // VQ L& operator^=(VQ L&, R);
5073 // VQ L& operator|=(VQ L&, R);
5074 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005075 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005076 Right < LastPromotedIntegralType; ++Right) {
5077 QualType ParamTypes[2];
5078 ParamTypes[1] = ArithmeticTypes[Right];
5079
5080 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005081 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005082 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00005083 if (VisibleTypeConversionsQuals.hasVolatile()) {
5084 // Add this built-in operator as a candidate (VQ is 'volatile').
5085 ParamTypes[0] = ArithmeticTypes[Left];
5086 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5087 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5088 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5089 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005090 }
5091 }
5092 break;
5093
Douglas Gregor74253732008-11-19 15:42:04 +00005094 case OO_Exclaim: {
5095 // C++ [over.operator]p23:
5096 //
5097 // There also exist candidate operator functions of the form
5098 //
Mike Stump1eb44332009-09-09 15:08:12 +00005099 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00005100 // bool operator&&(bool, bool); [BELOW]
5101 // bool operator||(bool, bool); [BELOW]
5102 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005103 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5104 /*IsAssignmentOperator=*/false,
5105 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00005106 break;
5107 }
5108
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005109 case OO_AmpAmp:
5110 case OO_PipePipe: {
5111 // C++ [over.operator]p23:
5112 //
5113 // There also exist candidate operator functions of the form
5114 //
Douglas Gregor74253732008-11-19 15:42:04 +00005115 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005116 // bool operator&&(bool, bool);
5117 // bool operator||(bool, bool);
5118 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005119 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5120 /*IsAssignmentOperator=*/false,
5121 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005122 break;
5123 }
5124
5125 case OO_Subscript:
5126 // C++ [over.built]p13:
5127 //
5128 // For every cv-qualified or cv-unqualified object type T there
5129 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00005130 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005131 // T* operator+(T*, ptrdiff_t); [ABOVE]
5132 // T& operator[](T*, ptrdiff_t);
5133 // T* operator-(T*, ptrdiff_t); [ABOVE]
5134 // T* operator+(ptrdiff_t, T*); [ABOVE]
5135 // T& operator[](ptrdiff_t, T*);
5136 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5137 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5138 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00005139 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005140 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005141
5142 // T& operator[](T*, ptrdiff_t)
5143 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5144
5145 // T& operator[](ptrdiff_t, T*);
5146 ParamTypes[0] = ParamTypes[1];
5147 ParamTypes[1] = *Ptr;
5148 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00005149 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005150 break;
5151
5152 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005153 // C++ [over.built]p11:
5154 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5155 // C1 is the same type as C2 or is a derived class of C2, T is an object
5156 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5157 // there exist candidate operator functions of the form
5158 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5159 // where CV12 is the union of CV1 and CV2.
5160 {
5161 for (BuiltinCandidateTypeSet::iterator Ptr =
5162 CandidateTypes.pointer_begin();
5163 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5164 QualType C1Ty = (*Ptr);
5165 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005166 QualifierCollector Q1;
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00005167 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5168 if (!isa<RecordType>(C1))
5169 continue;
5170 // heuristic to reduce number of builtin candidates in the set.
5171 // Add volatile/restrict version only if there are conversions to a
5172 // volatile/restrict type.
5173 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5174 continue;
5175 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5176 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005177 for (BuiltinCandidateTypeSet::iterator
5178 MemPtr = CandidateTypes.member_pointer_begin(),
5179 MemPtrEnd = CandidateTypes.member_pointer_end();
5180 MemPtr != MemPtrEnd; ++MemPtr) {
5181 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5182 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00005183 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005184 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5185 break;
5186 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5187 // build CV12 T&
5188 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005189 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5190 T.isVolatileQualified())
5191 continue;
5192 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5193 T.isRestrictQualified())
5194 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005195 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005196 QualType ResultTy = Context.getLValueReferenceType(T);
5197 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5198 }
5199 }
5200 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005201 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005202
5203 case OO_Conditional:
5204 // Note that we don't consider the first argument, since it has been
5205 // contextually converted to bool long ago. The candidates below are
5206 // therefore added as binary.
5207 //
5208 // C++ [over.built]p24:
5209 // For every type T, where T is a pointer or pointer-to-member type,
5210 // there exist candidate operator functions of the form
5211 //
5212 // T operator?(bool, T, T);
5213 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005214 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5215 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5216 QualType ParamTypes[2] = { *Ptr, *Ptr };
5217 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5218 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00005219 for (BuiltinCandidateTypeSet::iterator Ptr =
5220 CandidateTypes.member_pointer_begin(),
5221 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5222 QualType ParamTypes[2] = { *Ptr, *Ptr };
5223 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5224 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005225 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005226 }
5227}
5228
Douglas Gregorfa047642009-02-04 00:32:51 +00005229/// \brief Add function candidates found via argument-dependent lookup
5230/// to the set of overloading candidates.
5231///
5232/// This routine performs argument-dependent name lookup based on the
5233/// given function name (which may also be an operator name) and adds
5234/// all of the overload candidates found by ADL to the overload
5235/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00005236void
Douglas Gregorfa047642009-02-04 00:32:51 +00005237Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00005238 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00005239 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00005240 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005241 OverloadCandidateSet& CandidateSet,
5242 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00005243 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00005244
John McCalla113e722010-01-26 06:04:06 +00005245 // FIXME: This approach for uniquing ADL results (and removing
5246 // redundant candidates from the set) relies on pointer-equality,
5247 // which means we need to key off the canonical decl. However,
5248 // always going back to the canonical decl might not get us the
5249 // right set of default arguments. What default arguments are
5250 // we supposed to consider on ADL candidates, anyway?
5251
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005252 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00005253 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00005254
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005255 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005256 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5257 CandEnd = CandidateSet.end();
5258 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00005259 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00005260 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00005261 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00005262 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00005263 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005264
5265 // For each of the ADL candidates we found, add it to the overload
5266 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00005267 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00005268 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00005269 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00005270 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005271 continue;
5272
John McCall9aa472c2010-03-19 07:35:19 +00005273 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00005274 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005275 } else
John McCall6e266892010-01-26 03:27:55 +00005276 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00005277 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00005278 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00005279 }
Douglas Gregorfa047642009-02-04 00:32:51 +00005280}
5281
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005282/// isBetterOverloadCandidate - Determines whether the first overload
5283/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00005284bool
John McCall120d63c2010-08-24 20:38:10 +00005285isBetterOverloadCandidate(Sema &S,
5286 const OverloadCandidate& Cand1,
5287 const OverloadCandidate& Cand2,
5288 SourceLocation Loc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005289 // Define viable functions to be better candidates than non-viable
5290 // functions.
5291 if (!Cand2.Viable)
5292 return Cand1.Viable;
5293 else if (!Cand1.Viable)
5294 return false;
5295
Douglas Gregor88a35142008-12-22 05:46:06 +00005296 // C++ [over.match.best]p1:
5297 //
5298 // -- if F is a static member function, ICS1(F) is defined such
5299 // that ICS1(F) is neither better nor worse than ICS1(G) for
5300 // any function G, and, symmetrically, ICS1(G) is neither
5301 // better nor worse than ICS1(F).
5302 unsigned StartArg = 0;
5303 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5304 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005305
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005306 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00005307 // A viable function F1 is defined to be a better function than another
5308 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005309 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005310 unsigned NumArgs = Cand1.Conversions.size();
5311 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5312 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005313 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00005314 switch (CompareImplicitConversionSequences(S,
5315 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005316 Cand2.Conversions[ArgIdx])) {
5317 case ImplicitConversionSequence::Better:
5318 // Cand1 has a better conversion sequence.
5319 HasBetterConversion = true;
5320 break;
5321
5322 case ImplicitConversionSequence::Worse:
5323 // Cand1 can't be better than Cand2.
5324 return false;
5325
5326 case ImplicitConversionSequence::Indistinguishable:
5327 // Do nothing.
5328 break;
5329 }
5330 }
5331
Mike Stump1eb44332009-09-09 15:08:12 +00005332 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005333 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005334 if (HasBetterConversion)
5335 return true;
5336
Mike Stump1eb44332009-09-09 15:08:12 +00005337 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005338 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00005339 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005340 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5341 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005342
5343 // -- F1 and F2 are function template specializations, and the function
5344 // template for F1 is more specialized than the template for F2
5345 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005346 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00005347 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5348 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005349 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00005350 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5351 Cand2.Function->getPrimaryTemplate(),
5352 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00005353 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5354 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005355 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005356
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005357 // -- the context is an initialization by user-defined conversion
5358 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5359 // from the return type of F1 to the destination type (i.e.,
5360 // the type of the entity being initialized) is a better
5361 // conversion sequence than the standard conversion sequence
5362 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00005363 if (Cand1.Function && Cand2.Function &&
5364 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005365 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00005366 switch (CompareStandardConversionSequences(S,
5367 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005368 Cand2.FinalConversion)) {
5369 case ImplicitConversionSequence::Better:
5370 // Cand1 has a better conversion sequence.
5371 return true;
5372
5373 case ImplicitConversionSequence::Worse:
5374 // Cand1 can't be better than Cand2.
5375 return false;
5376
5377 case ImplicitConversionSequence::Indistinguishable:
5378 // Do nothing
5379 break;
5380 }
5381 }
5382
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005383 return false;
5384}
5385
Mike Stump1eb44332009-09-09 15:08:12 +00005386/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00005387/// within an overload candidate set.
5388///
5389/// \param CandidateSet the set of candidate functions.
5390///
5391/// \param Loc the location of the function name (or operator symbol) for
5392/// which overload resolution occurs.
5393///
Mike Stump1eb44332009-09-09 15:08:12 +00005394/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00005395/// function, Best points to the candidate function found.
5396///
5397/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00005398OverloadingResult
5399OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
5400 iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005401 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00005402 Best = end();
5403 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5404 if (Cand->Viable)
5405 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005406 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005407 }
5408
5409 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00005410 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005411 return OR_No_Viable_Function;
5412
5413 // Make sure that this function is better than every other viable
5414 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00005415 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00005416 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005417 Cand != Best &&
John McCall120d63c2010-08-24 20:38:10 +00005418 !isBetterOverloadCandidate(S, *Best, *Cand, Loc)) {
5419 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005420 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005421 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005422 }
Mike Stump1eb44332009-09-09 15:08:12 +00005423
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005424 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005425 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005426 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005427 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005428 return OR_Deleted;
5429
Douglas Gregore0762c92009-06-19 23:52:42 +00005430 // C++ [basic.def.odr]p2:
5431 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00005432 // when referred to from a potentially-evaluated expression. [Note: this
5433 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00005434 // (clause 13), user-defined conversions (12.3.2), allocation function for
5435 // placement new (5.3.4), as well as non-default initialization (8.5).
5436 if (Best->Function)
John McCall120d63c2010-08-24 20:38:10 +00005437 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005438 return OR_Success;
5439}
5440
John McCall3c80f572010-01-12 02:15:36 +00005441namespace {
5442
5443enum OverloadCandidateKind {
5444 oc_function,
5445 oc_method,
5446 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005447 oc_function_template,
5448 oc_method_template,
5449 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00005450 oc_implicit_default_constructor,
5451 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005452 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00005453};
5454
John McCall220ccbf2010-01-13 00:25:19 +00005455OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5456 FunctionDecl *Fn,
5457 std::string &Description) {
5458 bool isTemplate = false;
5459
5460 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5461 isTemplate = true;
5462 Description = S.getTemplateArgumentBindingsText(
5463 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5464 }
John McCallb1622a12010-01-06 09:43:14 +00005465
5466 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00005467 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005468 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005469
John McCall3c80f572010-01-12 02:15:36 +00005470 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5471 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005472 }
5473
5474 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5475 // This actually gets spelled 'candidate function' for now, but
5476 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00005477 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005478 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00005479
5480 assert(Meth->isCopyAssignment()
5481 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00005482 return oc_implicit_copy_assignment;
5483 }
5484
John McCall220ccbf2010-01-13 00:25:19 +00005485 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00005486}
5487
5488} // end anonymous namespace
5489
5490// Notes the location of an overload candidate.
5491void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00005492 std::string FnDesc;
5493 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5494 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5495 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00005496}
5497
John McCall1d318332010-01-12 00:44:57 +00005498/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5499/// "lead" diagnostic; it will be given two arguments, the source and
5500/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00005501void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5502 Sema &S,
5503 SourceLocation CaretLoc,
5504 const PartialDiagnostic &PDiag) const {
5505 S.Diag(CaretLoc, PDiag)
5506 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00005507 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00005508 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5509 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00005510 }
John McCall81201622010-01-08 04:41:39 +00005511}
5512
John McCall1d318332010-01-12 00:44:57 +00005513namespace {
5514
John McCalladbb8f82010-01-13 09:16:55 +00005515void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5516 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5517 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00005518 assert(Cand->Function && "for now, candidate must be a function");
5519 FunctionDecl *Fn = Cand->Function;
5520
5521 // There's a conversion slot for the object argument if this is a
5522 // non-constructor method. Note that 'I' corresponds the
5523 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00005524 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00005525 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00005526 if (I == 0)
5527 isObjectArgument = true;
5528 else
5529 I--;
John McCall220ccbf2010-01-13 00:25:19 +00005530 }
5531
John McCall220ccbf2010-01-13 00:25:19 +00005532 std::string FnDesc;
5533 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5534
John McCalladbb8f82010-01-13 09:16:55 +00005535 Expr *FromExpr = Conv.Bad.FromExpr;
5536 QualType FromTy = Conv.Bad.getFromType();
5537 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00005538
John McCall5920dbb2010-02-02 02:42:52 +00005539 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00005540 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00005541 Expr *E = FromExpr->IgnoreParens();
5542 if (isa<UnaryOperator>(E))
5543 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00005544 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00005545
5546 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5547 << (unsigned) FnKind << FnDesc
5548 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5549 << ToTy << Name << I+1;
5550 return;
5551 }
5552
John McCall258b2032010-01-23 08:10:49 +00005553 // Do some hand-waving analysis to see if the non-viability is due
5554 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00005555 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5556 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5557 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5558 CToTy = RT->getPointeeType();
5559 else {
5560 // TODO: detect and diagnose the full richness of const mismatches.
5561 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5562 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5563 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5564 }
5565
5566 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5567 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5568 // It is dumb that we have to do this here.
5569 while (isa<ArrayType>(CFromTy))
5570 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5571 while (isa<ArrayType>(CToTy))
5572 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5573
5574 Qualifiers FromQs = CFromTy.getQualifiers();
5575 Qualifiers ToQs = CToTy.getQualifiers();
5576
5577 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5578 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5579 << (unsigned) FnKind << FnDesc
5580 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5581 << FromTy
5582 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5583 << (unsigned) isObjectArgument << I+1;
5584 return;
5585 }
5586
5587 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5588 assert(CVR && "unexpected qualifiers mismatch");
5589
5590 if (isObjectArgument) {
5591 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5592 << (unsigned) FnKind << FnDesc
5593 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5594 << FromTy << (CVR - 1);
5595 } else {
5596 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5597 << (unsigned) FnKind << FnDesc
5598 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5599 << FromTy << (CVR - 1) << I+1;
5600 }
5601 return;
5602 }
5603
John McCall258b2032010-01-23 08:10:49 +00005604 // Diagnose references or pointers to incomplete types differently,
5605 // since it's far from impossible that the incompleteness triggered
5606 // the failure.
5607 QualType TempFromTy = FromTy.getNonReferenceType();
5608 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5609 TempFromTy = PTy->getPointeeType();
5610 if (TempFromTy->isIncompleteType()) {
5611 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5612 << (unsigned) FnKind << FnDesc
5613 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5614 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5615 return;
5616 }
5617
Douglas Gregor85789812010-06-30 23:01:39 +00005618 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005619 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00005620 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5621 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5622 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5623 FromPtrTy->getPointeeType()) &&
5624 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5625 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5626 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5627 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005628 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00005629 }
5630 } else if (const ObjCObjectPointerType *FromPtrTy
5631 = FromTy->getAs<ObjCObjectPointerType>()) {
5632 if (const ObjCObjectPointerType *ToPtrTy
5633 = ToTy->getAs<ObjCObjectPointerType>())
5634 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5635 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5636 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5637 FromPtrTy->getPointeeType()) &&
5638 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005639 BaseToDerivedConversion = 2;
5640 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5641 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5642 !FromTy->isIncompleteType() &&
5643 !ToRefTy->getPointeeType()->isIncompleteType() &&
5644 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5645 BaseToDerivedConversion = 3;
5646 }
5647
5648 if (BaseToDerivedConversion) {
Douglas Gregor85789812010-06-30 23:01:39 +00005649 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005650 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00005651 << (unsigned) FnKind << FnDesc
5652 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005653 << (BaseToDerivedConversion - 1)
Douglas Gregor85789812010-06-30 23:01:39 +00005654 << FromTy << ToTy << I+1;
5655 return;
5656 }
5657
John McCall651f3ee2010-01-14 03:28:57 +00005658 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00005659 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5660 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00005661 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00005662 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00005663}
5664
5665void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5666 unsigned NumFormalArgs) {
5667 // TODO: treat calls to a missing default constructor as a special case
5668
5669 FunctionDecl *Fn = Cand->Function;
5670 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5671
5672 unsigned MinParams = Fn->getMinRequiredArguments();
5673
5674 // at least / at most / exactly
Douglas Gregora18592e2010-05-08 18:13:28 +00005675 // FIXME: variadic templates "at most" should account for parameter packs
John McCalladbb8f82010-01-13 09:16:55 +00005676 unsigned mode, modeCount;
5677 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00005678 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5679 (Cand->FailureKind == ovl_fail_bad_deduction &&
5680 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005681 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5682 mode = 0; // "at least"
5683 else
5684 mode = 2; // "exactly"
5685 modeCount = MinParams;
5686 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00005687 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5688 (Cand->FailureKind == ovl_fail_bad_deduction &&
5689 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005690 if (MinParams != FnTy->getNumArgs())
5691 mode = 1; // "at most"
5692 else
5693 mode = 2; // "exactly"
5694 modeCount = FnTy->getNumArgs();
5695 }
5696
5697 std::string Description;
5698 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5699
5700 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00005701 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5702 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00005703}
5704
John McCall342fec42010-02-01 18:53:26 +00005705/// Diagnose a failed template-argument deduction.
5706void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5707 Expr **Args, unsigned NumArgs) {
5708 FunctionDecl *Fn = Cand->Function; // pattern
5709
Douglas Gregora9333192010-05-08 17:41:32 +00005710 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00005711 NamedDecl *ParamD;
5712 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5713 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5714 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00005715 switch (Cand->DeductionFailure.Result) {
5716 case Sema::TDK_Success:
5717 llvm_unreachable("TDK_success while diagnosing bad deduction");
5718
5719 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00005720 assert(ParamD && "no parameter found for incomplete deduction result");
5721 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5722 << ParamD->getDeclName();
5723 return;
5724 }
5725
John McCall57e97782010-08-05 09:05:08 +00005726 case Sema::TDK_Underqualified: {
5727 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5728 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5729
5730 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5731
5732 // Param will have been canonicalized, but it should just be a
5733 // qualified version of ParamD, so move the qualifiers to that.
5734 QualifierCollector Qs(S.Context);
5735 Qs.strip(Param);
5736 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5737 assert(S.Context.hasSameType(Param, NonCanonParam));
5738
5739 // Arg has also been canonicalized, but there's nothing we can do
5740 // about that. It also doesn't matter as much, because it won't
5741 // have any template parameters in it (because deduction isn't
5742 // done on dependent types).
5743 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5744
5745 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5746 << ParamD->getDeclName() << Arg << NonCanonParam;
5747 return;
5748 }
5749
5750 case Sema::TDK_Inconsistent: {
Douglas Gregorf1a84452010-05-08 19:15:54 +00005751 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00005752 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005753 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005754 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005755 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005756 which = 1;
5757 else {
Douglas Gregora9333192010-05-08 17:41:32 +00005758 which = 2;
5759 }
5760
5761 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5762 << which << ParamD->getDeclName()
5763 << *Cand->DeductionFailure.getFirstArg()
5764 << *Cand->DeductionFailure.getSecondArg();
5765 return;
5766 }
Douglas Gregora18592e2010-05-08 18:13:28 +00005767
Douglas Gregorf1a84452010-05-08 19:15:54 +00005768 case Sema::TDK_InvalidExplicitArguments:
5769 assert(ParamD && "no parameter found for invalid explicit arguments");
5770 if (ParamD->getDeclName())
5771 S.Diag(Fn->getLocation(),
5772 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5773 << ParamD->getDeclName();
5774 else {
5775 int index = 0;
5776 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5777 index = TTP->getIndex();
5778 else if (NonTypeTemplateParmDecl *NTTP
5779 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5780 index = NTTP->getIndex();
5781 else
5782 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5783 S.Diag(Fn->getLocation(),
5784 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5785 << (index + 1);
5786 }
5787 return;
5788
Douglas Gregora18592e2010-05-08 18:13:28 +00005789 case Sema::TDK_TooManyArguments:
5790 case Sema::TDK_TooFewArguments:
5791 DiagnoseArityMismatch(S, Cand, NumArgs);
5792 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00005793
5794 case Sema::TDK_InstantiationDepth:
5795 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5796 return;
5797
5798 case Sema::TDK_SubstitutionFailure: {
5799 std::string ArgString;
5800 if (TemplateArgumentList *Args
5801 = Cand->DeductionFailure.getTemplateArgumentList())
5802 ArgString = S.getTemplateArgumentBindingsText(
5803 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5804 *Args);
5805 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5806 << ArgString;
5807 return;
5808 }
Douglas Gregora9333192010-05-08 17:41:32 +00005809
John McCall342fec42010-02-01 18:53:26 +00005810 // TODO: diagnose these individually, then kill off
5811 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00005812 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00005813 case Sema::TDK_FailedOverloadResolution:
5814 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5815 return;
5816 }
5817}
5818
5819/// Generates a 'note' diagnostic for an overload candidate. We've
5820/// already generated a primary error at the call site.
5821///
5822/// It really does need to be a single diagnostic with its caret
5823/// pointed at the candidate declaration. Yes, this creates some
5824/// major challenges of technical writing. Yes, this makes pointing
5825/// out problems with specific arguments quite awkward. It's still
5826/// better than generating twenty screens of text for every failed
5827/// overload.
5828///
5829/// It would be great to be able to express per-candidate problems
5830/// more richly for those diagnostic clients that cared, but we'd
5831/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00005832void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5833 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00005834 FunctionDecl *Fn = Cand->Function;
5835
John McCall81201622010-01-08 04:41:39 +00005836 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00005837 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00005838 std::string FnDesc;
5839 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00005840
5841 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00005842 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00005843 return;
John McCall81201622010-01-08 04:41:39 +00005844 }
5845
John McCall220ccbf2010-01-13 00:25:19 +00005846 // We don't really have anything else to say about viable candidates.
5847 if (Cand->Viable) {
5848 S.NoteOverloadCandidate(Fn);
5849 return;
5850 }
John McCall1d318332010-01-12 00:44:57 +00005851
John McCalladbb8f82010-01-13 09:16:55 +00005852 switch (Cand->FailureKind) {
5853 case ovl_fail_too_many_arguments:
5854 case ovl_fail_too_few_arguments:
5855 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00005856
John McCalladbb8f82010-01-13 09:16:55 +00005857 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00005858 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5859
John McCall717e8912010-01-23 05:17:32 +00005860 case ovl_fail_trivial_conversion:
5861 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00005862 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00005863 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005864
John McCallb1bdc622010-02-25 01:37:24 +00005865 case ovl_fail_bad_conversion: {
5866 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5867 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00005868 if (Cand->Conversions[I].isBad())
5869 return DiagnoseBadConversion(S, Cand, I);
5870
5871 // FIXME: this currently happens when we're called from SemaInit
5872 // when user-conversion overload fails. Figure out how to handle
5873 // those conditions and diagnose them well.
5874 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005875 }
John McCallb1bdc622010-02-25 01:37:24 +00005876 }
John McCalla1d7d622010-01-08 00:58:21 +00005877}
5878
5879void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5880 // Desugar the type of the surrogate down to a function type,
5881 // retaining as many typedefs as possible while still showing
5882 // the function type (and, therefore, its parameter types).
5883 QualType FnType = Cand->Surrogate->getConversionType();
5884 bool isLValueReference = false;
5885 bool isRValueReference = false;
5886 bool isPointer = false;
5887 if (const LValueReferenceType *FnTypeRef =
5888 FnType->getAs<LValueReferenceType>()) {
5889 FnType = FnTypeRef->getPointeeType();
5890 isLValueReference = true;
5891 } else if (const RValueReferenceType *FnTypeRef =
5892 FnType->getAs<RValueReferenceType>()) {
5893 FnType = FnTypeRef->getPointeeType();
5894 isRValueReference = true;
5895 }
5896 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5897 FnType = FnTypePtr->getPointeeType();
5898 isPointer = true;
5899 }
5900 // Desugar down to a function type.
5901 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5902 // Reconstruct the pointer/reference as appropriate.
5903 if (isPointer) FnType = S.Context.getPointerType(FnType);
5904 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5905 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5906
5907 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5908 << FnType;
5909}
5910
5911void NoteBuiltinOperatorCandidate(Sema &S,
5912 const char *Opc,
5913 SourceLocation OpLoc,
5914 OverloadCandidate *Cand) {
5915 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5916 std::string TypeStr("operator");
5917 TypeStr += Opc;
5918 TypeStr += "(";
5919 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5920 if (Cand->Conversions.size() == 1) {
5921 TypeStr += ")";
5922 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5923 } else {
5924 TypeStr += ", ";
5925 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5926 TypeStr += ")";
5927 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5928 }
5929}
5930
5931void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5932 OverloadCandidate *Cand) {
5933 unsigned NoOperands = Cand->Conversions.size();
5934 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5935 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00005936 if (ICS.isBad()) break; // all meaningless after first invalid
5937 if (!ICS.isAmbiguous()) continue;
5938
John McCall120d63c2010-08-24 20:38:10 +00005939 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005940 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00005941 }
5942}
5943
John McCall1b77e732010-01-15 23:32:50 +00005944SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5945 if (Cand->Function)
5946 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00005947 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00005948 return Cand->Surrogate->getLocation();
5949 return SourceLocation();
5950}
5951
John McCallbf65c0b2010-01-12 00:48:53 +00005952struct CompareOverloadCandidatesForDisplay {
5953 Sema &S;
5954 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00005955
5956 bool operator()(const OverloadCandidate *L,
5957 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00005958 // Fast-path this check.
5959 if (L == R) return false;
5960
John McCall81201622010-01-08 04:41:39 +00005961 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00005962 if (L->Viable) {
5963 if (!R->Viable) return true;
5964
5965 // TODO: introduce a tri-valued comparison for overload
5966 // candidates. Would be more worthwhile if we had a sort
5967 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00005968 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
5969 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00005970 } else if (R->Viable)
5971 return false;
John McCall81201622010-01-08 04:41:39 +00005972
John McCall1b77e732010-01-15 23:32:50 +00005973 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00005974
John McCall1b77e732010-01-15 23:32:50 +00005975 // Criteria by which we can sort non-viable candidates:
5976 if (!L->Viable) {
5977 // 1. Arity mismatches come after other candidates.
5978 if (L->FailureKind == ovl_fail_too_many_arguments ||
5979 L->FailureKind == ovl_fail_too_few_arguments)
5980 return false;
5981 if (R->FailureKind == ovl_fail_too_many_arguments ||
5982 R->FailureKind == ovl_fail_too_few_arguments)
5983 return true;
John McCall81201622010-01-08 04:41:39 +00005984
John McCall717e8912010-01-23 05:17:32 +00005985 // 2. Bad conversions come first and are ordered by the number
5986 // of bad conversions and quality of good conversions.
5987 if (L->FailureKind == ovl_fail_bad_conversion) {
5988 if (R->FailureKind != ovl_fail_bad_conversion)
5989 return true;
5990
5991 // If there's any ordering between the defined conversions...
5992 // FIXME: this might not be transitive.
5993 assert(L->Conversions.size() == R->Conversions.size());
5994
5995 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00005996 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5997 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00005998 switch (CompareImplicitConversionSequences(S,
5999 L->Conversions[I],
6000 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00006001 case ImplicitConversionSequence::Better:
6002 leftBetter++;
6003 break;
6004
6005 case ImplicitConversionSequence::Worse:
6006 leftBetter--;
6007 break;
6008
6009 case ImplicitConversionSequence::Indistinguishable:
6010 break;
6011 }
6012 }
6013 if (leftBetter > 0) return true;
6014 if (leftBetter < 0) return false;
6015
6016 } else if (R->FailureKind == ovl_fail_bad_conversion)
6017 return false;
6018
John McCall1b77e732010-01-15 23:32:50 +00006019 // TODO: others?
6020 }
6021
6022 // Sort everything else by location.
6023 SourceLocation LLoc = GetLocationForCandidate(L);
6024 SourceLocation RLoc = GetLocationForCandidate(R);
6025
6026 // Put candidates without locations (e.g. builtins) at the end.
6027 if (LLoc.isInvalid()) return false;
6028 if (RLoc.isInvalid()) return true;
6029
6030 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00006031 }
6032};
6033
John McCall717e8912010-01-23 05:17:32 +00006034/// CompleteNonViableCandidate - Normally, overload resolution only
6035/// computes up to the first
6036void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6037 Expr **Args, unsigned NumArgs) {
6038 assert(!Cand->Viable);
6039
6040 // Don't do anything on failures other than bad conversion.
6041 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6042
6043 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00006044 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00006045 unsigned ConvCount = Cand->Conversions.size();
6046 while (true) {
6047 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6048 ConvIdx++;
6049 if (Cand->Conversions[ConvIdx - 1].isBad())
6050 break;
6051 }
6052
6053 if (ConvIdx == ConvCount)
6054 return;
6055
John McCallb1bdc622010-02-25 01:37:24 +00006056 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6057 "remaining conversion is initialized?");
6058
Douglas Gregor23ef6c02010-04-16 17:45:54 +00006059 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00006060 // operation somehow.
6061 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00006062
6063 const FunctionProtoType* Proto;
6064 unsigned ArgIdx = ConvIdx;
6065
6066 if (Cand->IsSurrogate) {
6067 QualType ConvType
6068 = Cand->Surrogate->getConversionType().getNonReferenceType();
6069 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6070 ConvType = ConvPtrType->getPointeeType();
6071 Proto = ConvType->getAs<FunctionProtoType>();
6072 ArgIdx--;
6073 } else if (Cand->Function) {
6074 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6075 if (isa<CXXMethodDecl>(Cand->Function) &&
6076 !isa<CXXConstructorDecl>(Cand->Function))
6077 ArgIdx--;
6078 } else {
6079 // Builtin binary operator with a bad first conversion.
6080 assert(ConvCount <= 3);
6081 for (; ConvIdx != ConvCount; ++ConvIdx)
6082 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006083 = TryCopyInitialization(S, Args[ConvIdx],
6084 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6085 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006086 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00006087 return;
6088 }
6089
6090 // Fill in the rest of the conversions.
6091 unsigned NumArgsInProto = Proto->getNumArgs();
6092 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6093 if (ArgIdx < NumArgsInProto)
6094 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006095 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6096 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006097 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00006098 else
6099 Cand->Conversions[ConvIdx].setEllipsis();
6100 }
6101}
6102
John McCalla1d7d622010-01-08 00:58:21 +00006103} // end anonymous namespace
6104
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006105/// PrintOverloadCandidates - When overload resolution fails, prints
6106/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00006107/// set.
John McCall120d63c2010-08-24 20:38:10 +00006108void OverloadCandidateSet::NoteCandidates(Sema &S,
6109 OverloadCandidateDisplayKind OCD,
6110 Expr **Args, unsigned NumArgs,
6111 const char *Opc,
6112 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00006113 // Sort the candidates by viability and position. Sorting directly would
6114 // be prohibitive, so we make a set of pointers and sort those.
6115 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00006116 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6117 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00006118 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00006119 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00006120 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00006121 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006122 if (Cand->Function || Cand->IsSurrogate)
6123 Cands.push_back(Cand);
6124 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6125 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00006126 }
6127 }
6128
John McCallbf65c0b2010-01-12 00:48:53 +00006129 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00006130 CompareOverloadCandidatesForDisplay(S));
John McCall81201622010-01-08 04:41:39 +00006131
John McCall1d318332010-01-12 00:44:57 +00006132 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00006133
John McCall81201622010-01-08 04:41:39 +00006134 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall120d63c2010-08-24 20:38:10 +00006135 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006136 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00006137 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6138 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00006139
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006140 // Set an arbitrary limit on the number of candidate functions we'll spam
6141 // the user with. FIXME: This limit should depend on details of the
6142 // candidate list.
6143 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6144 break;
6145 }
6146 ++CandsShown;
6147
John McCalla1d7d622010-01-08 00:58:21 +00006148 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00006149 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00006150 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00006151 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006152 else {
6153 assert(Cand->Viable &&
6154 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00006155 // Generally we only see ambiguities including viable builtin
6156 // operators if overload resolution got screwed up by an
6157 // ambiguous user-defined conversion.
6158 //
6159 // FIXME: It's quite possible for different conversions to see
6160 // different ambiguities, though.
6161 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00006162 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00006163 ReportedAmbiguousConversions = true;
6164 }
John McCalla1d7d622010-01-08 00:58:21 +00006165
John McCall1d318332010-01-12 00:44:57 +00006166 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00006167 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006168 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006169 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006170
6171 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00006172 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006173}
6174
John McCall9aa472c2010-03-19 07:35:19 +00006175static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00006176 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00006177 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006178
John McCall9aa472c2010-03-19 07:35:19 +00006179 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006180}
6181
Douglas Gregor904eed32008-11-10 20:40:00 +00006182/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6183/// an overloaded function (C++ [over.over]), where @p From is an
6184/// expression with overloaded function type and @p ToType is the type
6185/// we're trying to resolve to. For example:
6186///
6187/// @code
6188/// int f(double);
6189/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00006190///
Douglas Gregor904eed32008-11-10 20:40:00 +00006191/// int (*pfd)(double) = f; // selects f(double)
6192/// @endcode
6193///
6194/// This routine returns the resulting FunctionDecl if it could be
6195/// resolved, and NULL otherwise. When @p Complain is true, this
6196/// routine will emit diagnostics if there is an error.
6197FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00006198Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00006199 bool Complain,
6200 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006201 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00006202 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00006203 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00006204 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00006205 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00006206 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00006207 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00006208 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006209 FunctionType = MemTypePtr->getPointeeType();
6210 IsMember = true;
6211 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006212
Douglas Gregor904eed32008-11-10 20:40:00 +00006213 // C++ [over.over]p1:
6214 // [...] [Note: any redundant set of parentheses surrounding the
6215 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00006216 // C++ [over.over]p1:
6217 // [...] The overloaded function name can be preceded by the &
6218 // operator.
John McCallc988fab2010-08-24 23:26:21 +00006219 // However, remember whether the expression has member-pointer form:
6220 // C++ [expr.unary.op]p4:
6221 // A pointer to member is only formed when an explicit & is used
6222 // and its operand is a qualified-id not enclosed in
6223 // parentheses.
6224 bool HasFormOfMemberPointer = false;
6225 OverloadExpr *OvlExpr;
6226 {
6227 Expr *Tmp = From->IgnoreParens();
6228 if (isa<UnaryOperator>(Tmp)) {
6229 Tmp = cast<UnaryOperator>(Tmp)->getSubExpr();
6230 OvlExpr = cast<OverloadExpr>(Tmp->IgnoreParens());
6231 HasFormOfMemberPointer = (Tmp == OvlExpr && OvlExpr->getQualifier());
6232 } else {
6233 OvlExpr = cast<OverloadExpr>(Tmp);
6234 }
6235 }
6236
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006237 // We expect a pointer or reference to function, or a function pointer.
6238 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6239 if (!FunctionType->isFunctionType()) {
6240 if (Complain)
6241 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6242 << OvlExpr->getName() << ToType;
6243
6244 return 0;
6245 }
6246
John McCallfb97e752010-08-24 22:52:39 +00006247 // If the overload expression doesn't have the form of a pointer to
John McCallc988fab2010-08-24 23:26:21 +00006248 // member, don't try to convert it to a pointer-to-member type.
6249 if (IsMember && !HasFormOfMemberPointer) {
John McCallfb97e752010-08-24 22:52:39 +00006250 if (!Complain) return 0;
6251
6252 // TODO: Should we condition this on whether any functions might
6253 // have matched, or is it more appropriate to do that in callers?
6254 // TODO: a fixit wouldn't hurt.
6255 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6256 << ToType << OvlExpr->getSourceRange();
6257 return 0;
6258 }
6259
6260 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6261 if (OvlExpr->hasExplicitTemplateArgs()) {
6262 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6263 ExplicitTemplateArgs = &ETABuffer;
6264 }
6265
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006266 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00006267
Douglas Gregor904eed32008-11-10 20:40:00 +00006268 // Look through all of the overloaded functions, searching for one
6269 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00006270 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00006271 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
6272
Douglas Gregor00aeb522009-07-08 23:33:52 +00006273 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00006274 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6275 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00006276 // Look through any using declarations to find the underlying function.
6277 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6278
Douglas Gregor904eed32008-11-10 20:40:00 +00006279 // C++ [over.over]p3:
6280 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00006281 // targets of type "pointer-to-function" or "reference-to-function."
6282 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00006283 // type "pointer-to-member-function."
6284 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006285
Mike Stump1eb44332009-09-09 15:08:12 +00006286 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00006287 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006288 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00006289 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00006290 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00006291 // static when converting to member pointer.
6292 if (Method->isStatic() == IsMember)
6293 continue;
6294 } else if (IsMember)
6295 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00006296
Douglas Gregor00aeb522009-07-08 23:33:52 +00006297 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006298 // If the name is a function template, template argument deduction is
6299 // done (14.8.2.2), and if the argument deduction succeeds, the
6300 // resulting template argument list is used to generate a single
6301 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00006302 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00006303 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00006304 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006305 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00006306 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00006307 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00006308 FunctionType, Specialization, Info)) {
6309 // FIXME: make a note of the failed deduction for diagnostics.
6310 (void)Result;
6311 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00006312 // FIXME: If the match isn't exact, shouldn't we just drop this as
6313 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00006314 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00006315 == Context.getCanonicalType(Specialization->getType()));
John McCall9aa472c2010-03-19 07:35:19 +00006316 Matches.push_back(std::make_pair(I.getPair(),
6317 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor83314aa2009-07-08 20:55:45 +00006318 }
John McCallba135432009-11-21 08:51:07 +00006319
6320 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00006321 }
Mike Stump1eb44332009-09-09 15:08:12 +00006322
Chandler Carruthbd647292009-12-29 06:17:27 +00006323 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006324 // Skip non-static functions when converting to pointer, and static
6325 // when converting to member pointer.
6326 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00006327 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006328
6329 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00006330 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006331 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00006332 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00006333 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00006334
Chandler Carruthbd647292009-12-29 06:17:27 +00006335 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00006336 QualType ResultTy;
6337 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6338 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6339 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00006340 Matches.push_back(std::make_pair(I.getPair(),
6341 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00006342 FoundNonTemplateFunction = true;
6343 }
Mike Stump1eb44332009-09-09 15:08:12 +00006344 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006345 }
6346
Douglas Gregor00aeb522009-07-08 23:33:52 +00006347 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006348 if (Matches.empty()) {
6349 if (Complain) {
6350 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6351 << OvlExpr->getName() << FunctionType;
6352 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6353 E = OvlExpr->decls_end();
6354 I != E; ++I)
6355 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6356 NoteOverloadCandidate(F);
6357 }
6358
Douglas Gregor00aeb522009-07-08 23:33:52 +00006359 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006360 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006361 FunctionDecl *Result = Matches[0].second;
John McCall6bb80172010-03-30 21:47:33 +00006362 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00006363 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCallc373d482010-01-27 01:50:18 +00006364 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00006365 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006366 return Result;
6367 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00006368
6369 // C++ [over.over]p4:
6370 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00006371 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006372 // [...] and any given function template specialization F1 is
6373 // eliminated if the set contains a second function template
6374 // specialization whose function template is more specialized
6375 // than the function template of F1 according to the partial
6376 // ordering rules of 14.5.5.2.
6377
6378 // The algorithm specified above is quadratic. We instead use a
6379 // two-pass algorithm (similar to the one used to identify the
6380 // best viable function in an overload set) that identifies the
6381 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00006382
6383 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6384 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6385 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00006386
6387 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00006388 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00006389 TPOC_Other, From->getLocStart(),
6390 PDiag(),
6391 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006392 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00006393 PDiag(diag::note_ovl_candidate)
6394 << (unsigned) oc_function_template);
John McCall9aa472c2010-03-19 07:35:19 +00006395 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCallc373d482010-01-27 01:50:18 +00006396 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00006397 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCallb697e082010-05-06 18:15:07 +00006398 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00006399 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallb697e082010-05-06 18:15:07 +00006400 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
6401 }
John McCallc373d482010-01-27 01:50:18 +00006402 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00006403 }
Mike Stump1eb44332009-09-09 15:08:12 +00006404
Douglas Gregor312a2022009-09-26 03:56:17 +00006405 // [...] any function template specializations in the set are
6406 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00006407 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00006408 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00006409 ++I;
6410 else {
John McCall9aa472c2010-03-19 07:35:19 +00006411 Matches[I] = Matches[--N];
6412 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00006413 }
6414 }
Douglas Gregor312a2022009-09-26 03:56:17 +00006415
Mike Stump1eb44332009-09-09 15:08:12 +00006416 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00006417 // selected function.
John McCallc373d482010-01-27 01:50:18 +00006418 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006419 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00006420 FoundResult = Matches[0].first;
John McCallb697e082010-05-06 18:15:07 +00006421 if (Complain) {
John McCall9aa472c2010-03-19 07:35:19 +00006422 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCallb697e082010-05-06 18:15:07 +00006423 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6424 }
John McCall9aa472c2010-03-19 07:35:19 +00006425 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006426 }
Mike Stump1eb44332009-09-09 15:08:12 +00006427
Douglas Gregor00aeb522009-07-08 23:33:52 +00006428 // FIXME: We should probably return the same thing that BestViableFunction
6429 // returns (even if we issue the diagnostics here).
6430 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006431 << Matches[0].second->getDeclName();
6432 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6433 NoteOverloadCandidate(Matches[I].second);
Douglas Gregor904eed32008-11-10 20:40:00 +00006434 return 0;
6435}
6436
Douglas Gregor4b52e252009-12-21 23:17:24 +00006437/// \brief Given an expression that refers to an overloaded function, try to
6438/// resolve that overloaded function expression down to a single function.
6439///
6440/// This routine can only resolve template-ids that refer to a single function
6441/// template, where that template-id refers to a single template whose template
6442/// arguments are either provided by the template-id or have defaults,
6443/// as described in C++0x [temp.arg.explicit]p3.
6444FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6445 // C++ [over.over]p1:
6446 // [...] [Note: any redundant set of parentheses surrounding the
6447 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00006448 // C++ [over.over]p1:
6449 // [...] The overloaded function name can be preceded by the &
6450 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00006451
6452 if (From->getType() != Context.OverloadTy)
6453 return 0;
6454
6455 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor4b52e252009-12-21 23:17:24 +00006456
6457 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00006458 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00006459 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00006460
6461 TemplateArgumentListInfo ExplicitTemplateArgs;
6462 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00006463
6464 // Look through all of the overloaded functions, searching for one
6465 // whose type matches exactly.
6466 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00006467 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6468 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00006469 // C++0x [temp.arg.explicit]p3:
6470 // [...] In contexts where deduction is done and fails, or in contexts
6471 // where deduction is not done, if a template argument list is
6472 // specified and it, along with any default template arguments,
6473 // identifies a single function template specialization, then the
6474 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00006475 FunctionTemplateDecl *FunctionTemplate
6476 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006477
6478 // C++ [over.over]p2:
6479 // If the name is a function template, template argument deduction is
6480 // done (14.8.2.2), and if the argument deduction succeeds, the
6481 // resulting template argument list is used to generate a single
6482 // function template specialization, which is added to the set of
6483 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00006484 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006485 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006486 if (TemplateDeductionResult Result
6487 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6488 Specialization, Info)) {
6489 // FIXME: make a note of the failed deduction for diagnostics.
6490 (void)Result;
6491 continue;
6492 }
6493
6494 // Multiple matches; we can't resolve to a single declaration.
6495 if (Matched)
6496 return 0;
6497
6498 Matched = Specialization;
6499 }
6500
6501 return Matched;
6502}
6503
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006504/// \brief Add a single candidate to the overload set.
6505static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00006506 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00006507 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006508 Expr **Args, unsigned NumArgs,
6509 OverloadCandidateSet &CandidateSet,
6510 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00006511 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00006512 if (isa<UsingShadowDecl>(Callee))
6513 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6514
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006515 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00006516 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00006517 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006518 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006519 return;
John McCallba135432009-11-21 08:51:07 +00006520 }
6521
6522 if (FunctionTemplateDecl *FuncTemplate
6523 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00006524 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6525 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006526 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00006527 return;
6528 }
6529
6530 assert(false && "unhandled case in overloaded call candidate");
6531
6532 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006533}
6534
6535/// \brief Add the overload candidates named by callee and/or found by argument
6536/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00006537void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006538 Expr **Args, unsigned NumArgs,
6539 OverloadCandidateSet &CandidateSet,
6540 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00006541
6542#ifndef NDEBUG
6543 // Verify that ArgumentDependentLookup is consistent with the rules
6544 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006545 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006546 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6547 // and let Y be the lookup set produced by argument dependent
6548 // lookup (defined as follows). If X contains
6549 //
6550 // -- a declaration of a class member, or
6551 //
6552 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00006553 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006554 //
6555 // -- a declaration that is neither a function or a function
6556 // template
6557 //
6558 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00006559
John McCall3b4294e2009-12-16 12:17:52 +00006560 if (ULE->requiresADL()) {
6561 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6562 E = ULE->decls_end(); I != E; ++I) {
6563 assert(!(*I)->getDeclContext()->isRecord());
6564 assert(isa<UsingShadowDecl>(*I) ||
6565 !(*I)->getDeclContext()->isFunctionOrMethod());
6566 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00006567 }
6568 }
6569#endif
6570
John McCall3b4294e2009-12-16 12:17:52 +00006571 // It would be nice to avoid this copy.
6572 TemplateArgumentListInfo TABuffer;
6573 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6574 if (ULE->hasExplicitTemplateArgs()) {
6575 ULE->copyTemplateArgumentsInto(TABuffer);
6576 ExplicitTemplateArgs = &TABuffer;
6577 }
6578
6579 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6580 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00006581 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006582 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006583 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00006584
John McCall3b4294e2009-12-16 12:17:52 +00006585 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00006586 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6587 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006588 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006589 CandidateSet,
6590 PartialOverloading);
6591}
John McCall578b69b2009-12-16 08:11:27 +00006592
6593/// Attempts to recover from a call where no functions were found.
6594///
6595/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00006596static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006597BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00006598 UnresolvedLookupExpr *ULE,
6599 SourceLocation LParenLoc,
6600 Expr **Args, unsigned NumArgs,
6601 SourceLocation *CommaLocs,
6602 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00006603
6604 CXXScopeSpec SS;
6605 if (ULE->getQualifier()) {
6606 SS.setScopeRep(ULE->getQualifier());
6607 SS.setRange(ULE->getQualifierRange());
6608 }
6609
John McCall3b4294e2009-12-16 12:17:52 +00006610 TemplateArgumentListInfo TABuffer;
6611 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6612 if (ULE->hasExplicitTemplateArgs()) {
6613 ULE->copyTemplateArgumentsInto(TABuffer);
6614 ExplicitTemplateArgs = &TABuffer;
6615 }
6616
John McCall578b69b2009-12-16 08:11:27 +00006617 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6618 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00006619 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
Douglas Gregorff331c12010-07-25 18:17:45 +00006620 return SemaRef.ExprError();
John McCall578b69b2009-12-16 08:11:27 +00006621
John McCall3b4294e2009-12-16 12:17:52 +00006622 assert(!R.empty() && "lookup results empty despite recovery");
6623
6624 // Build an implicit member call if appropriate. Just drop the
6625 // casts and such from the call, we don't really care.
John McCall60d7b3a2010-08-24 06:29:42 +00006626 ExprResult NewFn = SemaRef.ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00006627 if ((*R.begin())->isCXXClassMember())
6628 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6629 else if (ExplicitTemplateArgs)
6630 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6631 else
6632 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6633
6634 if (NewFn.isInvalid())
Douglas Gregorff331c12010-07-25 18:17:45 +00006635 return SemaRef.ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00006636
6637 // This shouldn't cause an infinite loop because we're giving it
6638 // an expression with non-empty lookup results, which should never
6639 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00006640 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
John McCallca0408f2010-08-23 06:44:23 +00006641 Sema::MultiExprArg(SemaRef, Args, NumArgs),
John McCall3b4294e2009-12-16 12:17:52 +00006642 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006643}
Douglas Gregord7a95972010-06-08 17:35:15 +00006644
Douglas Gregorf6b89692008-11-26 05:54:23 +00006645/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00006646/// (which eventually refers to the declaration Func) and the call
6647/// arguments Args/NumArgs, attempt to resolve the function call down
6648/// to a specific function. If overload resolution succeeds, returns
6649/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00006650/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00006651/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00006652ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006653Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00006654 SourceLocation LParenLoc,
6655 Expr **Args, unsigned NumArgs,
6656 SourceLocation *CommaLocs,
6657 SourceLocation RParenLoc) {
6658#ifndef NDEBUG
6659 if (ULE->requiresADL()) {
6660 // To do ADL, we must have found an unqualified name.
6661 assert(!ULE->getQualifier() && "qualified name with ADL");
6662
6663 // We don't perform ADL for implicit declarations of builtins.
6664 // Verify that this was correctly set up.
6665 FunctionDecl *F;
6666 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6667 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6668 F->getBuiltinID() && F->isImplicit())
6669 assert(0 && "performing ADL for builtin");
6670
6671 // We don't perform ADL in C.
6672 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6673 }
6674#endif
6675
John McCall5769d612010-02-08 23:07:23 +00006676 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00006677
John McCall3b4294e2009-12-16 12:17:52 +00006678 // Add the functions denoted by the callee to the set of candidate
6679 // functions, including those from argument-dependent lookup.
6680 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00006681
6682 // If we found nothing, try to recover.
6683 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6684 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00006685 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006686 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006687 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006688
Douglas Gregorf6b89692008-11-26 05:54:23 +00006689 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006690 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00006691 case OR_Success: {
6692 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00006693 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006694 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00006695 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall3b4294e2009-12-16 12:17:52 +00006696 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6697 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00006698
6699 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00006700 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00006701 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00006702 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006703 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006704 break;
6705
6706 case OR_Ambiguous:
6707 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00006708 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006709 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006710 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006711
6712 case OR_Deleted:
6713 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6714 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00006715 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006716 << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006717 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006718 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00006719 }
6720
Douglas Gregorff331c12010-07-25 18:17:45 +00006721 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00006722 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00006723}
6724
John McCall6e266892010-01-26 03:27:55 +00006725static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00006726 return Functions.size() > 1 ||
6727 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6728}
6729
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006730/// \brief Create a unary operation that may resolve to an overloaded
6731/// operator.
6732///
6733/// \param OpLoc The location of the operator itself (e.g., '*').
6734///
6735/// \param OpcIn The UnaryOperator::Opcode that describes this
6736/// operator.
6737///
6738/// \param Functions The set of non-member functions that will be
6739/// considered by overload resolution. The caller needs to build this
6740/// set based on the context using, e.g.,
6741/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6742/// set should not contain any member functions; those will be added
6743/// by CreateOverloadedUnaryOp().
6744///
6745/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00006746ExprResult
John McCall6e266892010-01-26 03:27:55 +00006747Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6748 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00006749 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006750 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006751
6752 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6753 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6754 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00006755 // TODO: provide better source location info.
6756 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006757
6758 Expr *Args[2] = { Input, 0 };
6759 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00006760
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006761 // For post-increment and post-decrement, add the implicit '0' as
6762 // the second argument, so that we know this is a post-increment or
6763 // post-decrement.
6764 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6765 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00006766 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006767 SourceLocation());
6768 NumArgs = 2;
6769 }
6770
6771 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00006772 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00006773 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00006774 Opc,
6775 Context.DependentTy,
6776 OpLoc));
6777
John McCallc373d482010-01-27 01:50:18 +00006778 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006779 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006780 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00006781 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006782 /*ADL*/ true, IsOverloaded(Fns),
6783 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006784 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6785 &Args[0], NumArgs,
6786 Context.DependentTy,
6787 OpLoc));
6788 }
6789
6790 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006791 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006792
6793 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006794 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006795
6796 // Add operator candidates that are member functions.
6797 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6798
John McCall6e266892010-01-26 03:27:55 +00006799 // Add candidates from ADL.
6800 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00006801 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00006802 /*ExplicitTemplateArgs*/ 0,
6803 CandidateSet);
6804
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006805 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006806 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006807
6808 // Perform overload resolution.
6809 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006810 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006811 case OR_Success: {
6812 // We found a built-in operator or an overloaded operator.
6813 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00006814
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006815 if (FnDecl) {
6816 // We matched an overloaded operator. Build a call to that
6817 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00006818
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006819 // Convert the arguments.
6820 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00006821 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006822
John McCall6bb80172010-03-30 21:47:33 +00006823 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6824 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006825 return ExprError();
6826 } else {
6827 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00006828 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00006829 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006830 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00006831 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00006832 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00006833 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006834 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00006835 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006836 }
6837
John McCallb697e082010-05-06 18:15:07 +00006838 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6839
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006840 // Determine the result type
Douglas Gregor5291c3c2010-07-13 08:18:22 +00006841 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006842
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006843 // Build the actual expression node.
6844 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6845 SourceLocation());
6846 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00006847
Eli Friedman4c3b8962009-11-18 03:58:17 +00006848 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00006849 CallExpr *TheCall =
Anders Carlsson26a2a072009-10-13 21:19:37 +00006850 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall9ae2f072010-08-23 23:25:46 +00006851 Args, NumArgs, ResultTy, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00006852
John McCall9ae2f072010-08-23 23:25:46 +00006853 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00006854 FnDecl))
6855 return ExprError();
6856
John McCall9ae2f072010-08-23 23:25:46 +00006857 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006858 } else {
6859 // We matched a built-in operator. Convert the arguments, then
6860 // break out so that we will build the appropriate built-in
6861 // operator node.
6862 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006863 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006864 return ExprError();
6865
6866 break;
6867 }
6868 }
6869
6870 case OR_No_Viable_Function:
6871 // No viable function; fall through to handling this as a
6872 // built-in operator, which will produce an error message for us.
6873 break;
6874
6875 case OR_Ambiguous:
6876 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6877 << UnaryOperator::getOpcodeStr(Opc)
6878 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006879 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
6880 Args, NumArgs,
6881 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006882 return ExprError();
6883
6884 case OR_Deleted:
6885 Diag(OpLoc, diag::err_ovl_deleted_oper)
6886 << Best->Function->isDeleted()
6887 << UnaryOperator::getOpcodeStr(Opc)
6888 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006889 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006890 return ExprError();
6891 }
6892
6893 // Either we found no viable overloaded operator or we matched a
6894 // built-in operator. In either case, fall through to trying to
6895 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00006896 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006897}
6898
Douglas Gregor063daf62009-03-13 18:40:31 +00006899/// \brief Create a binary operation that may resolve to an overloaded
6900/// operator.
6901///
6902/// \param OpLoc The location of the operator itself (e.g., '+').
6903///
6904/// \param OpcIn The BinaryOperator::Opcode that describes this
6905/// operator.
6906///
6907/// \param Functions The set of non-member functions that will be
6908/// considered by overload resolution. The caller needs to build this
6909/// set based on the context using, e.g.,
6910/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6911/// set should not contain any member functions; those will be added
6912/// by CreateOverloadedBinOp().
6913///
6914/// \param LHS Left-hand argument.
6915/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00006916ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00006917Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006918 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00006919 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00006920 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006921 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006922 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00006923
6924 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6925 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6926 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6927
6928 // If either side is type-dependent, create an appropriate dependent
6929 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006930 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00006931 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006932 // If there are no functions to store, just build a dependent
6933 // BinaryOperator or CompoundAssignment.
6934 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6935 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6936 Context.DependentTy, OpLoc));
6937
6938 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6939 Context.DependentTy,
6940 Context.DependentTy,
6941 Context.DependentTy,
6942 OpLoc));
6943 }
John McCall6e266892010-01-26 03:27:55 +00006944
6945 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00006946 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00006947 // TODO: provide better source location info in DNLoc component.
6948 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00006949 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006950 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00006951 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006952 /*ADL*/ true, IsOverloaded(Fns),
6953 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00006954 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00006955 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00006956 Context.DependentTy,
6957 OpLoc));
6958 }
6959
6960 // If this is the .* operator, which is not overloadable, just
6961 // create a built-in binary operator.
6962 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006963 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006964
Sebastian Redl275c2b42009-11-18 23:10:33 +00006965 // If this is the assignment operator, we only perform overload resolution
6966 // if the left-hand side is a class or enumeration type. This is actually
6967 // a hack. The standard requires that we do overload resolution between the
6968 // various built-in candidates, but as DR507 points out, this can lead to
6969 // problems. So we do it this way, which pretty much follows what GCC does.
6970 // Note that we go the traditional code path for compound assignment forms.
6971 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006972 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006973
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006974 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006975 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006976
6977 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006978 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00006979
6980 // Add operator candidates that are member functions.
6981 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6982
John McCall6e266892010-01-26 03:27:55 +00006983 // Add candidates from ADL.
6984 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6985 Args, 2,
6986 /*ExplicitTemplateArgs*/ 0,
6987 CandidateSet);
6988
Douglas Gregor063daf62009-03-13 18:40:31 +00006989 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006990 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00006991
6992 // Perform overload resolution.
6993 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006994 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006995 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00006996 // We found a built-in operator or an overloaded operator.
6997 FunctionDecl *FnDecl = Best->Function;
6998
6999 if (FnDecl) {
7000 // We matched an overloaded operator. Build a call to that
7001 // operator.
7002
7003 // Convert the arguments.
7004 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00007005 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00007006 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007007
John McCall60d7b3a2010-08-24 06:29:42 +00007008 ExprResult Arg1
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007009 = PerformCopyInitialization(
7010 InitializedEntity::InitializeParameter(
7011 FnDecl->getParamDecl(0)),
7012 SourceLocation(),
7013 Owned(Args[1]));
7014 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007015 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007016
Douglas Gregor5fccd362010-03-03 23:55:11 +00007017 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007018 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007019 return ExprError();
7020
7021 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007022 } else {
7023 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007024 ExprResult Arg0
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007025 = PerformCopyInitialization(
7026 InitializedEntity::InitializeParameter(
7027 FnDecl->getParamDecl(0)),
7028 SourceLocation(),
7029 Owned(Args[0]));
7030 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007031 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007032
John McCall60d7b3a2010-08-24 06:29:42 +00007033 ExprResult Arg1
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007034 = PerformCopyInitialization(
7035 InitializedEntity::InitializeParameter(
7036 FnDecl->getParamDecl(1)),
7037 SourceLocation(),
7038 Owned(Args[1]));
7039 if (Arg1.isInvalid())
7040 return ExprError();
7041 Args[0] = LHS = Arg0.takeAs<Expr>();
7042 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007043 }
7044
John McCallb697e082010-05-06 18:15:07 +00007045 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7046
Douglas Gregor063daf62009-03-13 18:40:31 +00007047 // Determine the result type
7048 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007049 = FnDecl->getType()->getAs<FunctionType>()
7050 ->getCallResultType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00007051
7052 // Build the actual expression node.
7053 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00007054 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007055 UsualUnaryConversions(FnExpr);
7056
John McCall9ae2f072010-08-23 23:25:46 +00007057 CXXOperatorCallExpr *TheCall =
7058 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7059 Args, 2, ResultTy, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007060
John McCall9ae2f072010-08-23 23:25:46 +00007061 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00007062 FnDecl))
7063 return ExprError();
7064
John McCall9ae2f072010-08-23 23:25:46 +00007065 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00007066 } else {
7067 // We matched a built-in operator. Convert the arguments, then
7068 // break out so that we will build the appropriate built-in
7069 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007070 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007071 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007072 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007073 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00007074 return ExprError();
7075
7076 break;
7077 }
7078 }
7079
Douglas Gregor33074752009-09-30 21:46:01 +00007080 case OR_No_Viable_Function: {
7081 // C++ [over.match.oper]p9:
7082 // If the operator is the operator , [...] and there are no
7083 // viable functions, then the operator is assumed to be the
7084 // built-in operator and interpreted according to clause 5.
7085 if (Opc == BinaryOperator::Comma)
7086 break;
7087
Sebastian Redl8593c782009-05-21 11:50:50 +00007088 // For class as left operand for assignment or compound assigment operator
7089 // do not fall through to handling in built-in, but report that no overloaded
7090 // assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00007091 ExprResult Result = ExprError();
Douglas Gregor33074752009-09-30 21:46:01 +00007092 if (Args[0]->getType()->isRecordType() &&
7093 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00007094 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7095 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007096 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00007097 } else {
7098 // No viable function; try to create a built-in operation, which will
7099 // produce an error. Then, show the non-viable candidates.
7100 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00007101 }
Douglas Gregor33074752009-09-30 21:46:01 +00007102 assert(Result.isInvalid() &&
7103 "C++ binary operator overloading is missing candidates!");
7104 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00007105 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7106 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00007107 return move(Result);
7108 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007109
7110 case OR_Ambiguous:
7111 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7112 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007113 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007114 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7115 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007116 return ExprError();
7117
7118 case OR_Deleted:
7119 Diag(OpLoc, diag::err_ovl_deleted_oper)
7120 << Best->Function->isDeleted()
7121 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007122 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007123 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00007124 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00007125 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007126
Douglas Gregor33074752009-09-30 21:46:01 +00007127 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007128 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007129}
7130
John McCall60d7b3a2010-08-24 06:29:42 +00007131ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +00007132Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7133 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007134 Expr *Base, Expr *Idx) {
7135 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +00007136 DeclarationName OpName =
7137 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7138
7139 // If either side is type-dependent, create an appropriate dependent
7140 // expression.
7141 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7142
John McCallc373d482010-01-27 01:50:18 +00007143 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007144 // CHECKME: no 'operator' keyword?
7145 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7146 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00007147 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007148 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007149 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007150 /*ADL*/ true, /*Overloaded*/ false,
7151 UnresolvedSetIterator(),
7152 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00007153 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00007154
Sebastian Redlf322ed62009-10-29 20:17:01 +00007155 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7156 Args, 2,
7157 Context.DependentTy,
7158 RLoc));
7159 }
7160
7161 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007162 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007163
7164 // Subscript can only be overloaded as a member function.
7165
7166 // Add operator candidates that are member functions.
7167 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7168
7169 // Add builtin operator candidates.
7170 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7171
7172 // Perform overload resolution.
7173 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007174 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00007175 case OR_Success: {
7176 // We found a built-in operator or an overloaded operator.
7177 FunctionDecl *FnDecl = Best->Function;
7178
7179 if (FnDecl) {
7180 // We matched an overloaded operator. Build a call to that
7181 // operator.
7182
John McCall9aa472c2010-03-19 07:35:19 +00007183 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007184 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00007185
Sebastian Redlf322ed62009-10-29 20:17:01 +00007186 // Convert the arguments.
7187 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007188 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007189 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007190 return ExprError();
7191
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007192 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007193 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007194 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7195 FnDecl->getParamDecl(0)),
7196 SourceLocation(),
7197 Owned(Args[1]));
7198 if (InputInit.isInvalid())
7199 return ExprError();
7200
7201 Args[1] = InputInit.takeAs<Expr>();
7202
Sebastian Redlf322ed62009-10-29 20:17:01 +00007203 // Determine the result type
7204 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007205 = FnDecl->getType()->getAs<FunctionType>()
7206 ->getCallResultType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007207
7208 // Build the actual expression node.
7209 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7210 LLoc);
7211 UsualUnaryConversions(FnExpr);
7212
John McCall9ae2f072010-08-23 23:25:46 +00007213 CXXOperatorCallExpr *TheCall =
7214 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7215 FnExpr, Args, 2,
7216 ResultTy, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007217
John McCall9ae2f072010-08-23 23:25:46 +00007218 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007219 FnDecl))
7220 return ExprError();
7221
John McCall9ae2f072010-08-23 23:25:46 +00007222 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007223 } else {
7224 // We matched a built-in operator. Convert the arguments, then
7225 // break out so that we will build the appropriate built-in
7226 // operator node.
7227 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007228 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00007229 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007230 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007231 return ExprError();
7232
7233 break;
7234 }
7235 }
7236
7237 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00007238 if (CandidateSet.empty())
7239 Diag(LLoc, diag::err_ovl_no_oper)
7240 << Args[0]->getType() << /*subscript*/ 0
7241 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7242 else
7243 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7244 << Args[0]->getType()
7245 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007246 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7247 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +00007248 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00007249 }
7250
7251 case OR_Ambiguous:
7252 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7253 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007254 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7255 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007256 return ExprError();
7257
7258 case OR_Deleted:
7259 Diag(LLoc, diag::err_ovl_deleted_oper)
7260 << Best->Function->isDeleted() << "[]"
7261 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007262 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7263 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007264 return ExprError();
7265 }
7266
7267 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +00007268 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007269}
7270
Douglas Gregor88a35142008-12-22 05:46:06 +00007271/// BuildCallToMemberFunction - Build a call to a member
7272/// function. MemExpr is the expression that refers to the member
7273/// function (and includes the object parameter), Args/NumArgs are the
7274/// arguments to the function call (not including the object
7275/// parameter). The caller needs to validate that the member
7276/// expression refers to a member function or an overloaded member
7277/// function.
John McCall60d7b3a2010-08-24 06:29:42 +00007278ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007279Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7280 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00007281 unsigned NumArgs, SourceLocation *CommaLocs,
7282 SourceLocation RParenLoc) {
7283 // Dig out the member expression. This holds both the object
7284 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00007285 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7286
John McCall129e2df2009-11-30 22:42:35 +00007287 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00007288 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00007289 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007290 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00007291 if (isa<MemberExpr>(NakedMemExpr)) {
7292 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00007293 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00007294 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00007295 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00007296 } else {
7297 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007298 Qualifier = UnresExpr->getQualifier();
7299
John McCall701c89e2009-12-03 04:06:58 +00007300 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00007301
Douglas Gregor88a35142008-12-22 05:46:06 +00007302 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00007303 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00007304
John McCallaa81e162009-12-01 22:10:20 +00007305 // FIXME: avoid copy.
7306 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7307 if (UnresExpr->hasExplicitTemplateArgs()) {
7308 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7309 TemplateArgs = &TemplateArgsBuffer;
7310 }
7311
John McCall129e2df2009-11-30 22:42:35 +00007312 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7313 E = UnresExpr->decls_end(); I != E; ++I) {
7314
John McCall701c89e2009-12-03 04:06:58 +00007315 NamedDecl *Func = *I;
7316 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7317 if (isa<UsingShadowDecl>(Func))
7318 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7319
John McCall129e2df2009-11-30 22:42:35 +00007320 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007321 // If explicit template arguments were provided, we can't call a
7322 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00007323 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007324 continue;
7325
John McCall9aa472c2010-03-19 07:35:19 +00007326 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00007327 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00007328 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007329 } else {
John McCall129e2df2009-11-30 22:42:35 +00007330 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00007331 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00007332 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00007333 CandidateSet,
7334 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007335 }
Douglas Gregordec06662009-08-21 18:42:58 +00007336 }
Mike Stump1eb44332009-09-09 15:08:12 +00007337
John McCall129e2df2009-11-30 22:42:35 +00007338 DeclarationName DeclName = UnresExpr->getMemberName();
7339
Douglas Gregor88a35142008-12-22 05:46:06 +00007340 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007341 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
7342 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007343 case OR_Success:
7344 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007345 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00007346 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007347 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00007348 break;
7349
7350 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00007351 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00007352 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007353 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007354 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007355 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007356 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007357
7358 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00007359 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007360 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007361 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007362 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007363 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007364
7365 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00007366 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007367 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00007368 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007369 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007370 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007371 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007372 }
7373
John McCall6bb80172010-03-30 21:47:33 +00007374 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00007375
John McCallaa81e162009-12-01 22:10:20 +00007376 // If overload resolution picked a static member, build a
7377 // non-member call based on that function.
7378 if (Method->isStatic()) {
7379 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7380 Args, NumArgs, RParenLoc);
7381 }
7382
John McCall129e2df2009-11-30 22:42:35 +00007383 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00007384 }
7385
7386 assert(Method && "Member call to something that isn't a method?");
John McCall9ae2f072010-08-23 23:25:46 +00007387 CXXMemberCallExpr *TheCall =
7388 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
7389 Method->getCallResultType(),
7390 RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +00007391
Anders Carlssoneed3e692009-10-10 00:06:20 +00007392 // Check for a valid return type.
7393 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +00007394 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +00007395 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00007396
Douglas Gregor88a35142008-12-22 05:46:06 +00007397 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00007398 // We only need to do this if there was actually an overload; otherwise
7399 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00007400 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00007401 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00007402 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7403 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00007404 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007405 MemExpr->setBase(ObjectArg);
7406
7407 // Convert the rest of the arguments
Douglas Gregor5f970ee2010-05-04 18:18:31 +00007408 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +00007409 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00007410 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00007411 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007412
John McCall9ae2f072010-08-23 23:25:46 +00007413 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +00007414 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00007415
John McCall9ae2f072010-08-23 23:25:46 +00007416 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +00007417}
7418
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007419/// BuildCallToObjectOfClassType - Build a call to an object of class
7420/// type (C++ [over.call.object]), which can end up invoking an
7421/// overloaded function call operator (@c operator()) or performing a
7422/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00007423Sema::ExprResult
7424Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00007425 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007426 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00007427 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007428 SourceLocation RParenLoc) {
7429 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00007430 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007431
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007432 // C++ [over.call.object]p1:
7433 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00007434 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007435 // candidate functions includes at least the function call
7436 // operators of T. The function call operators of T are obtained by
7437 // ordinary lookup of the name operator() in the context of
7438 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00007439 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00007440 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00007441
7442 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007443 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00007444 << Object->getSourceRange()))
7445 return true;
7446
John McCalla24dc2e2009-11-17 02:14:36 +00007447 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7448 LookupQualifiedName(R, Record->getDecl());
7449 R.suppressDiagnostics();
7450
Douglas Gregor593564b2009-11-15 07:48:03 +00007451 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00007452 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007453 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00007454 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00007455 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00007456 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00007457
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007458 // C++ [over.call.object]p2:
7459 // In addition, for each conversion function declared in T of the
7460 // form
7461 //
7462 // operator conversion-type-id () cv-qualifier;
7463 //
7464 // where cv-qualifier is the same cv-qualification as, or a
7465 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00007466 // denotes the type "pointer to function of (P1,...,Pn) returning
7467 // R", or the type "reference to pointer to function of
7468 // (P1,...,Pn) returning R", or the type "reference to function
7469 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007470 // is also considered as a candidate function. Similarly,
7471 // surrogate call functions are added to the set of candidate
7472 // functions for each conversion function declared in an
7473 // accessible base class provided the function is not hidden
7474 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00007475 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00007476 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00007477 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00007478 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00007479 NamedDecl *D = *I;
7480 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7481 if (isa<UsingShadowDecl>(D))
7482 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7483
Douglas Gregor4a27d702009-10-21 06:18:39 +00007484 // Skip over templated conversion functions; they aren't
7485 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00007486 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00007487 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007488
John McCall701c89e2009-12-03 04:06:58 +00007489 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00007490
Douglas Gregor4a27d702009-10-21 06:18:39 +00007491 // Strip the reference type (if any) and then the pointer type (if
7492 // any) to get down to what might be a function type.
7493 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7494 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7495 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007496
Douglas Gregor4a27d702009-10-21 06:18:39 +00007497 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00007498 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00007499 Object->getType(), Args, NumArgs,
7500 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007501 }
Mike Stump1eb44332009-09-09 15:08:12 +00007502
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007503 // Perform overload resolution.
7504 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007505 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7506 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007507 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007508 // Overload resolution succeeded; we'll build the appropriate call
7509 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007510 break;
7511
7512 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00007513 if (CandidateSet.empty())
7514 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7515 << Object->getType() << /*call*/ 1
7516 << Object->getSourceRange();
7517 else
7518 Diag(Object->getSourceRange().getBegin(),
7519 diag::err_ovl_no_viable_object_call)
7520 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007521 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007522 break;
7523
7524 case OR_Ambiguous:
7525 Diag(Object->getSourceRange().getBegin(),
7526 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00007527 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007528 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007529 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007530
7531 case OR_Deleted:
7532 Diag(Object->getSourceRange().getBegin(),
7533 diag::err_ovl_deleted_object_call)
7534 << Best->Function->isDeleted()
7535 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007536 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007537 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007538 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007539
Douglas Gregorff331c12010-07-25 18:17:45 +00007540 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007541 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007542
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007543 if (Best->Function == 0) {
7544 // Since there is no function declaration, this is one of the
7545 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00007546 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007547 = cast<CXXConversionDecl>(
7548 Best->Conversions[0].UserDefined.ConversionFunction);
7549
John McCall9aa472c2010-03-19 07:35:19 +00007550 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007551 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007552
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007553 // We selected one of the surrogate functions that converts the
7554 // object parameter to a function pointer. Perform the conversion
7555 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007556
7557 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007558 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00007559 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7560 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007561
John McCall9ae2f072010-08-23 23:25:46 +00007562 return ActOnCallExpr(S, CE, LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00007563 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
John McCall182f7092010-08-24 06:09:16 +00007564 CommaLocs, RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007565 }
7566
John McCall9aa472c2010-03-19 07:35:19 +00007567 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007568 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007569
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007570 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7571 // that calls this method, using Object for the implicit object
7572 // parameter and passing along the remaining arguments.
7573 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00007574 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007575
7576 unsigned NumArgsInProto = Proto->getNumArgs();
7577 unsigned NumArgsToCheck = NumArgs;
7578
7579 // Build the full argument list for the method call (the
7580 // implicit object parameter is placed at the beginning of the
7581 // list).
7582 Expr **MethodArgs;
7583 if (NumArgs < NumArgsInProto) {
7584 NumArgsToCheck = NumArgsInProto;
7585 MethodArgs = new Expr*[NumArgsInProto + 1];
7586 } else {
7587 MethodArgs = new Expr*[NumArgs + 1];
7588 }
7589 MethodArgs[0] = Object;
7590 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7591 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00007592
7593 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00007594 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007595 UsualUnaryConversions(NewFn);
7596
7597 // Once we've built TheCall, all of the expressions are properly
7598 // owned.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007599 QualType ResultTy = Method->getCallResultType();
John McCall9ae2f072010-08-23 23:25:46 +00007600 CXXOperatorCallExpr *TheCall =
7601 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7602 MethodArgs, NumArgs + 1,
7603 ResultTy, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007604 delete [] MethodArgs;
7605
John McCall9ae2f072010-08-23 23:25:46 +00007606 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +00007607 Method))
7608 return true;
7609
Douglas Gregor518fda12009-01-13 05:10:00 +00007610 // We may have default arguments. If so, we need to allocate more
7611 // slots in the call for them.
7612 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007613 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00007614 else if (NumArgs > NumArgsInProto)
7615 NumArgsToCheck = NumArgsInProto;
7616
Chris Lattner312531a2009-04-12 08:11:20 +00007617 bool IsError = false;
7618
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007619 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00007620 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007621 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007622 TheCall->setArg(0, Object);
7623
Chris Lattner312531a2009-04-12 08:11:20 +00007624
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007625 // Check the argument types.
7626 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007627 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00007628 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007629 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00007630
Douglas Gregor518fda12009-01-13 05:10:00 +00007631 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00007632
John McCall60d7b3a2010-08-24 06:29:42 +00007633 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +00007634 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7635 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +00007636 SourceLocation(), Arg);
Anders Carlsson3faa4862010-01-29 18:43:53 +00007637
7638 IsError |= InputInit.isInvalid();
7639 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007640 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00007641 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +00007642 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7643 if (DefArg.isInvalid()) {
7644 IsError = true;
7645 break;
7646 }
7647
7648 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007649 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007650
7651 TheCall->setArg(i + 1, Arg);
7652 }
7653
7654 // If this is a variadic call, handle args passed through "...".
7655 if (Proto->isVariadic()) {
7656 // Promote the arguments (C99 6.5.2.2p7).
7657 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7658 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00007659 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007660 TheCall->setArg(i + 1, Arg);
7661 }
7662 }
7663
Chris Lattner312531a2009-04-12 08:11:20 +00007664 if (IsError) return true;
7665
John McCall9ae2f072010-08-23 23:25:46 +00007666 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00007667 return true;
7668
John McCall182f7092010-08-24 06:09:16 +00007669 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007670}
7671
Douglas Gregor8ba10742008-11-20 16:27:02 +00007672/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00007673/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00007674/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +00007675ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00007676Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007677 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00007678
John McCall5769d612010-02-08 23:07:23 +00007679 SourceLocation Loc = Base->getExprLoc();
7680
Douglas Gregor8ba10742008-11-20 16:27:02 +00007681 // C++ [over.ref]p1:
7682 //
7683 // [...] An expression x->m is interpreted as (x.operator->())->m
7684 // for a class object x of type T if T::operator->() exists and if
7685 // the operator is selected as the best match function by the
7686 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00007687 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00007688 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00007689 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007690
John McCall5769d612010-02-08 23:07:23 +00007691 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00007692 PDiag(diag::err_typecheck_incomplete_tag)
7693 << Base->getSourceRange()))
7694 return ExprError();
7695
John McCalla24dc2e2009-11-17 02:14:36 +00007696 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7697 LookupQualifiedName(R, BaseRecord->getDecl());
7698 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00007699
7700 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00007701 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007702 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00007703 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00007704 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00007705
7706 // Perform overload resolution.
7707 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007708 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007709 case OR_Success:
7710 // Overload resolution succeeded; we'll build the call below.
7711 break;
7712
7713 case OR_No_Viable_Function:
7714 if (CandidateSet.empty())
7715 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007716 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007717 else
7718 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007719 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007720 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007721 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007722
7723 case OR_Ambiguous:
7724 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00007725 << "->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007726 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007727 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007728
7729 case OR_Deleted:
7730 Diag(OpLoc, diag::err_ovl_deleted_oper)
7731 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00007732 << "->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007733 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007734 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007735 }
7736
John McCall9aa472c2010-03-19 07:35:19 +00007737 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007738 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00007739
Douglas Gregor8ba10742008-11-20 16:27:02 +00007740 // Convert the object parameter.
7741 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007742 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7743 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007744 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00007745
Douglas Gregor8ba10742008-11-20 16:27:02 +00007746 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00007747 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7748 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007749 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007750
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007751 QualType ResultTy = Method->getCallResultType();
John McCall9ae2f072010-08-23 23:25:46 +00007752 CXXOperatorCallExpr *TheCall =
7753 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7754 &Base, 1, ResultTy, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007755
John McCall9ae2f072010-08-23 23:25:46 +00007756 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00007757 Method))
7758 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00007759 return Owned(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00007760}
7761
Douglas Gregor904eed32008-11-10 20:40:00 +00007762/// FixOverloadedFunctionReference - E is an expression that refers to
7763/// a C++ overloaded function (possibly with some parentheses and
7764/// perhaps a '&' around it). We have resolved the overloaded function
7765/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00007766/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00007767Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00007768 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00007769 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007770 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7771 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007772 if (SubExpr == PE->getSubExpr())
7773 return PE->Retain();
7774
7775 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7776 }
7777
7778 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007779 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7780 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00007781 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00007782 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00007783 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +00007784 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +00007785 if (SubExpr == ICE->getSubExpr())
7786 return ICE->Retain();
7787
John McCallf871d0c2010-08-07 06:22:56 +00007788 return ImplicitCastExpr::Create(Context, ICE->getType(),
7789 ICE->getCastKind(),
7790 SubExpr, 0,
7791 ICE->getCategory());
Douglas Gregor699ee522009-11-20 19:42:02 +00007792 }
7793
7794 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007795 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00007796 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00007797 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7798 if (Method->isStatic()) {
7799 // Do nothing: static member functions aren't any different
7800 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00007801 } else {
John McCallf7a1a742009-11-24 19:00:30 +00007802 // Fix the sub expression, which really has to be an
7803 // UnresolvedLookupExpr holding an overloaded member function
7804 // or template.
John McCall6bb80172010-03-30 21:47:33 +00007805 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7806 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00007807 if (SubExpr == UnOp->getSubExpr())
7808 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00007809
John McCallba135432009-11-21 08:51:07 +00007810 assert(isa<DeclRefExpr>(SubExpr)
7811 && "fixed to something other than a decl ref");
7812 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7813 && "fixed to a member ref with no nested name qualifier");
7814
7815 // We have taken the address of a pointer to member
7816 // function. Perform the computation here so that we get the
7817 // appropriate pointer to member type.
7818 QualType ClassType
7819 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7820 QualType MemPtrType
7821 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7822
7823 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7824 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00007825 }
7826 }
John McCall6bb80172010-03-30 21:47:33 +00007827 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7828 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007829 if (SubExpr == UnOp->getSubExpr())
7830 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00007831
Douglas Gregor699ee522009-11-20 19:42:02 +00007832 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7833 Context.getPointerType(SubExpr->getType()),
7834 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00007835 }
John McCallba135432009-11-21 08:51:07 +00007836
7837 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00007838 // FIXME: avoid copy.
7839 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00007840 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00007841 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7842 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00007843 }
7844
John McCallba135432009-11-21 08:51:07 +00007845 return DeclRefExpr::Create(Context,
7846 ULE->getQualifier(),
7847 ULE->getQualifierRange(),
7848 Fn,
7849 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00007850 Fn->getType(),
7851 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00007852 }
7853
John McCall129e2df2009-11-30 22:42:35 +00007854 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00007855 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00007856 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7857 if (MemExpr->hasExplicitTemplateArgs()) {
7858 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7859 TemplateArgs = &TemplateArgsBuffer;
7860 }
John McCalld5532b62009-11-23 01:53:49 +00007861
John McCallaa81e162009-12-01 22:10:20 +00007862 Expr *Base;
7863
7864 // If we're filling in
7865 if (MemExpr->isImplicitAccess()) {
7866 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7867 return DeclRefExpr::Create(Context,
7868 MemExpr->getQualifier(),
7869 MemExpr->getQualifierRange(),
7870 Fn,
7871 MemExpr->getMemberLoc(),
7872 Fn->getType(),
7873 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00007874 } else {
7875 SourceLocation Loc = MemExpr->getMemberLoc();
7876 if (MemExpr->getQualifier())
7877 Loc = MemExpr->getQualifierRange().getBegin();
7878 Base = new (Context) CXXThisExpr(Loc,
7879 MemExpr->getBaseType(),
7880 /*isImplicit=*/true);
7881 }
John McCallaa81e162009-12-01 22:10:20 +00007882 } else
7883 Base = MemExpr->getBase()->Retain();
7884
7885 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00007886 MemExpr->isArrow(),
7887 MemExpr->getQualifier(),
7888 MemExpr->getQualifierRange(),
7889 Fn,
John McCall6bb80172010-03-30 21:47:33 +00007890 Found,
Abramo Bagnara25777432010-08-11 22:01:17 +00007891 MemExpr->getMemberNameInfo(),
John McCallaa81e162009-12-01 22:10:20 +00007892 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00007893 Fn->getType());
7894 }
7895
Douglas Gregor699ee522009-11-20 19:42:02 +00007896 assert(false && "Invalid reference to overloaded function");
7897 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00007898}
7899
John McCall60d7b3a2010-08-24 06:29:42 +00007900ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
7901 DeclAccessPair Found,
7902 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00007903 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00007904}
7905
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007906} // end namespace clang