blob: 4c843ea738229b2b5537686d5474efae59fb85b3 [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000026#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000028#include "llvm/ADT/DenseSet.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000029#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000031#include <algorithm>
32
33namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000034using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000035
John McCall120d63c2010-08-24 20:38:10 +000036static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
37 bool InOverloadResolution,
38 StandardConversionSequence &SCS);
39static OverloadingResult
40IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
41 UserDefinedConversionSequence& User,
42 OverloadCandidateSet& Conversions,
43 bool AllowExplicit);
44
45
46static ImplicitConversionSequence::CompareKind
47CompareStandardConversionSequences(Sema &S,
48 const StandardConversionSequence& SCS1,
49 const StandardConversionSequence& SCS2);
50
51static ImplicitConversionSequence::CompareKind
52CompareQualificationConversions(Sema &S,
53 const StandardConversionSequence& SCS1,
54 const StandardConversionSequence& SCS2);
55
56static ImplicitConversionSequence::CompareKind
57CompareDerivedToBaseConversions(Sema &S,
58 const StandardConversionSequence& SCS1,
59 const StandardConversionSequence& SCS2);
60
61
62
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000063/// GetConversionCategory - Retrieve the implicit conversion
64/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000065ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000066GetConversionCategory(ImplicitConversionKind Kind) {
67 static const ImplicitConversionCategory
68 Category[(int)ICK_Num_Conversion_Kinds] = {
69 ICC_Identity,
70 ICC_Lvalue_Transformation,
71 ICC_Lvalue_Transformation,
72 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000073 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000074 ICC_Qualification_Adjustment,
75 ICC_Promotion,
76 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000077 ICC_Promotion,
78 ICC_Conversion,
79 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000080 ICC_Conversion,
81 ICC_Conversion,
82 ICC_Conversion,
83 ICC_Conversion,
84 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000085 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000086 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +000087 ICC_Conversion,
88 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000089 ICC_Conversion
90 };
91 return Category[(int)Kind];
92}
93
94/// GetConversionRank - Retrieve the implicit conversion rank
95/// corresponding to the given implicit conversion kind.
96ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
97 static const ImplicitConversionRank
98 Rank[(int)ICK_Num_Conversion_Kinds] = {
99 ICR_Exact_Match,
100 ICR_Exact_Match,
101 ICR_Exact_Match,
102 ICR_Exact_Match,
103 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000104 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000105 ICR_Promotion,
106 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000107 ICR_Promotion,
108 ICR_Conversion,
109 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000110 ICR_Conversion,
111 ICR_Conversion,
112 ICR_Conversion,
113 ICR_Conversion,
114 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000115 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000116 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000117 ICR_Conversion,
118 ICR_Conversion,
Chandler Carruth23a370f2010-02-25 07:20:54 +0000119 ICR_Complex_Real_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000120 };
121 return Rank[(int)Kind];
122}
123
124/// GetImplicitConversionName - Return the name of this kind of
125/// implicit conversion.
126const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000127 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000128 "No conversion",
129 "Lvalue-to-rvalue",
130 "Array-to-pointer",
131 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000132 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000133 "Qualification",
134 "Integral promotion",
135 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000136 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000137 "Integral conversion",
138 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000139 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000140 "Floating-integral conversion",
141 "Pointer conversion",
142 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000143 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000144 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000145 "Derived-to-base conversion",
146 "Vector conversion",
147 "Vector splat",
148 "Complex-real conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000149 };
150 return Name[Kind];
151}
152
Douglas Gregor60d62c22008-10-31 16:23:19 +0000153/// StandardConversionSequence - Set the standard conversion
154/// sequence to the identity conversion.
155void StandardConversionSequence::setAsIdentityConversion() {
156 First = ICK_Identity;
157 Second = ICK_Identity;
158 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000159 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000160 ReferenceBinding = false;
161 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000162 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000163 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000164}
165
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000166/// getRank - Retrieve the rank of this standard conversion sequence
167/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
168/// implicit conversions.
169ImplicitConversionRank StandardConversionSequence::getRank() const {
170 ImplicitConversionRank Rank = ICR_Exact_Match;
171 if (GetConversionRank(First) > Rank)
172 Rank = GetConversionRank(First);
173 if (GetConversionRank(Second) > Rank)
174 Rank = GetConversionRank(Second);
175 if (GetConversionRank(Third) > Rank)
176 Rank = GetConversionRank(Third);
177 return Rank;
178}
179
180/// isPointerConversionToBool - Determines whether this conversion is
181/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000182/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000183/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000184bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000185 // Note that FromType has not necessarily been transformed by the
186 // array-to-pointer or function-to-pointer implicit conversions, so
187 // check for their presence as well as checking whether FromType is
188 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000189 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000190 (getFromType()->isPointerType() ||
191 getFromType()->isObjCObjectPointerType() ||
192 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000193 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000194 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
195 return true;
196
197 return false;
198}
199
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000200/// isPointerConversionToVoidPointer - Determines whether this
201/// conversion is a conversion of a pointer to a void pointer. This is
202/// used as part of the ranking of standard conversion sequences (C++
203/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000204bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000205StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000206isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000207 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000208 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000209
210 // Note that FromType has not necessarily been transformed by the
211 // array-to-pointer implicit conversion, so check for its presence
212 // and redo the conversion to get a pointer.
213 if (First == ICK_Array_To_Pointer)
214 FromType = Context.getArrayDecayedType(FromType);
215
John McCall202422e2010-10-26 06:40:27 +0000216 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000217 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000218 return ToPtrType->getPointeeType()->isVoidType();
219
220 return false;
221}
222
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000223/// DebugPrint - Print this standard conversion sequence to standard
224/// error. Useful for debugging overloading issues.
225void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000226 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000227 bool PrintedSomething = false;
228 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000229 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000230 PrintedSomething = true;
231 }
232
233 if (Second != ICK_Identity) {
234 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000235 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000236 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000237 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000238
239 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000240 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000241 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000242 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000243 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000244 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000245 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000246 PrintedSomething = true;
247 }
248
249 if (Third != ICK_Identity) {
250 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000251 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000252 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000253 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000254 PrintedSomething = true;
255 }
256
257 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000258 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000259 }
260}
261
262/// DebugPrint - Print this user-defined conversion sequence to standard
263/// error. Useful for debugging overloading issues.
264void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000265 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000266 if (Before.First || Before.Second || Before.Third) {
267 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000268 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000269 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000270 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000271 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000272 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000273 After.DebugPrint();
274 }
275}
276
277/// DebugPrint - Print this implicit conversion sequence to standard
278/// error. Useful for debugging overloading issues.
279void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000280 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000281 switch (ConversionKind) {
282 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000283 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000284 Standard.DebugPrint();
285 break;
286 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000287 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000288 UserDefined.DebugPrint();
289 break;
290 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000291 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000292 break;
John McCall1d318332010-01-12 00:44:57 +0000293 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000294 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000295 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000296 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000297 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000298 break;
299 }
300
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000301 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000302}
303
John McCall1d318332010-01-12 00:44:57 +0000304void AmbiguousConversionSequence::construct() {
305 new (&conversions()) ConversionSet();
306}
307
308void AmbiguousConversionSequence::destruct() {
309 conversions().~ConversionSet();
310}
311
312void
313AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
314 FromTypePtr = O.FromTypePtr;
315 ToTypePtr = O.ToTypePtr;
316 new (&conversions()) ConversionSet(O.conversions());
317}
318
Douglas Gregora9333192010-05-08 17:41:32 +0000319namespace {
320 // Structure used by OverloadCandidate::DeductionFailureInfo to store
321 // template parameter and template argument information.
322 struct DFIParamWithArguments {
323 TemplateParameter Param;
324 TemplateArgument FirstArg;
325 TemplateArgument SecondArg;
326 };
327}
328
329/// \brief Convert from Sema's representation of template deduction information
330/// to the form used in overload-candidate information.
331OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000332static MakeDeductionFailureInfo(ASTContext &Context,
333 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000334 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000335 OverloadCandidate::DeductionFailureInfo Result;
336 Result.Result = static_cast<unsigned>(TDK);
337 Result.Data = 0;
338 switch (TDK) {
339 case Sema::TDK_Success:
340 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000341 case Sema::TDK_TooManyArguments:
342 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000343 break;
344
345 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000346 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000347 Result.Data = Info.Param.getOpaqueValue();
348 break;
349
Douglas Gregora9333192010-05-08 17:41:32 +0000350 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000351 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000352 // FIXME: Should allocate from normal heap so that we can free this later.
353 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000354 Saved->Param = Info.Param;
355 Saved->FirstArg = Info.FirstArg;
356 Saved->SecondArg = Info.SecondArg;
357 Result.Data = Saved;
358 break;
359 }
360
361 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000362 Result.Data = Info.take();
363 break;
364
Douglas Gregora9333192010-05-08 17:41:32 +0000365 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000366 case Sema::TDK_FailedOverloadResolution:
367 break;
368 }
369
370 return Result;
371}
John McCall1d318332010-01-12 00:44:57 +0000372
Douglas Gregora9333192010-05-08 17:41:32 +0000373void OverloadCandidate::DeductionFailureInfo::Destroy() {
374 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
375 case Sema::TDK_Success:
376 case Sema::TDK_InstantiationDepth:
377 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000378 case Sema::TDK_TooManyArguments:
379 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000380 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000381 break;
382
Douglas Gregora9333192010-05-08 17:41:32 +0000383 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000384 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000385 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000386 Data = 0;
387 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000388
389 case Sema::TDK_SubstitutionFailure:
390 // FIXME: Destroy the template arugment list?
391 Data = 0;
392 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000393
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000394 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000395 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000396 case Sema::TDK_FailedOverloadResolution:
397 break;
398 }
399}
400
401TemplateParameter
402OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
403 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
404 case Sema::TDK_Success:
405 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000406 case Sema::TDK_TooManyArguments:
407 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000408 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000409 return TemplateParameter();
410
411 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000412 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000413 return TemplateParameter::getFromOpaqueValue(Data);
414
415 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000416 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000417 return static_cast<DFIParamWithArguments*>(Data)->Param;
418
419 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000420 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000421 case Sema::TDK_FailedOverloadResolution:
422 break;
423 }
424
425 return TemplateParameter();
426}
Douglas Gregorec20f462010-05-08 20:07:26 +0000427
428TemplateArgumentList *
429OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
430 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
431 case Sema::TDK_Success:
432 case Sema::TDK_InstantiationDepth:
433 case Sema::TDK_TooManyArguments:
434 case Sema::TDK_TooFewArguments:
435 case Sema::TDK_Incomplete:
436 case Sema::TDK_InvalidExplicitArguments:
437 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000438 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000439 return 0;
440
441 case Sema::TDK_SubstitutionFailure:
442 return static_cast<TemplateArgumentList*>(Data);
443
444 // Unhandled
445 case Sema::TDK_NonDeducedMismatch:
446 case Sema::TDK_FailedOverloadResolution:
447 break;
448 }
449
450 return 0;
451}
452
Douglas Gregora9333192010-05-08 17:41:32 +0000453const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
454 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
455 case Sema::TDK_Success:
456 case Sema::TDK_InstantiationDepth:
457 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000458 case Sema::TDK_TooManyArguments:
459 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000460 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000461 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000462 return 0;
463
Douglas Gregora9333192010-05-08 17:41:32 +0000464 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000465 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000466 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
467
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000468 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000469 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000470 case Sema::TDK_FailedOverloadResolution:
471 break;
472 }
473
474 return 0;
475}
476
477const TemplateArgument *
478OverloadCandidate::DeductionFailureInfo::getSecondArg() {
479 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
480 case Sema::TDK_Success:
481 case Sema::TDK_InstantiationDepth:
482 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000483 case Sema::TDK_TooManyArguments:
484 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000485 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000486 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000487 return 0;
488
Douglas Gregora9333192010-05-08 17:41:32 +0000489 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000490 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000491 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
492
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000493 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000494 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000495 case Sema::TDK_FailedOverloadResolution:
496 break;
497 }
498
499 return 0;
500}
501
502void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000503 inherited::clear();
504 Functions.clear();
505}
506
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000507// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000508// overload of the declarations in Old. This routine returns false if
509// New and Old cannot be overloaded, e.g., if New has the same
510// signature as some function in Old (C++ 1.3.10) or if the Old
511// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000512// it does return false, MatchedDecl will point to the decl that New
513// cannot be overloaded with. This decl may be a UsingShadowDecl on
514// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000515//
516// Example: Given the following input:
517//
518// void f(int, float); // #1
519// void f(int, int); // #2
520// int f(int, int); // #3
521//
522// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000523// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000524//
John McCall51fa86f2009-12-02 08:47:38 +0000525// When we process #2, Old contains only the FunctionDecl for #1. By
526// comparing the parameter types, we see that #1 and #2 are overloaded
527// (since they have different signatures), so this routine returns
528// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000529//
John McCall51fa86f2009-12-02 08:47:38 +0000530// When we process #3, Old is an overload set containing #1 and #2. We
531// compare the signatures of #3 to #1 (they're overloaded, so we do
532// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
533// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000534// signature), IsOverload returns false and MatchedDecl will be set to
535// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000536//
537// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
538// into a class by a using declaration. The rules for whether to hide
539// shadow declarations ignore some properties which otherwise figure
540// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000541Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000542Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
543 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000544 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000545 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000546 NamedDecl *OldD = *I;
547
548 bool OldIsUsingDecl = false;
549 if (isa<UsingShadowDecl>(OldD)) {
550 OldIsUsingDecl = true;
551
552 // We can always introduce two using declarations into the same
553 // context, even if they have identical signatures.
554 if (NewIsUsingDecl) continue;
555
556 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
557 }
558
559 // If either declaration was introduced by a using declaration,
560 // we'll need to use slightly different rules for matching.
561 // Essentially, these rules are the normal rules, except that
562 // function templates hide function templates with different
563 // return types or template parameter lists.
564 bool UseMemberUsingDeclRules =
565 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
566
John McCall51fa86f2009-12-02 08:47:38 +0000567 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000568 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
569 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
570 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
571 continue;
572 }
573
John McCall871b2e72009-12-09 03:35:25 +0000574 Match = *I;
575 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000576 }
John McCall51fa86f2009-12-02 08:47:38 +0000577 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000578 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
579 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
580 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
581 continue;
582 }
583
John McCall871b2e72009-12-09 03:35:25 +0000584 Match = *I;
585 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000586 }
John McCalld7945c62010-11-10 03:01:53 +0000587 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000588 // We can overload with these, which can show up when doing
589 // redeclaration checks for UsingDecls.
590 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000591 } else if (isa<TagDecl>(OldD)) {
592 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000593 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
594 // Optimistically assume that an unresolved using decl will
595 // overload; if it doesn't, we'll have to diagnose during
596 // template instantiation.
597 } else {
John McCall68263142009-11-18 22:49:29 +0000598 // (C++ 13p1):
599 // Only function declarations can be overloaded; object and type
600 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000601 Match = *I;
602 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000603 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000604 }
John McCall68263142009-11-18 22:49:29 +0000605
John McCall871b2e72009-12-09 03:35:25 +0000606 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000607}
608
John McCallad00b772010-06-16 08:42:20 +0000609bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
610 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000611 // If both of the functions are extern "C", then they are not
612 // overloads.
613 if (Old->isExternC() && New->isExternC())
614 return false;
615
John McCall68263142009-11-18 22:49:29 +0000616 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
617 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
618
619 // C++ [temp.fct]p2:
620 // A function template can be overloaded with other function templates
621 // and with normal (non-template) functions.
622 if ((OldTemplate == 0) != (NewTemplate == 0))
623 return true;
624
625 // Is the function New an overload of the function Old?
626 QualType OldQType = Context.getCanonicalType(Old->getType());
627 QualType NewQType = Context.getCanonicalType(New->getType());
628
629 // Compare the signatures (C++ 1.3.10) of the two functions to
630 // determine whether they are overloads. If we find any mismatch
631 // in the signature, they are overloads.
632
633 // If either of these functions is a K&R-style function (no
634 // prototype), then we consider them to have matching signatures.
635 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
636 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
637 return false;
638
639 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
640 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
641
642 // The signature of a function includes the types of its
643 // parameters (C++ 1.3.10), which includes the presence or absence
644 // of the ellipsis; see C++ DR 357).
645 if (OldQType != NewQType &&
646 (OldType->getNumArgs() != NewType->getNumArgs() ||
647 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000648 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000649 return true;
650
651 // C++ [temp.over.link]p4:
652 // The signature of a function template consists of its function
653 // signature, its return type and its template parameter list. The names
654 // of the template parameters are significant only for establishing the
655 // relationship between the template parameters and the rest of the
656 // signature.
657 //
658 // We check the return type and template parameter lists for function
659 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000660 //
661 // However, we don't consider either of these when deciding whether
662 // a member introduced by a shadow declaration is hidden.
663 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000664 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
665 OldTemplate->getTemplateParameters(),
666 false, TPL_TemplateMatch) ||
667 OldType->getResultType() != NewType->getResultType()))
668 return true;
669
670 // If the function is a class member, its signature includes the
671 // cv-qualifiers (if any) on the function itself.
672 //
673 // As part of this, also check whether one of the member functions
674 // is static, in which case they are not overloads (C++
675 // 13.1p2). While not part of the definition of the signature,
676 // this check is important to determine whether these functions
677 // can be overloaded.
678 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
679 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
680 if (OldMethod && NewMethod &&
681 !OldMethod->isStatic() && !NewMethod->isStatic() &&
682 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
683 return true;
684
685 // The signatures match; this is not an overload.
686 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000687}
688
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000689/// TryImplicitConversion - Attempt to perform an implicit conversion
690/// from the given expression (Expr) to the given type (ToType). This
691/// function returns an implicit conversion sequence that can be used
692/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000693///
694/// void f(float f);
695/// void g(int i) { f(i); }
696///
697/// this routine would produce an implicit conversion sequence to
698/// describe the initialization of f from i, which will be a standard
699/// conversion sequence containing an lvalue-to-rvalue conversion (C++
700/// 4.1) followed by a floating-integral conversion (C++ 4.9).
701//
702/// Note that this routine only determines how the conversion can be
703/// performed; it does not actually perform the conversion. As such,
704/// it will not produce any diagnostics if no conversion is available,
705/// but will instead return an implicit conversion sequence of kind
706/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000707///
708/// If @p SuppressUserConversions, then user-defined conversions are
709/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000710/// If @p AllowExplicit, then explicit user-defined conversions are
711/// permitted.
John McCall120d63c2010-08-24 20:38:10 +0000712static ImplicitConversionSequence
713TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
714 bool SuppressUserConversions,
715 bool AllowExplicit,
716 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000717 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +0000718 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
719 ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000720 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000721 return ICS;
722 }
723
John McCall120d63c2010-08-24 20:38:10 +0000724 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000725 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000726 return ICS;
727 }
728
Douglas Gregor604eb652010-08-11 02:15:33 +0000729 // C++ [over.ics.user]p4:
730 // A conversion of an expression of class type to the same class
731 // type is given Exact Match rank, and a conversion of an
732 // expression of class type to a base class of that type is
733 // given Conversion rank, in spite of the fact that a copy/move
734 // constructor (i.e., a user-defined conversion function) is
735 // called for those cases.
736 QualType FromType = From->getType();
737 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +0000738 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
739 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000740 ICS.setStandard();
741 ICS.Standard.setAsIdentityConversion();
742 ICS.Standard.setFromType(FromType);
743 ICS.Standard.setAllToTypes(ToType);
744
745 // We don't actually check at this point whether there is a valid
746 // copy/move constructor, since overloading just assumes that it
747 // exists. When we actually perform initialization, we'll find the
748 // appropriate constructor to copy the returned object, if needed.
749 ICS.Standard.CopyConstructor = 0;
Douglas Gregor604eb652010-08-11 02:15:33 +0000750
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000751 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +0000752 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000753 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor604eb652010-08-11 02:15:33 +0000754
755 return ICS;
756 }
757
758 if (SuppressUserConversions) {
759 // We're not in the case above, so there is no conversion that
760 // we can perform.
761 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000762 return ICS;
763 }
764
765 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000766 OverloadCandidateSet Conversions(From->getExprLoc());
767 OverloadingResult UserDefResult
John McCall120d63c2010-08-24 20:38:10 +0000768 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000769 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000770
771 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000772 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000773 // C++ [over.ics.user]p4:
774 // A conversion of an expression of class type to the same class
775 // type is given Exact Match rank, and a conversion of an
776 // expression of class type to a base class of that type is
777 // given Conversion rank, in spite of the fact that a copy
778 // constructor (i.e., a user-defined conversion function) is
779 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000780 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000781 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000782 QualType FromCanon
John McCall120d63c2010-08-24 20:38:10 +0000783 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
784 QualType ToCanon
785 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000786 if (Constructor->isCopyConstructor() &&
John McCall120d63c2010-08-24 20:38:10 +0000787 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000788 // Turn this into a "standard" conversion sequence, so that it
789 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000790 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000791 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000792 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000793 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000794 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000795 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000796 ICS.Standard.Second = ICK_Derived_To_Base;
797 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000798 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000799
800 // C++ [over.best.ics]p4:
801 // However, when considering the argument of a user-defined
802 // conversion function that is a candidate by 13.3.1.3 when
803 // invoked for the copying of the temporary in the second step
804 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
805 // 13.3.1.6 in all cases, only standard conversion sequences and
806 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000807 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000808 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000809 }
John McCallcefd3ad2010-01-13 22:30:33 +0000810 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000811 ICS.setAmbiguous();
812 ICS.Ambiguous.setFromType(From->getType());
813 ICS.Ambiguous.setToType(ToType);
814 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
815 Cand != Conversions.end(); ++Cand)
816 if (Cand->Viable)
817 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000818 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000819 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000820 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000821
822 return ICS;
823}
824
John McCall120d63c2010-08-24 20:38:10 +0000825bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
826 const InitializedEntity &Entity,
827 Expr *Initializer,
828 bool SuppressUserConversions,
829 bool AllowExplicitConversions,
830 bool InOverloadResolution) {
831 ImplicitConversionSequence ICS
832 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
833 SuppressUserConversions,
834 AllowExplicitConversions,
835 InOverloadResolution);
836 if (ICS.isBad()) return true;
837
838 // Perform the actual conversion.
839 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
840 return false;
841}
842
Douglas Gregor575c63a2010-04-16 22:27:05 +0000843/// PerformImplicitConversion - Perform an implicit conversion of the
844/// expression From to the type ToType. Returns true if there was an
845/// error, false otherwise. The expression From is replaced with the
846/// converted expression. Flavor is the kind of conversion we're
847/// performing, used in the error message. If @p AllowExplicit,
848/// explicit user-defined conversions are permitted.
849bool
850Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
851 AssignmentAction Action, bool AllowExplicit) {
852 ImplicitConversionSequence ICS;
853 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
854}
855
856bool
857Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
858 AssignmentAction Action, bool AllowExplicit,
859 ImplicitConversionSequence& ICS) {
John McCall120d63c2010-08-24 20:38:10 +0000860 ICS = clang::TryImplicitConversion(*this, From, ToType,
861 /*SuppressUserConversions=*/false,
862 AllowExplicit,
863 /*InOverloadResolution=*/false);
Douglas Gregor575c63a2010-04-16 22:27:05 +0000864 return PerformImplicitConversion(From, ToType, ICS, Action);
865}
866
Douglas Gregor43c79c22009-12-09 00:47:37 +0000867/// \brief Determine whether the conversion from FromType to ToType is a valid
868/// conversion that strips "noreturn" off the nested function type.
869static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
870 QualType ToType, QualType &ResultTy) {
871 if (Context.hasSameUnqualifiedType(FromType, ToType))
872 return false;
873
874 // Strip the noreturn off the type we're converting from; noreturn can
875 // safely be removed.
876 FromType = Context.getNoReturnType(FromType, false);
877 if (!Context.hasSameUnqualifiedType(FromType, ToType))
878 return false;
879
880 ResultTy = FromType;
881 return true;
882}
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000883
884/// \brief Determine whether the conversion from FromType to ToType is a valid
885/// vector conversion.
886///
887/// \param ICK Will be set to the vector conversion kind, if this is a vector
888/// conversion.
889static bool IsVectorConversion(ASTContext &Context, QualType FromType,
890 QualType ToType, ImplicitConversionKind &ICK) {
891 // We need at least one of these types to be a vector type to have a vector
892 // conversion.
893 if (!ToType->isVectorType() && !FromType->isVectorType())
894 return false;
895
896 // Identical types require no conversions.
897 if (Context.hasSameUnqualifiedType(FromType, ToType))
898 return false;
899
900 // There are no conversions between extended vector types, only identity.
901 if (ToType->isExtVectorType()) {
902 // There are no conversions between extended vector types other than the
903 // identity conversion.
904 if (FromType->isExtVectorType())
905 return false;
906
907 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +0000908 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000909 ICK = ICK_Vector_Splat;
910 return true;
911 }
912 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000913
914 // We can perform the conversion between vector types in the following cases:
915 // 1)vector types are equivalent AltiVec and GCC vector types
916 // 2)lax vector conversions are permitted and the vector types are of the
917 // same size
918 if (ToType->isVectorType() && FromType->isVectorType()) {
919 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +0000920 (Context.getLangOptions().LaxVectorConversions &&
921 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +0000922 ICK = ICK_Vector_Conversion;
923 return true;
924 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000925 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000926
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000927 return false;
928}
Douglas Gregor43c79c22009-12-09 00:47:37 +0000929
Douglas Gregor60d62c22008-10-31 16:23:19 +0000930/// IsStandardConversion - Determines whether there is a standard
931/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
932/// expression From to the type ToType. Standard conversion sequences
933/// only consider non-class types; for conversions that involve class
934/// types, use TryImplicitConversion. If a conversion exists, SCS will
935/// contain the standard conversion sequence required to perform this
936/// conversion and this routine will return true. Otherwise, this
937/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +0000938static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
939 bool InOverloadResolution,
940 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000941 QualType FromType = From->getType();
John McCall120d63c2010-08-24 20:38:10 +0000942
Douglas Gregor60d62c22008-10-31 16:23:19 +0000943 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000944 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000945 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000946 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000947 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000948 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000949
Douglas Gregorf9201e02009-02-11 23:02:49 +0000950 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000951 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000952 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +0000953 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000954 return false;
955
Mike Stump1eb44332009-09-09 15:08:12 +0000956 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000957 }
958
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000959 // The first conversion can be an lvalue-to-rvalue conversion,
960 // array-to-pointer conversion, or function-to-pointer conversion
961 // (C++ 4p1).
962
John McCall120d63c2010-08-24 20:38:10 +0000963 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000964 DeclAccessPair AccessPair;
965 if (FunctionDecl *Fn
John McCall120d63c2010-08-24 20:38:10 +0000966 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
967 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000968 // We were able to resolve the address of the overloaded function,
969 // so we can convert to the type of that function.
970 FromType = Fn->getType();
971 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
972 if (!Method->isStatic()) {
973 Type *ClassType
John McCall120d63c2010-08-24 20:38:10 +0000974 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
975 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000976 }
977 }
978
979 // If the "from" expression takes the address of the overloaded
980 // function, update the type of the resulting expression accordingly.
981 if (FromType->getAs<FunctionType>())
982 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCall2de56d12010-08-25 11:45:40 +0000983 if (UnOp->getOpcode() == UO_AddrOf)
John McCall120d63c2010-08-24 20:38:10 +0000984 FromType = S.Context.getPointerType(FromType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000985
986 // Check that we've computed the proper type after overload resolution.
John McCall120d63c2010-08-24 20:38:10 +0000987 assert(S.Context.hasSameType(FromType,
988 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000989 } else {
990 return false;
991 }
Anders Carlsson2bd62502010-11-04 05:28:09 +0000992 }
Mike Stump1eb44332009-09-09 15:08:12 +0000993 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000994 // An lvalue (3.10) of a non-function, non-array type T can be
995 // converted to an rvalue.
John McCall120d63c2010-08-24 20:38:10 +0000996 Expr::isLvalueResult argIsLvalue = From->isLvalue(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000997 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000998 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +0000999 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001000 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001001
1002 // If T is a non-class type, the type of the rvalue is the
1003 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001004 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1005 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001006 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001007 } else if (FromType->isArrayType()) {
1008 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001009 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001010
1011 // An lvalue or rvalue of type "array of N T" or "array of unknown
1012 // bound of T" can be converted to an rvalue of type "pointer to
1013 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001014 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001015
John McCall120d63c2010-08-24 20:38:10 +00001016 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001017 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001018 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001019
1020 // For the purpose of ranking in overload resolution
1021 // (13.3.3.1.1), this conversion is considered an
1022 // array-to-pointer conversion followed by a qualification
1023 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001024 SCS.Second = ICK_Identity;
1025 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +00001026 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001027 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001028 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001029 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
1030 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001031 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001032
1033 // An lvalue of function type T can be converted to an rvalue of
1034 // type "pointer to T." The result is a pointer to the
1035 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001036 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001037 } else {
1038 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001039 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001040 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001041 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001042
1043 // The second conversion can be an integral promotion, floating
1044 // point promotion, integral conversion, floating point conversion,
1045 // floating-integral conversion, pointer conversion,
1046 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001047 // For overloading in C, this can also be a "compatible-type"
1048 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001049 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001050 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001051 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001052 // The unqualified versions of the types are the same: there's no
1053 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001054 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001055 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001056 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001057 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001058 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001059 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001060 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001061 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001062 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001063 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001064 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001065 SCS.Second = ICK_Complex_Promotion;
1066 FromType = ToType.getUnqualifiedType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001067 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001068 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001069 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001070 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001071 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001072 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1073 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001074 SCS.Second = ICK_Complex_Conversion;
1075 FromType = ToType.getUnqualifiedType();
Chandler Carruth23a370f2010-02-25 07:20:54 +00001076 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1077 (ToType->isComplexType() && FromType->isArithmeticType())) {
1078 // Complex-real conversions (C99 6.3.1.7)
1079 SCS.Second = ICK_Complex_Real;
1080 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001081 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001082 // Floating point conversions (C++ 4.8).
1083 SCS.Second = ICK_Floating_Conversion;
1084 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001085 } else if ((FromType->isRealFloatingType() &&
John McCall120d63c2010-08-24 20:38:10 +00001086 ToType->isIntegralType(S.Context) && !ToType->isBooleanType()) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001087 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001088 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001089 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001090 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001091 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001092 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1093 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001094 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001095 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001096 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall120d63c2010-08-24 20:38:10 +00001097 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1098 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001099 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001100 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001101 } else if (ToType->isBooleanType() &&
1102 (FromType->isArithmeticType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +00001103 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001104 FromType->isBlockPointerType() ||
1105 FromType->isMemberPointerType() ||
Douglas Gregor00619622010-06-22 23:41:02 +00001106 FromType->isNullPtrType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001107 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001108 SCS.Second = ICK_Boolean_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001109 FromType = S.Context.BoolTy;
1110 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001111 SCS.Second = SecondICK;
1112 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001113 } else if (!S.getLangOptions().CPlusPlus &&
1114 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001115 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001116 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001117 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001118 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001119 // Treat a conversion that strips "noreturn" as an identity conversion.
1120 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001121 } else {
1122 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001123 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001124 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001125 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001126
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001127 QualType CanonFrom;
1128 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001129 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall120d63c2010-08-24 20:38:10 +00001130 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001131 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001132 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001133 CanonFrom = S.Context.getCanonicalType(FromType);
1134 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001135 } else {
1136 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001137 SCS.Third = ICK_Identity;
1138
Mike Stump1eb44332009-09-09 15:08:12 +00001139 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001140 // [...] Any difference in top-level cv-qualification is
1141 // subsumed by the initialization itself and does not constitute
1142 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001143 CanonFrom = S.Context.getCanonicalType(FromType);
1144 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001145 if (CanonFrom.getLocalUnqualifiedType()
1146 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001147 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1148 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001149 FromType = ToType;
1150 CanonFrom = CanonTo;
1151 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001152 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001153 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001154
1155 // If we have not converted the argument type to the parameter type,
1156 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001157 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001158 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001159
Douglas Gregor60d62c22008-10-31 16:23:19 +00001160 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001161}
1162
1163/// IsIntegralPromotion - Determines whether the conversion from the
1164/// expression From (whose potentially-adjusted type is FromType) to
1165/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1166/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001167bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001168 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001169 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001170 if (!To) {
1171 return false;
1172 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001173
1174 // An rvalue of type char, signed char, unsigned char, short int, or
1175 // unsigned short int can be converted to an rvalue of type int if
1176 // int can represent all the values of the source type; otherwise,
1177 // the source rvalue can be converted to an rvalue of type unsigned
1178 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001179 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1180 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001181 if (// We can promote any signed, promotable integer type to an int
1182 (FromType->isSignedIntegerType() ||
1183 // We can promote any unsigned integer type whose size is
1184 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001185 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001186 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001187 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001188 }
1189
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001190 return To->getKind() == BuiltinType::UInt;
1191 }
1192
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001193 // C++0x [conv.prom]p3:
1194 // A prvalue of an unscoped enumeration type whose underlying type is not
1195 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1196 // following types that can represent all the values of the enumeration
1197 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1198 // unsigned int, long int, unsigned long int, long long int, or unsigned
1199 // long long int. If none of the types in that list can represent all the
1200 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1201 // type can be converted to an rvalue a prvalue of the extended integer type
1202 // with lowest integer conversion rank (4.13) greater than the rank of long
1203 // long in which all the values of the enumeration can be represented. If
1204 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001205 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1206 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1207 // provided for a scoped enumeration.
1208 if (FromEnumType->getDecl()->isScoped())
1209 return false;
1210
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001211 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregor5dde1602010-09-12 03:38:25 +00001212 if (ToType->isIntegerType() &&
1213 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001214 return Context.hasSameUnqualifiedType(ToType,
1215 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001216 }
John McCall842aef82009-12-09 09:09:27 +00001217
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001218 // C++0x [conv.prom]p2:
1219 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1220 // to an rvalue a prvalue of the first of the following types that can
1221 // represent all the values of its underlying type: int, unsigned int,
1222 // long int, unsigned long int, long long int, or unsigned long long int.
1223 // If none of the types in that list can represent all the values of its
1224 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1225 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1226 // type.
1227 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1228 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001229 // Determine whether the type we're converting from is signed or
1230 // unsigned.
1231 bool FromIsSigned;
1232 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +00001233
1234 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1235 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001236
1237 // The types we'll try to promote to, in the appropriate
1238 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001239 QualType PromoteTypes[6] = {
1240 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001241 Context.LongTy, Context.UnsignedLongTy ,
1242 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001243 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001244 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001245 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1246 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001247 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001248 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1249 // We found the type that we can promote to. If this is the
1250 // type we wanted, we have a promotion. Otherwise, no
1251 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001252 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001253 }
1254 }
1255 }
1256
1257 // An rvalue for an integral bit-field (9.6) can be converted to an
1258 // rvalue of type int if int can represent all the values of the
1259 // bit-field; otherwise, it can be converted to unsigned int if
1260 // unsigned int can represent all the values of the bit-field. If
1261 // the bit-field is larger yet, no integral promotion applies to
1262 // it. If the bit-field has an enumerated type, it is treated as any
1263 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001264 // FIXME: We should delay checking of bit-fields until we actually perform the
1265 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001266 using llvm::APSInt;
1267 if (From)
1268 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001269 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001270 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001271 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1272 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1273 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Douglas Gregor86f19402008-12-20 23:49:58 +00001275 // Are we promoting to an int from a bitfield that fits in an int?
1276 if (BitWidth < ToSize ||
1277 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1278 return To->getKind() == BuiltinType::Int;
1279 }
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Douglas Gregor86f19402008-12-20 23:49:58 +00001281 // Are we promoting to an unsigned int from an unsigned bitfield
1282 // that fits into an unsigned int?
1283 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1284 return To->getKind() == BuiltinType::UInt;
1285 }
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Douglas Gregor86f19402008-12-20 23:49:58 +00001287 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001288 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001289 }
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001291 // An rvalue of type bool can be converted to an rvalue of type int,
1292 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001293 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001294 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001295 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001296
1297 return false;
1298}
1299
1300/// IsFloatingPointPromotion - Determines whether the conversion from
1301/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1302/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001303bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001304 /// An rvalue of type float can be converted to an rvalue of type
1305 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001306 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1307 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001308 if (FromBuiltin->getKind() == BuiltinType::Float &&
1309 ToBuiltin->getKind() == BuiltinType::Double)
1310 return true;
1311
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001312 // C99 6.3.1.5p1:
1313 // When a float is promoted to double or long double, or a
1314 // double is promoted to long double [...].
1315 if (!getLangOptions().CPlusPlus &&
1316 (FromBuiltin->getKind() == BuiltinType::Float ||
1317 FromBuiltin->getKind() == BuiltinType::Double) &&
1318 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1319 return true;
1320 }
1321
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001322 return false;
1323}
1324
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001325/// \brief Determine if a conversion is a complex promotion.
1326///
1327/// A complex promotion is defined as a complex -> complex conversion
1328/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001329/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001330bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001331 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001332 if (!FromComplex)
1333 return false;
1334
John McCall183700f2009-09-21 23:43:11 +00001335 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001336 if (!ToComplex)
1337 return false;
1338
1339 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001340 ToComplex->getElementType()) ||
1341 IsIntegralPromotion(0, FromComplex->getElementType(),
1342 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001343}
1344
Douglas Gregorcb7de522008-11-26 23:31:11 +00001345/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1346/// the pointer type FromPtr to a pointer to type ToPointee, with the
1347/// same type qualifiers as FromPtr has on its pointee type. ToType,
1348/// if non-empty, will be a pointer to ToType that may or may not have
1349/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001350static QualType
1351BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001352 QualType ToPointee, QualType ToType,
1353 ASTContext &Context) {
1354 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1355 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001356 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001357
1358 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001359 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001360 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001361 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001362 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001363
1364 // Build a pointer to ToPointee. It has the right qualifiers
1365 // already.
1366 return Context.getPointerType(ToPointee);
1367 }
1368
1369 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +00001370 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +00001371 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1372 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +00001373}
1374
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001375/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1376/// the FromType, which is an objective-c pointer, to ToType, which may or may
1377/// not have the right set of qualifiers.
1378static QualType
1379BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1380 QualType ToType,
1381 ASTContext &Context) {
1382 QualType CanonFromType = Context.getCanonicalType(FromType);
1383 QualType CanonToType = Context.getCanonicalType(ToType);
1384 Qualifiers Quals = CanonFromType.getQualifiers();
1385
1386 // Exact qualifier match -> return the pointer type we're converting to.
1387 if (CanonToType.getLocalQualifiers() == Quals)
1388 return ToType;
1389
1390 // Just build a canonical type that has the right qualifiers.
1391 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1392}
1393
Mike Stump1eb44332009-09-09 15:08:12 +00001394static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001395 bool InOverloadResolution,
1396 ASTContext &Context) {
1397 // Handle value-dependent integral null pointer constants correctly.
1398 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1399 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001400 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001401 return !InOverloadResolution;
1402
Douglas Gregorce940492009-09-25 04:25:58 +00001403 return Expr->isNullPointerConstant(Context,
1404 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1405 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001406}
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001408/// IsPointerConversion - Determines whether the conversion of the
1409/// expression From, which has the (possibly adjusted) type FromType,
1410/// can be converted to the type ToType via a pointer conversion (C++
1411/// 4.10). If so, returns true and places the converted type (that
1412/// might differ from ToType in its cv-qualifiers at some level) into
1413/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001414///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001415/// This routine also supports conversions to and from block pointers
1416/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1417/// pointers to interfaces. FIXME: Once we've determined the
1418/// appropriate overloading rules for Objective-C, we may want to
1419/// split the Objective-C checks into a different routine; however,
1420/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001421/// conversions, so for now they live here. IncompatibleObjC will be
1422/// set if the conversion is an allowed Objective-C conversion that
1423/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001424bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001425 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001426 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001427 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001428 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001429 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1430 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001431
Mike Stump1eb44332009-09-09 15:08:12 +00001432 // Conversion from a null pointer constant to any Objective-C pointer type.
1433 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001434 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001435 ConvertedType = ToType;
1436 return true;
1437 }
1438
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001439 // Blocks: Block pointers can be converted to void*.
1440 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001441 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001442 ConvertedType = ToType;
1443 return true;
1444 }
1445 // Blocks: A null pointer constant can be converted to a block
1446 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001447 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001448 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001449 ConvertedType = ToType;
1450 return true;
1451 }
1452
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001453 // If the left-hand-side is nullptr_t, the right side can be a null
1454 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001455 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001456 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001457 ConvertedType = ToType;
1458 return true;
1459 }
1460
Ted Kremenek6217b802009-07-29 21:53:49 +00001461 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001462 if (!ToTypePtr)
1463 return false;
1464
1465 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001466 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001467 ConvertedType = ToType;
1468 return true;
1469 }
Sebastian Redl07779722008-10-31 14:43:28 +00001470
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001471 // Beyond this point, both types need to be pointers
1472 // , including objective-c pointers.
1473 QualType ToPointeeType = ToTypePtr->getPointeeType();
1474 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1475 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1476 ToType, Context);
1477 return true;
1478
1479 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001480 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001481 if (!FromTypePtr)
1482 return false;
1483
1484 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001485
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001486 // If the unqualified pointee types are the same, this can't be a
1487 // pointer conversion, so don't do all of the work below.
1488 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1489 return false;
1490
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001491 // An rvalue of type "pointer to cv T," where T is an object type,
1492 // can be converted to an rvalue of type "pointer to cv void" (C++
1493 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001494 if (FromPointeeType->isIncompleteOrObjectType() &&
1495 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001496 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001497 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001498 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001499 return true;
1500 }
1501
Douglas Gregorf9201e02009-02-11 23:02:49 +00001502 // When we're overloading in C, we allow a special kind of pointer
1503 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001504 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001505 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001506 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001507 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001508 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001509 return true;
1510 }
1511
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001512 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001513 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001514 // An rvalue of type "pointer to cv D," where D is a class type,
1515 // can be converted to an rvalue of type "pointer to cv B," where
1516 // B is a base class (clause 10) of D. If B is an inaccessible
1517 // (clause 11) or ambiguous (10.2) base class of D, a program that
1518 // necessitates this conversion is ill-formed. The result of the
1519 // conversion is a pointer to the base class sub-object of the
1520 // derived class object. The null pointer value is converted to
1521 // the null pointer value of the destination type.
1522 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001523 // Note that we do not check for ambiguity or inaccessibility
1524 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001525 if (getLangOptions().CPlusPlus &&
1526 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001527 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001528 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001529 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001530 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001531 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001532 ToType, Context);
1533 return true;
1534 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001535
Douglas Gregorc7887512008-12-19 19:13:09 +00001536 return false;
1537}
1538
1539/// isObjCPointerConversion - Determines whether this is an
1540/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1541/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001542bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001543 QualType& ConvertedType,
1544 bool &IncompatibleObjC) {
1545 if (!getLangOptions().ObjC1)
1546 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001547
Steve Naroff14108da2009-07-10 23:34:53 +00001548 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001549 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001550 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001551 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001552
Steve Naroff14108da2009-07-10 23:34:53 +00001553 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001554 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001555 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001556 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001557 ConvertedType = ToType;
1558 return true;
1559 }
1560 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001561 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001562 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001563 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001564 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001565 ConvertedType = ToType;
1566 return true;
1567 }
1568 // Objective C++: We're able to convert from a pointer to an
1569 // interface to a pointer to a different interface.
1570 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001571 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1572 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1573 if (getLangOptions().CPlusPlus && LHS && RHS &&
1574 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1575 FromObjCPtr->getPointeeType()))
1576 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00001577 ConvertedType = ToType;
1578 return true;
1579 }
1580
1581 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1582 // Okay: this is some kind of implicit downcast of Objective-C
1583 // interfaces, which is permitted. However, we're going to
1584 // complain about it.
1585 IncompatibleObjC = true;
1586 ConvertedType = FromType;
1587 return true;
1588 }
Mike Stump1eb44332009-09-09 15:08:12 +00001589 }
Steve Naroff14108da2009-07-10 23:34:53 +00001590 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001591 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001592 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001593 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001594 else if (const BlockPointerType *ToBlockPtr =
1595 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001596 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001597 // to a block pointer type.
1598 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1599 ConvertedType = ToType;
1600 return true;
1601 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001602 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001603 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001604 else if (FromType->getAs<BlockPointerType>() &&
1605 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1606 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001607 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001608 ConvertedType = ToType;
1609 return true;
1610 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001611 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001612 return false;
1613
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001614 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001615 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001616 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001617 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001618 FromPointeeType = FromBlockPtr->getPointeeType();
1619 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001620 return false;
1621
Douglas Gregorc7887512008-12-19 19:13:09 +00001622 // If we have pointers to pointers, recursively check whether this
1623 // is an Objective-C conversion.
1624 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1625 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1626 IncompatibleObjC)) {
1627 // We always complain about this conversion.
1628 IncompatibleObjC = true;
1629 ConvertedType = ToType;
1630 return true;
1631 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001632 // Allow conversion of pointee being objective-c pointer to another one;
1633 // as in I* to id.
1634 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1635 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1636 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1637 IncompatibleObjC)) {
1638 ConvertedType = ToType;
1639 return true;
1640 }
1641
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001642 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001643 // differences in the argument and result types are in Objective-C
1644 // pointer conversions. If so, we permit the conversion (but
1645 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001646 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001647 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001648 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001649 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001650 if (FromFunctionType && ToFunctionType) {
1651 // If the function types are exactly the same, this isn't an
1652 // Objective-C pointer conversion.
1653 if (Context.getCanonicalType(FromPointeeType)
1654 == Context.getCanonicalType(ToPointeeType))
1655 return false;
1656
1657 // Perform the quick checks that will tell us whether these
1658 // function types are obviously different.
1659 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1660 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1661 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1662 return false;
1663
1664 bool HasObjCConversion = false;
1665 if (Context.getCanonicalType(FromFunctionType->getResultType())
1666 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1667 // Okay, the types match exactly. Nothing to do.
1668 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1669 ToFunctionType->getResultType(),
1670 ConvertedType, IncompatibleObjC)) {
1671 // Okay, we have an Objective-C pointer conversion.
1672 HasObjCConversion = true;
1673 } else {
1674 // Function types are too different. Abort.
1675 return false;
1676 }
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Douglas Gregorc7887512008-12-19 19:13:09 +00001678 // Check argument types.
1679 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1680 ArgIdx != NumArgs; ++ArgIdx) {
1681 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1682 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1683 if (Context.getCanonicalType(FromArgType)
1684 == Context.getCanonicalType(ToArgType)) {
1685 // Okay, the types match exactly. Nothing to do.
1686 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1687 ConvertedType, IncompatibleObjC)) {
1688 // Okay, we have an Objective-C pointer conversion.
1689 HasObjCConversion = true;
1690 } else {
1691 // Argument types are too different. Abort.
1692 return false;
1693 }
1694 }
1695
1696 if (HasObjCConversion) {
1697 // We had an Objective-C conversion. Allow this pointer
1698 // conversion, but complain about it.
1699 ConvertedType = ToType;
1700 IncompatibleObjC = true;
1701 return true;
1702 }
1703 }
1704
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001705 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001706}
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001707
1708/// FunctionArgTypesAreEqual - This routine checks two function proto types
1709/// for equlity of their argument types. Caller has already checked that
1710/// they have same number of arguments. This routine assumes that Objective-C
1711/// pointer types which only differ in their protocol qualifiers are equal.
1712bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1713 FunctionProtoType* NewType){
1714 if (!getLangOptions().ObjC1)
1715 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1716 NewType->arg_type_begin());
1717
1718 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1719 N = NewType->arg_type_begin(),
1720 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1721 QualType ToType = (*O);
1722 QualType FromType = (*N);
1723 if (ToType != FromType) {
1724 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1725 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001726 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1727 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1728 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1729 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001730 continue;
1731 }
John McCallc12c5bb2010-05-15 11:32:37 +00001732 else if (const ObjCObjectPointerType *PTTo =
1733 ToType->getAs<ObjCObjectPointerType>()) {
1734 if (const ObjCObjectPointerType *PTFr =
1735 FromType->getAs<ObjCObjectPointerType>())
1736 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1737 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001738 }
1739 return false;
1740 }
1741 }
1742 return true;
1743}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001744
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001745/// CheckPointerConversion - Check the pointer conversion from the
1746/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001747/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001748/// conversions for which IsPointerConversion has already returned
1749/// true. It returns true and produces a diagnostic if there was an
1750/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001751bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001752 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001753 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001754 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001755 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00001756 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001757
Douglas Gregord7a95972010-06-08 17:35:15 +00001758 if (CXXBoolLiteralExpr* LitBool
1759 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00001760 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregord7a95972010-06-08 17:35:15 +00001761 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1762 << ToType;
1763
Ted Kremenek6217b802009-07-29 21:53:49 +00001764 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1765 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001766 QualType FromPointeeType = FromPtrType->getPointeeType(),
1767 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001768
Douglas Gregor5fccd362010-03-03 23:55:11 +00001769 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1770 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001771 // We must have a derived-to-base conversion. Check an
1772 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001773 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1774 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001775 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001776 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001777 return true;
1778
1779 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00001780 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001781 }
1782 }
Mike Stump1eb44332009-09-09 15:08:12 +00001783 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001784 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001785 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001786 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001787 // Objective-C++ conversions are always okay.
1788 // FIXME: We should have a different class of conversions for the
1789 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001790 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001791 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001792
Steve Naroff14108da2009-07-10 23:34:53 +00001793 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001794 return false;
1795}
1796
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001797/// IsMemberPointerConversion - Determines whether the conversion of the
1798/// expression From, which has the (possibly adjusted) type FromType, can be
1799/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1800/// If so, returns true and places the converted type (that might differ from
1801/// ToType in its cv-qualifiers at some level) into ConvertedType.
1802bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001803 QualType ToType,
1804 bool InOverloadResolution,
1805 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001806 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001807 if (!ToTypePtr)
1808 return false;
1809
1810 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001811 if (From->isNullPointerConstant(Context,
1812 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1813 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001814 ConvertedType = ToType;
1815 return true;
1816 }
1817
1818 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001819 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001820 if (!FromTypePtr)
1821 return false;
1822
1823 // A pointer to member of B can be converted to a pointer to member of D,
1824 // where D is derived from B (C++ 4.11p2).
1825 QualType FromClass(FromTypePtr->getClass(), 0);
1826 QualType ToClass(ToTypePtr->getClass(), 0);
1827 // FIXME: What happens when these are dependent? Is this function even called?
1828
1829 if (IsDerivedFrom(ToClass, FromClass)) {
1830 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1831 ToClass.getTypePtr());
1832 return true;
1833 }
1834
1835 return false;
1836}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001837
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001838/// CheckMemberPointerConversion - Check the member pointer conversion from the
1839/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001840/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001841/// for which IsMemberPointerConversion has already returned true. It returns
1842/// true and produces a diagnostic if there was an error, or returns false
1843/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001844bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001845 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001846 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001847 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001848 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001849 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001850 if (!FromPtrType) {
1851 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001852 assert(From->isNullPointerConstant(Context,
1853 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001854 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00001855 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001856 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001857 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001858
Ted Kremenek6217b802009-07-29 21:53:49 +00001859 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001860 assert(ToPtrType && "No member pointer cast has a target type "
1861 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001862
Sebastian Redl21593ac2009-01-28 18:33:18 +00001863 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1864 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001865
Sebastian Redl21593ac2009-01-28 18:33:18 +00001866 // FIXME: What about dependent types?
1867 assert(FromClass->isRecordType() && "Pointer into non-class.");
1868 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001869
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001870 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001871 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001872 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1873 assert(DerivationOkay &&
1874 "Should not have been called if derivation isn't OK.");
1875 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001876
Sebastian Redl21593ac2009-01-28 18:33:18 +00001877 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1878 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001879 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1880 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1881 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1882 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001883 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001884
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001885 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001886 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1887 << FromClass << ToClass << QualType(VBase, 0)
1888 << From->getSourceRange();
1889 return true;
1890 }
1891
John McCall6b2accb2010-02-10 09:31:12 +00001892 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001893 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1894 Paths.front(),
1895 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001896
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001897 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001898 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001899 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001900 return false;
1901}
1902
Douglas Gregor98cd5992008-10-21 23:43:52 +00001903/// IsQualificationConversion - Determines whether the conversion from
1904/// an rvalue of type FromType to ToType is a qualification conversion
1905/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001906bool
1907Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001908 FromType = Context.getCanonicalType(FromType);
1909 ToType = Context.getCanonicalType(ToType);
1910
1911 // If FromType and ToType are the same type, this is not a
1912 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001913 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001914 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001915
Douglas Gregor98cd5992008-10-21 23:43:52 +00001916 // (C++ 4.4p4):
1917 // A conversion can add cv-qualifiers at levels other than the first
1918 // in multi-level pointers, subject to the following rules: [...]
1919 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001920 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001921 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001922 // Within each iteration of the loop, we check the qualifiers to
1923 // determine if this still looks like a qualification
1924 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001925 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001926 // until there are no more pointers or pointers-to-members left to
1927 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001928 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001929
1930 // -- for every j > 0, if const is in cv 1,j then const is in cv
1931 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001932 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001933 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Douglas Gregor98cd5992008-10-21 23:43:52 +00001935 // -- if the cv 1,j and cv 2,j are different, then const is in
1936 // every cv for 0 < k < j.
1937 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001938 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001939 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Douglas Gregor98cd5992008-10-21 23:43:52 +00001941 // Keep track of whether all prior cv-qualifiers in the "to" type
1942 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001943 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001944 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001945 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001946
1947 // We are left with FromType and ToType being the pointee types
1948 // after unwrapping the original FromType and ToType the same number
1949 // of types. If we unwrapped any pointers, and if FromType and
1950 // ToType have the same unqualified type (since we checked
1951 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001952 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001953}
1954
Douglas Gregor734d9862009-01-30 23:27:23 +00001955/// Determines whether there is a user-defined conversion sequence
1956/// (C++ [over.ics.user]) that converts expression From to the type
1957/// ToType. If such a conversion exists, User will contain the
1958/// user-defined conversion sequence that performs such a conversion
1959/// and this routine will return true. Otherwise, this routine returns
1960/// false and User is unspecified.
1961///
Douglas Gregor734d9862009-01-30 23:27:23 +00001962/// \param AllowExplicit true if the conversion should consider C++0x
1963/// "explicit" conversion functions as well as non-explicit conversion
1964/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00001965static OverloadingResult
1966IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1967 UserDefinedConversionSequence& User,
1968 OverloadCandidateSet& CandidateSet,
1969 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001970 // Whether we will only visit constructors.
1971 bool ConstructorsOnly = false;
1972
1973 // If the type we are conversion to is a class type, enumerate its
1974 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00001975 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001976 // C++ [over.match.ctor]p1:
1977 // When objects of class type are direct-initialized (8.5), or
1978 // copy-initialized from an expression of the same or a
1979 // derived class type (8.5), overload resolution selects the
1980 // constructor. [...] For copy-initialization, the candidate
1981 // functions are all the converting constructors (12.3.1) of
1982 // that class. The argument list is the expression-list within
1983 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00001984 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001985 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001986 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001987 ConstructorsOnly = true;
1988
John McCall120d63c2010-08-24 20:38:10 +00001989 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001990 // We're not going to find any constructors.
1991 } else if (CXXRecordDecl *ToRecordDecl
1992 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001993 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00001994 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001995 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00001996 NamedDecl *D = *Con;
1997 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1998
Douglas Gregordec06662009-08-21 18:42:58 +00001999 // Find the constructor (which may be a template).
2000 CXXConstructorDecl *Constructor = 0;
2001 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002002 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002003 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002004 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002005 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2006 else
John McCall9aa472c2010-03-19 07:35:19 +00002007 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002008
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00002009 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00002010 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00002011 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002012 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2013 /*ExplicitArgs*/ 0,
2014 &From, 1, CandidateSet,
2015 /*SuppressUserConversions=*/
2016 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002017 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002018 // Allow one user-defined conversion when user specifies a
2019 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002020 S.AddOverloadCandidate(Constructor, FoundDecl,
2021 &From, 1, CandidateSet,
2022 /*SuppressUserConversions=*/
2023 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002024 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002025 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002026 }
2027 }
2028
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002029 // Enumerate conversion functions, if we're allowed to.
2030 if (ConstructorsOnly) {
John McCall120d63c2010-08-24 20:38:10 +00002031 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2032 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002033 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002034 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002035 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002036 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002037 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2038 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002039 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002040 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002041 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002042 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002043 DeclAccessPair FoundDecl = I.getPair();
2044 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002045 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2046 if (isa<UsingShadowDecl>(D))
2047 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2048
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002049 CXXConversionDecl *Conv;
2050 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002051 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2052 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002053 else
John McCall32daa422010-03-31 01:36:47 +00002054 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002055
2056 if (AllowExplicit || !Conv->isExplicit()) {
2057 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002058 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2059 ActingContext, From, ToType,
2060 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002061 else
John McCall120d63c2010-08-24 20:38:10 +00002062 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2063 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002064 }
2065 }
2066 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002067 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002068
2069 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002070 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002071 case OR_Success:
2072 // Record the standard conversion we used and the conversion function.
2073 if (CXXConstructorDecl *Constructor
2074 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2075 // C++ [over.ics.user]p1:
2076 // If the user-defined conversion is specified by a
2077 // constructor (12.3.1), the initial standard conversion
2078 // sequence converts the source type to the type required by
2079 // the argument of the constructor.
2080 //
2081 QualType ThisType = Constructor->getThisType(S.Context);
2082 if (Best->Conversions[0].isEllipsis())
2083 User.EllipsisConversion = true;
2084 else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002085 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002086 User.EllipsisConversion = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002087 }
John McCall120d63c2010-08-24 20:38:10 +00002088 User.ConversionFunction = Constructor;
2089 User.After.setAsIdentityConversion();
2090 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2091 User.After.setAllToTypes(ToType);
2092 return OR_Success;
2093 } else if (CXXConversionDecl *Conversion
2094 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2095 // C++ [over.ics.user]p1:
2096 //
2097 // [...] If the user-defined conversion is specified by a
2098 // conversion function (12.3.2), the initial standard
2099 // conversion sequence converts the source type to the
2100 // implicit object parameter of the conversion function.
2101 User.Before = Best->Conversions[0].Standard;
2102 User.ConversionFunction = Conversion;
2103 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002104
John McCall120d63c2010-08-24 20:38:10 +00002105 // C++ [over.ics.user]p2:
2106 // The second standard conversion sequence converts the
2107 // result of the user-defined conversion to the target type
2108 // for the sequence. Since an implicit conversion sequence
2109 // is an initialization, the special rules for
2110 // initialization by user-defined conversion apply when
2111 // selecting the best user-defined conversion for a
2112 // user-defined conversion sequence (see 13.3.3 and
2113 // 13.3.3.1).
2114 User.After = Best->FinalConversion;
2115 return OR_Success;
2116 } else {
2117 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002118 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002119 }
2120
John McCall120d63c2010-08-24 20:38:10 +00002121 case OR_No_Viable_Function:
2122 return OR_No_Viable_Function;
2123 case OR_Deleted:
2124 // No conversion here! We're done.
2125 return OR_Deleted;
2126
2127 case OR_Ambiguous:
2128 return OR_Ambiguous;
2129 }
2130
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002131 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002132}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002133
2134bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002135Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002136 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002137 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002138 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00002139 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002140 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002141 if (OvResult == OR_Ambiguous)
2142 Diag(From->getSourceRange().getBegin(),
2143 diag::err_typecheck_ambiguous_condition)
2144 << From->getType() << ToType << From->getSourceRange();
2145 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2146 Diag(From->getSourceRange().getBegin(),
2147 diag::err_typecheck_nonviable_condition)
2148 << From->getType() << ToType << From->getSourceRange();
2149 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002150 return false;
John McCall120d63c2010-08-24 20:38:10 +00002151 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002152 return true;
2153}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002154
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002155/// CompareImplicitConversionSequences - Compare two implicit
2156/// conversion sequences to determine whether one is better than the
2157/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00002158static ImplicitConversionSequence::CompareKind
2159CompareImplicitConversionSequences(Sema &S,
2160 const ImplicitConversionSequence& ICS1,
2161 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002162{
2163 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2164 // conversion sequences (as defined in 13.3.3.1)
2165 // -- a standard conversion sequence (13.3.3.1.1) is a better
2166 // conversion sequence than a user-defined conversion sequence or
2167 // an ellipsis conversion sequence, and
2168 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2169 // conversion sequence than an ellipsis conversion sequence
2170 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002171 //
John McCall1d318332010-01-12 00:44:57 +00002172 // C++0x [over.best.ics]p10:
2173 // For the purpose of ranking implicit conversion sequences as
2174 // described in 13.3.3.2, the ambiguous conversion sequence is
2175 // treated as a user-defined sequence that is indistinguishable
2176 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002177 if (ICS1.getKindRank() < ICS2.getKindRank())
2178 return ImplicitConversionSequence::Better;
2179 else if (ICS2.getKindRank() < ICS1.getKindRank())
2180 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002181
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002182 // The following checks require both conversion sequences to be of
2183 // the same kind.
2184 if (ICS1.getKind() != ICS2.getKind())
2185 return ImplicitConversionSequence::Indistinguishable;
2186
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002187 // Two implicit conversion sequences of the same form are
2188 // indistinguishable conversion sequences unless one of the
2189 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002190 if (ICS1.isStandard())
John McCall120d63c2010-08-24 20:38:10 +00002191 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002192 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002193 // User-defined conversion sequence U1 is a better conversion
2194 // sequence than another user-defined conversion sequence U2 if
2195 // they contain the same user-defined conversion function or
2196 // constructor and if the second standard conversion sequence of
2197 // U1 is better than the second standard conversion sequence of
2198 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002199 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002200 ICS2.UserDefined.ConversionFunction)
John McCall120d63c2010-08-24 20:38:10 +00002201 return CompareStandardConversionSequences(S,
2202 ICS1.UserDefined.After,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002203 ICS2.UserDefined.After);
2204 }
2205
2206 return ImplicitConversionSequence::Indistinguishable;
2207}
2208
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002209static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2210 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2211 Qualifiers Quals;
2212 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2213 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2214 }
2215
2216 return Context.hasSameUnqualifiedType(T1, T2);
2217}
2218
Douglas Gregorad323a82010-01-27 03:51:04 +00002219// Per 13.3.3.2p3, compare the given standard conversion sequences to
2220// determine if one is a proper subset of the other.
2221static ImplicitConversionSequence::CompareKind
2222compareStandardConversionSubsets(ASTContext &Context,
2223 const StandardConversionSequence& SCS1,
2224 const StandardConversionSequence& SCS2) {
2225 ImplicitConversionSequence::CompareKind Result
2226 = ImplicitConversionSequence::Indistinguishable;
2227
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002228 // the identity conversion sequence is considered to be a subsequence of
2229 // any non-identity conversion sequence
2230 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2231 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2232 return ImplicitConversionSequence::Better;
2233 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2234 return ImplicitConversionSequence::Worse;
2235 }
2236
Douglas Gregorad323a82010-01-27 03:51:04 +00002237 if (SCS1.Second != SCS2.Second) {
2238 if (SCS1.Second == ICK_Identity)
2239 Result = ImplicitConversionSequence::Better;
2240 else if (SCS2.Second == ICK_Identity)
2241 Result = ImplicitConversionSequence::Worse;
2242 else
2243 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002244 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002245 return ImplicitConversionSequence::Indistinguishable;
2246
2247 if (SCS1.Third == SCS2.Third) {
2248 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2249 : ImplicitConversionSequence::Indistinguishable;
2250 }
2251
2252 if (SCS1.Third == ICK_Identity)
2253 return Result == ImplicitConversionSequence::Worse
2254 ? ImplicitConversionSequence::Indistinguishable
2255 : ImplicitConversionSequence::Better;
2256
2257 if (SCS2.Third == ICK_Identity)
2258 return Result == ImplicitConversionSequence::Better
2259 ? ImplicitConversionSequence::Indistinguishable
2260 : ImplicitConversionSequence::Worse;
2261
2262 return ImplicitConversionSequence::Indistinguishable;
2263}
2264
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002265/// CompareStandardConversionSequences - Compare two standard
2266/// conversion sequences to determine whether one is better than the
2267/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00002268static ImplicitConversionSequence::CompareKind
2269CompareStandardConversionSequences(Sema &S,
2270 const StandardConversionSequence& SCS1,
2271 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002272{
2273 // Standard conversion sequence S1 is a better conversion sequence
2274 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2275
2276 // -- S1 is a proper subsequence of S2 (comparing the conversion
2277 // sequences in the canonical form defined by 13.3.3.1.1,
2278 // excluding any Lvalue Transformation; the identity conversion
2279 // sequence is considered to be a subsequence of any
2280 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002281 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00002282 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00002283 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002284
2285 // -- the rank of S1 is better than the rank of S2 (by the rules
2286 // defined below), or, if not that,
2287 ImplicitConversionRank Rank1 = SCS1.getRank();
2288 ImplicitConversionRank Rank2 = SCS2.getRank();
2289 if (Rank1 < Rank2)
2290 return ImplicitConversionSequence::Better;
2291 else if (Rank2 < Rank1)
2292 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002293
Douglas Gregor57373262008-10-22 14:17:15 +00002294 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2295 // are indistinguishable unless one of the following rules
2296 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002297
Douglas Gregor57373262008-10-22 14:17:15 +00002298 // A conversion that is not a conversion of a pointer, or
2299 // pointer to member, to bool is better than another conversion
2300 // that is such a conversion.
2301 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2302 return SCS2.isPointerConversionToBool()
2303 ? ImplicitConversionSequence::Better
2304 : ImplicitConversionSequence::Worse;
2305
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002306 // C++ [over.ics.rank]p4b2:
2307 //
2308 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002309 // conversion of B* to A* is better than conversion of B* to
2310 // void*, and conversion of A* to void* is better than conversion
2311 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002312 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002313 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002314 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002315 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002316 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2317 // Exactly one of the conversion sequences is a conversion to
2318 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002319 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2320 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002321 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2322 // Neither conversion sequence converts to a void pointer; compare
2323 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002324 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00002325 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002326 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002327 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2328 // Both conversion sequences are conversions to void
2329 // pointers. Compare the source types to determine if there's an
2330 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002331 QualType FromType1 = SCS1.getFromType();
2332 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002333
2334 // Adjust the types we're converting from via the array-to-pointer
2335 // conversion, if we need to.
2336 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002337 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002338 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002339 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002340
Douglas Gregor01919692009-12-13 21:37:05 +00002341 QualType FromPointee1
2342 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2343 QualType FromPointee2
2344 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002345
John McCall120d63c2010-08-24 20:38:10 +00002346 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00002347 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002348 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00002349 return ImplicitConversionSequence::Worse;
2350
2351 // Objective-C++: If one interface is more specific than the
2352 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002353 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2354 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002355 if (FromIface1 && FromIface1) {
John McCall120d63c2010-08-24 20:38:10 +00002356 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor01919692009-12-13 21:37:05 +00002357 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002358 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor01919692009-12-13 21:37:05 +00002359 return ImplicitConversionSequence::Worse;
2360 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002361 }
Douglas Gregor57373262008-10-22 14:17:15 +00002362
2363 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2364 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002365 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00002366 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002367 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002368
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002369 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002370 // C++0x [over.ics.rank]p3b4:
2371 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2372 // implicit object parameter of a non-static member function declared
2373 // without a ref-qualifier, and S1 binds an rvalue reference to an
2374 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00002375 // FIXME: We don't know if we're dealing with the implicit object parameter,
2376 // or if the member function in this case has a ref qualifier.
2377 // (Of course, we don't have ref qualifiers yet.)
2378 if (SCS1.RRefBinding != SCS2.RRefBinding)
2379 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2380 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002381
2382 // C++ [over.ics.rank]p3b4:
2383 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2384 // which the references refer are the same type except for
2385 // top-level cv-qualifiers, and the type to which the reference
2386 // initialized by S2 refers is more cv-qualified than the type
2387 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002388 QualType T1 = SCS1.getToType(2);
2389 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002390 T1 = S.Context.getCanonicalType(T1);
2391 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002392 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002393 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2394 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002395 if (UnqualT1 == UnqualT2) {
2396 // If the type is an array type, promote the element qualifiers to the type
2397 // for comparison.
2398 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002399 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002400 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002401 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002402 if (T2.isMoreQualifiedThan(T1))
2403 return ImplicitConversionSequence::Better;
2404 else if (T1.isMoreQualifiedThan(T2))
2405 return ImplicitConversionSequence::Worse;
2406 }
2407 }
Douglas Gregor57373262008-10-22 14:17:15 +00002408
2409 return ImplicitConversionSequence::Indistinguishable;
2410}
2411
2412/// CompareQualificationConversions - Compares two standard conversion
2413/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002414/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2415ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002416CompareQualificationConversions(Sema &S,
2417 const StandardConversionSequence& SCS1,
2418 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002419 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002420 // -- S1 and S2 differ only in their qualification conversion and
2421 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2422 // cv-qualification signature of type T1 is a proper subset of
2423 // the cv-qualification signature of type T2, and S1 is not the
2424 // deprecated string literal array-to-pointer conversion (4.2).
2425 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2426 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2427 return ImplicitConversionSequence::Indistinguishable;
2428
2429 // FIXME: the example in the standard doesn't use a qualification
2430 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002431 QualType T1 = SCS1.getToType(2);
2432 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002433 T1 = S.Context.getCanonicalType(T1);
2434 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002435 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002436 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2437 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002438
2439 // If the types are the same, we won't learn anything by unwrapped
2440 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002441 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002442 return ImplicitConversionSequence::Indistinguishable;
2443
Chandler Carruth28e318c2009-12-29 07:16:59 +00002444 // If the type is an array type, promote the element qualifiers to the type
2445 // for comparison.
2446 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002447 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002448 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002449 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002450
Mike Stump1eb44332009-09-09 15:08:12 +00002451 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002452 = ImplicitConversionSequence::Indistinguishable;
John McCall120d63c2010-08-24 20:38:10 +00002453 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002454 // Within each iteration of the loop, we check the qualifiers to
2455 // determine if this still looks like a qualification
2456 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002457 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002458 // until there are no more pointers or pointers-to-members left
2459 // to unwrap. This essentially mimics what
2460 // IsQualificationConversion does, but here we're checking for a
2461 // strict subset of qualifiers.
2462 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2463 // The qualifiers are the same, so this doesn't tell us anything
2464 // about how the sequences rank.
2465 ;
2466 else if (T2.isMoreQualifiedThan(T1)) {
2467 // T1 has fewer qualifiers, so it could be the better sequence.
2468 if (Result == ImplicitConversionSequence::Worse)
2469 // Neither has qualifiers that are a subset of the other's
2470 // qualifiers.
2471 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002472
Douglas Gregor57373262008-10-22 14:17:15 +00002473 Result = ImplicitConversionSequence::Better;
2474 } else if (T1.isMoreQualifiedThan(T2)) {
2475 // T2 has fewer qualifiers, so it could be the better sequence.
2476 if (Result == ImplicitConversionSequence::Better)
2477 // Neither has qualifiers that are a subset of the other's
2478 // qualifiers.
2479 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002480
Douglas Gregor57373262008-10-22 14:17:15 +00002481 Result = ImplicitConversionSequence::Worse;
2482 } else {
2483 // Qualifiers are disjoint.
2484 return ImplicitConversionSequence::Indistinguishable;
2485 }
2486
2487 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00002488 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002489 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002490 }
2491
Douglas Gregor57373262008-10-22 14:17:15 +00002492 // Check that the winning standard conversion sequence isn't using
2493 // the deprecated string literal array to pointer conversion.
2494 switch (Result) {
2495 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002496 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002497 Result = ImplicitConversionSequence::Indistinguishable;
2498 break;
2499
2500 case ImplicitConversionSequence::Indistinguishable:
2501 break;
2502
2503 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002504 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002505 Result = ImplicitConversionSequence::Indistinguishable;
2506 break;
2507 }
2508
2509 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002510}
2511
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002512/// CompareDerivedToBaseConversions - Compares two standard conversion
2513/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002514/// various kinds of derived-to-base conversions (C++
2515/// [over.ics.rank]p4b3). As part of these checks, we also look at
2516/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002517ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002518CompareDerivedToBaseConversions(Sema &S,
2519 const StandardConversionSequence& SCS1,
2520 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002521 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002522 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002523 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002524 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002525
2526 // Adjust the types we're converting from via the array-to-pointer
2527 // conversion, if we need to.
2528 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002529 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002530 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002531 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002532
2533 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00002534 FromType1 = S.Context.getCanonicalType(FromType1);
2535 ToType1 = S.Context.getCanonicalType(ToType1);
2536 FromType2 = S.Context.getCanonicalType(FromType2);
2537 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002538
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002539 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002540 //
2541 // If class B is derived directly or indirectly from class A and
2542 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002543 //
2544 // For Objective-C, we let A, B, and C also be Objective-C
2545 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002546
2547 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002548 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002549 SCS2.Second == ICK_Pointer_Conversion &&
2550 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2551 FromType1->isPointerType() && FromType2->isPointerType() &&
2552 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002553 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002554 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002555 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002556 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002557 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002558 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002559 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002560 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002561
John McCallc12c5bb2010-05-15 11:32:37 +00002562 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2563 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2564 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2565 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002566
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002567 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002568 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002569 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002570 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002571 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002572 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002573
2574 if (ToIface1 && ToIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002575 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002576 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002577 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002578 return ImplicitConversionSequence::Worse;
2579 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002580 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002581
2582 // -- conversion of B* to A* is better than conversion of C* to A*,
2583 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002584 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002585 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002586 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002587 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002588
Douglas Gregorcb7de522008-11-26 23:31:11 +00002589 if (FromIface1 && FromIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002590 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002591 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002592 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002593 return ImplicitConversionSequence::Worse;
2594 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002595 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002596 }
2597
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002598 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002599 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2600 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2601 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2602 const MemberPointerType * FromMemPointer1 =
2603 FromType1->getAs<MemberPointerType>();
2604 const MemberPointerType * ToMemPointer1 =
2605 ToType1->getAs<MemberPointerType>();
2606 const MemberPointerType * FromMemPointer2 =
2607 FromType2->getAs<MemberPointerType>();
2608 const MemberPointerType * ToMemPointer2 =
2609 ToType2->getAs<MemberPointerType>();
2610 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2611 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2612 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2613 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2614 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2615 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2616 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2617 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002618 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002619 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002620 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002621 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00002622 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002623 return ImplicitConversionSequence::Better;
2624 }
2625 // conversion of B::* to C::* is better than conversion of A::* to C::*
2626 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002627 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002628 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002629 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002630 return ImplicitConversionSequence::Worse;
2631 }
2632 }
2633
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002634 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002635 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002636 // -- binding of an expression of type C to a reference of type
2637 // B& is better than binding an expression of type C to a
2638 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002639 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2640 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2641 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002642 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002643 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002644 return ImplicitConversionSequence::Worse;
2645 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002646
Douglas Gregor225c41e2008-11-03 19:09:14 +00002647 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002648 // -- binding of an expression of type B to a reference of type
2649 // A& is better than binding an expression of type C to a
2650 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002651 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2652 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2653 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002654 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002655 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002656 return ImplicitConversionSequence::Worse;
2657 }
2658 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002659
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002660 return ImplicitConversionSequence::Indistinguishable;
2661}
2662
Douglas Gregorabe183d2010-04-13 16:31:36 +00002663/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2664/// determine whether they are reference-related,
2665/// reference-compatible, reference-compatible with added
2666/// qualification, or incompatible, for use in C++ initialization by
2667/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2668/// type, and the first type (T1) is the pointee type of the reference
2669/// type being initialized.
2670Sema::ReferenceCompareResult
2671Sema::CompareReferenceRelationship(SourceLocation Loc,
2672 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00002673 bool &DerivedToBase,
2674 bool &ObjCConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002675 assert(!OrigT1->isReferenceType() &&
2676 "T1 must be the pointee type of the reference type");
2677 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2678
2679 QualType T1 = Context.getCanonicalType(OrigT1);
2680 QualType T2 = Context.getCanonicalType(OrigT2);
2681 Qualifiers T1Quals, T2Quals;
2682 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2683 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2684
2685 // C++ [dcl.init.ref]p4:
2686 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2687 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2688 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00002689 DerivedToBase = false;
2690 ObjCConversion = false;
2691 if (UnqualT1 == UnqualT2) {
2692 // Nothing to do.
2693 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002694 IsDerivedFrom(UnqualT2, UnqualT1))
2695 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00002696 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2697 UnqualT2->isObjCObjectOrInterfaceType() &&
2698 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2699 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002700 else
2701 return Ref_Incompatible;
2702
2703 // At this point, we know that T1 and T2 are reference-related (at
2704 // least).
2705
2706 // If the type is an array type, promote the element qualifiers to the type
2707 // for comparison.
2708 if (isa<ArrayType>(T1) && T1Quals)
2709 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2710 if (isa<ArrayType>(T2) && T2Quals)
2711 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2712
2713 // C++ [dcl.init.ref]p4:
2714 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2715 // reference-related to T2 and cv1 is the same cv-qualification
2716 // as, or greater cv-qualification than, cv2. For purposes of
2717 // overload resolution, cases for which cv1 is greater
2718 // cv-qualification than cv2 are identified as
2719 // reference-compatible with added qualification (see 13.3.3.2).
2720 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2721 return Ref_Compatible;
2722 else if (T1.isMoreQualifiedThan(T2))
2723 return Ref_Compatible_With_Added_Qualification;
2724 else
2725 return Ref_Related;
2726}
2727
Douglas Gregor604eb652010-08-11 02:15:33 +00002728/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00002729/// with DeclType. Return true if something definite is found.
2730static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00002731FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2732 QualType DeclType, SourceLocation DeclLoc,
2733 Expr *Init, QualType T2, bool AllowRvalues,
2734 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002735 assert(T2->isRecordType() && "Can only find conversions of record types.");
2736 CXXRecordDecl *T2RecordDecl
2737 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2738
Douglas Gregor604eb652010-08-11 02:15:33 +00002739 QualType ToType
2740 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2741 : DeclType;
2742
Sebastian Redl4680bf22010-06-30 18:13:39 +00002743 OverloadCandidateSet CandidateSet(DeclLoc);
2744 const UnresolvedSetImpl *Conversions
2745 = T2RecordDecl->getVisibleConversionFunctions();
2746 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2747 E = Conversions->end(); I != E; ++I) {
2748 NamedDecl *D = *I;
2749 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2750 if (isa<UsingShadowDecl>(D))
2751 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2752
2753 FunctionTemplateDecl *ConvTemplate
2754 = dyn_cast<FunctionTemplateDecl>(D);
2755 CXXConversionDecl *Conv;
2756 if (ConvTemplate)
2757 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2758 else
2759 Conv = cast<CXXConversionDecl>(D);
2760
Douglas Gregor604eb652010-08-11 02:15:33 +00002761 // If this is an explicit conversion, and we're not allowed to consider
2762 // explicit conversions, skip it.
2763 if (!AllowExplicit && Conv->isExplicit())
2764 continue;
2765
2766 if (AllowRvalues) {
2767 bool DerivedToBase = false;
2768 bool ObjCConversion = false;
2769 if (!ConvTemplate &&
2770 S.CompareReferenceRelationship(DeclLoc,
2771 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2772 DeclType.getNonReferenceType().getUnqualifiedType(),
2773 DerivedToBase, ObjCConversion)
2774 == Sema::Ref_Incompatible)
2775 continue;
2776 } else {
2777 // If the conversion function doesn't return a reference type,
2778 // it can't be considered for this conversion. An rvalue reference
2779 // is only acceptable if its referencee is a function type.
2780
2781 const ReferenceType *RefType =
2782 Conv->getConversionType()->getAs<ReferenceType>();
2783 if (!RefType ||
2784 (!RefType->isLValueReferenceType() &&
2785 !RefType->getPointeeType()->isFunctionType()))
2786 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002787 }
Douglas Gregor604eb652010-08-11 02:15:33 +00002788
2789 if (ConvTemplate)
2790 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2791 Init, ToType, CandidateSet);
2792 else
2793 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2794 ToType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002795 }
2796
2797 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002798 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002799 case OR_Success:
2800 // C++ [over.ics.ref]p1:
2801 //
2802 // [...] If the parameter binds directly to the result of
2803 // applying a conversion function to the argument
2804 // expression, the implicit conversion sequence is a
2805 // user-defined conversion sequence (13.3.3.1.2), with the
2806 // second standard conversion sequence either an identity
2807 // conversion or, if the conversion function returns an
2808 // entity of a type that is a derived class of the parameter
2809 // type, a derived-to-base Conversion.
2810 if (!Best->FinalConversion.DirectBinding)
2811 return false;
2812
2813 ICS.setUserDefined();
2814 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2815 ICS.UserDefined.After = Best->FinalConversion;
2816 ICS.UserDefined.ConversionFunction = Best->Function;
2817 ICS.UserDefined.EllipsisConversion = false;
2818 assert(ICS.UserDefined.After.ReferenceBinding &&
2819 ICS.UserDefined.After.DirectBinding &&
2820 "Expected a direct reference binding!");
2821 return true;
2822
2823 case OR_Ambiguous:
2824 ICS.setAmbiguous();
2825 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2826 Cand != CandidateSet.end(); ++Cand)
2827 if (Cand->Viable)
2828 ICS.Ambiguous.addConversion(Cand->Function);
2829 return true;
2830
2831 case OR_No_Viable_Function:
2832 case OR_Deleted:
2833 // There was no suitable conversion, or we found a deleted
2834 // conversion; continue with other checks.
2835 return false;
2836 }
Eric Christopher1c3d5022010-06-30 18:36:32 +00002837
2838 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002839}
2840
Douglas Gregorabe183d2010-04-13 16:31:36 +00002841/// \brief Compute an implicit conversion sequence for reference
2842/// initialization.
2843static ImplicitConversionSequence
2844TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2845 SourceLocation DeclLoc,
2846 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002847 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002848 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2849
2850 // Most paths end in a failed conversion.
2851 ImplicitConversionSequence ICS;
2852 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2853
2854 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2855 QualType T2 = Init->getType();
2856
2857 // If the initializer is the address of an overloaded function, try
2858 // to resolve the overloaded function. If all goes well, T2 is the
2859 // type of the resulting function.
2860 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2861 DeclAccessPair Found;
2862 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2863 false, Found))
2864 T2 = Fn->getType();
2865 }
2866
2867 // Compute some basic properties of the types and the initializer.
2868 bool isRValRef = DeclType->isRValueReferenceType();
2869 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002870 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002871 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002872 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002873 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2874 ObjCConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002875
Douglas Gregorabe183d2010-04-13 16:31:36 +00002876
Sebastian Redl4680bf22010-06-30 18:13:39 +00002877 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00002878 // A reference to type "cv1 T1" is initialized by an expression
2879 // of type "cv2 T2" as follows:
2880
Sebastian Redl4680bf22010-06-30 18:13:39 +00002881 // -- If reference is an lvalue reference and the initializer expression
2882 // The next bullet point (T1 is a function) is pretty much equivalent to this
2883 // one, so it's handled here.
2884 if (!isRValRef || T1->isFunctionType()) {
2885 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2886 // reference-compatible with "cv2 T2," or
2887 //
2888 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2889 if (InitCategory.isLValue() &&
2890 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002891 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00002892 // When a parameter of reference type binds directly (8.5.3)
2893 // to an argument expression, the implicit conversion sequence
2894 // is the identity conversion, unless the argument expression
2895 // has a type that is a derived class of the parameter type,
2896 // in which case the implicit conversion sequence is a
2897 // derived-to-base Conversion (13.3.3.1).
2898 ICS.setStandard();
2899 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00002900 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2901 : ObjCConversion? ICK_Compatible_Conversion
2902 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002903 ICS.Standard.Third = ICK_Identity;
2904 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2905 ICS.Standard.setToType(0, T2);
2906 ICS.Standard.setToType(1, T1);
2907 ICS.Standard.setToType(2, T1);
2908 ICS.Standard.ReferenceBinding = true;
2909 ICS.Standard.DirectBinding = true;
2910 ICS.Standard.RRefBinding = isRValRef;
2911 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002912
Sebastian Redl4680bf22010-06-30 18:13:39 +00002913 // Nothing more to do: the inaccessibility/ambiguity check for
2914 // derived-to-base conversions is suppressed when we're
2915 // computing the implicit conversion sequence (C++
2916 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002917 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002918 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00002919
Sebastian Redl4680bf22010-06-30 18:13:39 +00002920 // -- has a class type (i.e., T2 is a class type), where T1 is
2921 // not reference-related to T2, and can be implicitly
2922 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2923 // is reference-compatible with "cv3 T3" 92) (this
2924 // conversion is selected by enumerating the applicable
2925 // conversion functions (13.3.1.6) and choosing the best
2926 // one through overload resolution (13.3)),
2927 if (!SuppressUserConversions && T2->isRecordType() &&
2928 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2929 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00002930 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2931 Init, T2, /*AllowRvalues=*/false,
2932 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00002933 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002934 }
2935 }
2936
Sebastian Redl4680bf22010-06-30 18:13:39 +00002937 // -- Otherwise, the reference shall be an lvalue reference to a
2938 // non-volatile const type (i.e., cv1 shall be const), or the reference
2939 // shall be an rvalue reference and the initializer expression shall be
2940 // an rvalue or have a function type.
Douglas Gregor66821b52010-04-18 09:22:00 +00002941 //
2942 // We actually handle one oddity of C++ [over.ics.ref] at this
2943 // point, which is that, due to p2 (which short-circuits reference
2944 // binding by only attempting a simple conversion for non-direct
2945 // bindings) and p3's strange wording, we allow a const volatile
2946 // reference to bind to an rvalue. Hence the check for the presence
2947 // of "const" rather than checking for "const" being the only
2948 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00002949 // This is also the point where rvalue references and lvalue inits no longer
2950 // go together.
2951 if ((!isRValRef && !T1.isConstQualified()) ||
2952 (isRValRef && InitCategory.isLValue()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00002953 return ICS;
2954
Sebastian Redl4680bf22010-06-30 18:13:39 +00002955 // -- If T1 is a function type, then
2956 // -- if T2 is the same type as T1, the reference is bound to the
2957 // initializer expression lvalue;
2958 // -- if T2 is a class type and the initializer expression can be
2959 // implicitly converted to an lvalue of type T1 [...], the
2960 // reference is bound to the function lvalue that is the result
2961 // of the conversion;
2962 // This is the same as for the lvalue case above, so it was handled there.
2963 // -- otherwise, the program is ill-formed.
2964 // This is the one difference to the lvalue case.
2965 if (T1->isFunctionType())
2966 return ICS;
2967
2968 // -- Otherwise, if T2 is a class type and
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002969 // -- the initializer expression is an rvalue and "cv1 T1"
2970 // is reference-compatible with "cv2 T2," or
Douglas Gregorabe183d2010-04-13 16:31:36 +00002971 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002972 // -- T1 is not reference-related to T2 and the initializer
2973 // expression can be implicitly converted to an rvalue
2974 // of type "cv3 T3" (this conversion is selected by
2975 // enumerating the applicable conversion functions
2976 // (13.3.1.6) and choosing the best one through overload
2977 // resolution (13.3)),
Douglas Gregorabe183d2010-04-13 16:31:36 +00002978 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002979 // then the reference is bound to the initializer
2980 // expression rvalue in the first case and to the object
2981 // that is the result of the conversion in the second case
2982 // (or, in either case, to the appropriate base class
2983 // subobject of the object).
Douglas Gregor604eb652010-08-11 02:15:33 +00002984 if (T2->isRecordType()) {
2985 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2986 // direct binding in C++0x but not in C++03.
2987 if (InitCategory.isRValue() &&
2988 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2989 ICS.setStandard();
2990 ICS.Standard.First = ICK_Identity;
2991 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2992 : ObjCConversion? ICK_Compatible_Conversion
2993 : ICK_Identity;
2994 ICS.Standard.Third = ICK_Identity;
2995 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2996 ICS.Standard.setToType(0, T2);
2997 ICS.Standard.setToType(1, T1);
2998 ICS.Standard.setToType(2, T1);
2999 ICS.Standard.ReferenceBinding = true;
3000 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
3001 ICS.Standard.RRefBinding = isRValRef;
3002 ICS.Standard.CopyConstructor = 0;
3003 return ICS;
3004 }
3005
3006 // Second case: not reference-related.
3007 if (RefRelationship == Sema::Ref_Incompatible &&
3008 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3009 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3010 Init, T2, /*AllowRvalues=*/true,
3011 AllowExplicit))
3012 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003013 }
Douglas Gregor604eb652010-08-11 02:15:33 +00003014
Douglas Gregorabe183d2010-04-13 16:31:36 +00003015 // -- Otherwise, a temporary of type "cv1 T1" is created and
3016 // initialized from the initializer expression using the
3017 // rules for a non-reference copy initialization (8.5). The
3018 // reference is then bound to the temporary. If T1 is
3019 // reference-related to T2, cv1 must be the same
3020 // cv-qualification as, or greater cv-qualification than,
3021 // cv2; otherwise, the program is ill-formed.
3022 if (RefRelationship == Sema::Ref_Related) {
3023 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3024 // we would be reference-compatible or reference-compatible with
3025 // added qualification. But that wasn't the case, so the reference
3026 // initialization fails.
3027 return ICS;
3028 }
3029
3030 // If at least one of the types is a class type, the types are not
3031 // related, and we aren't allowed any user conversions, the
3032 // reference binding fails. This case is important for breaking
3033 // recursion, since TryImplicitConversion below will attempt to
3034 // create a temporary through the use of a copy constructor.
3035 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3036 (T1->isRecordType() || T2->isRecordType()))
3037 return ICS;
3038
3039 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00003040 // When a parameter of reference type is not bound directly to
3041 // an argument expression, the conversion sequence is the one
3042 // required to convert the argument expression to the
3043 // underlying type of the reference according to
3044 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3045 // to copy-initializing a temporary of the underlying type with
3046 // the argument expression. Any difference in top-level
3047 // cv-qualification is subsumed by the initialization itself
3048 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00003049 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3050 /*AllowExplicit=*/false,
3051 /*InOverloadResolution=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003052
3053 // Of course, that's still a reference binding.
3054 if (ICS.isStandard()) {
3055 ICS.Standard.ReferenceBinding = true;
3056 ICS.Standard.RRefBinding = isRValRef;
3057 } else if (ICS.isUserDefined()) {
3058 ICS.UserDefined.After.ReferenceBinding = true;
3059 ICS.UserDefined.After.RRefBinding = isRValRef;
3060 }
3061 return ICS;
3062}
3063
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003064/// TryCopyInitialization - Try to copy-initialize a value of type
3065/// ToType from the expression From. Return the implicit conversion
3066/// sequence required to pass this argument, which may be a bad
3067/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00003068/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00003069/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00003070static ImplicitConversionSequence
3071TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00003072 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00003073 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003074 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00003075 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003076 /*FIXME:*/From->getLocStart(),
3077 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003078 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003079
John McCall120d63c2010-08-24 20:38:10 +00003080 return TryImplicitConversion(S, From, ToType,
3081 SuppressUserConversions,
3082 /*AllowExplicit=*/false,
3083 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003084}
3085
Douglas Gregor96176b32008-11-18 23:14:02 +00003086/// TryObjectArgumentInitialization - Try to initialize the object
3087/// parameter of the given member function (@c Method) from the
3088/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00003089static ImplicitConversionSequence
3090TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3091 CXXMethodDecl *Method,
3092 CXXRecordDecl *ActingContext) {
3093 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003094 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3095 // const volatile object.
3096 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3097 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00003098 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00003099
3100 // Set up the conversion sequence as a "bad" conversion, to allow us
3101 // to exit early.
3102 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00003103
3104 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00003105 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00003106 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00003107 FromType = PT->getPointeeType();
3108
3109 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00003110
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003111 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00003112 // where X is the class of which the function is a member
3113 // (C++ [over.match.funcs]p4). However, when finding an implicit
3114 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00003115 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00003116 // (C++ [over.match.funcs]p5). We perform a simplified version of
3117 // reference binding here, that allows class rvalues to bind to
3118 // non-constant references.
3119
3120 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3121 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall120d63c2010-08-24 20:38:10 +00003122 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00003123 if (ImplicitParamType.getCVRQualifiers()
3124 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00003125 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00003126 ICS.setBad(BadConversionSequence::bad_qualifiers,
3127 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003128 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003129 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003130
3131 // Check that we have either the same type or a derived type. It
3132 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00003133 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00003134 ImplicitConversionKind SecondKind;
3135 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3136 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00003137 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00003138 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00003139 else {
John McCallb1bdc622010-02-25 01:37:24 +00003140 ICS.setBad(BadConversionSequence::unrelated_class,
3141 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003142 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003143 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003144
3145 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00003146 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003147 ICS.Standard.setAsIdentityConversion();
3148 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003149 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003150 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003151 ICS.Standard.ReferenceBinding = true;
3152 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00003153 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003154 return ICS;
3155}
3156
3157/// PerformObjectArgumentInitialization - Perform initialization of
3158/// the implicit object parameter for the given Method with the given
3159/// expression.
3160bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00003161Sema::PerformObjectArgumentInitialization(Expr *&From,
3162 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003163 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003164 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003165 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003166 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003167 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003168
Ted Kremenek6217b802009-07-29 21:53:49 +00003169 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003170 FromRecordType = PT->getPointeeType();
3171 DestType = Method->getThisType(Context);
3172 } else {
3173 FromRecordType = From->getType();
3174 DestType = ImplicitParamRecordType;
3175 }
3176
John McCall701c89e2009-12-03 04:06:58 +00003177 // Note that we always use the true parent context when performing
3178 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003179 ImplicitConversionSequence ICS
John McCall120d63c2010-08-24 20:38:10 +00003180 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall701c89e2009-12-03 04:06:58 +00003181 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00003182 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00003183 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003184 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003185 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003186
Douglas Gregor5fccd362010-03-03 23:55:11 +00003187 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00003188 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00003189
Douglas Gregor5fccd362010-03-03 23:55:11 +00003190 if (!Context.hasSameType(From->getType(), DestType))
John McCall2de56d12010-08-25 11:45:40 +00003191 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall5baba9d2010-08-25 10:28:54 +00003192 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor96176b32008-11-18 23:14:02 +00003193 return false;
3194}
3195
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003196/// TryContextuallyConvertToBool - Attempt to contextually convert the
3197/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00003198static ImplicitConversionSequence
3199TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003200 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00003201 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003202 // FIXME: Are these flags correct?
3203 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003204 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00003205 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003206}
3207
3208/// PerformContextuallyConvertToBool - Perform a contextual conversion
3209/// of the expression From to bool (C++0x [conv]p3).
3210bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall120d63c2010-08-24 20:38:10 +00003211 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00003212 if (!ICS.isBad())
3213 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003214
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003215 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003216 return Diag(From->getSourceRange().getBegin(),
3217 diag::err_typecheck_bool_condition)
3218 << From->getType() << From->getSourceRange();
3219 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003220}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003221
3222/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3223/// expression From to 'id'.
John McCall120d63c2010-08-24 20:38:10 +00003224static ImplicitConversionSequence
3225TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3226 QualType Ty = S.Context.getObjCIdType();
3227 return TryImplicitConversion(S, From, Ty,
3228 // FIXME: Are these flags correct?
3229 /*SuppressUserConversions=*/false,
3230 /*AllowExplicit=*/true,
3231 /*InOverloadResolution=*/false);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003232}
John McCall120d63c2010-08-24 20:38:10 +00003233
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003234/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3235/// of the expression From to 'id'.
3236bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003237 QualType Ty = Context.getObjCIdType();
John McCall120d63c2010-08-24 20:38:10 +00003238 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003239 if (!ICS.isBad())
3240 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3241 return true;
3242}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003243
Douglas Gregorc30614b2010-06-29 23:17:37 +00003244/// \brief Attempt to convert the given expression to an integral or
3245/// enumeration type.
3246///
3247/// This routine will attempt to convert an expression of class type to an
3248/// integral or enumeration type, if that class type only has a single
3249/// conversion to an integral or enumeration type.
3250///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003251/// \param Loc The source location of the construct that requires the
3252/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003253///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003254/// \param FromE The expression we're converting from.
3255///
3256/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3257/// have integral or enumeration type.
3258///
3259/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3260/// incomplete class type.
3261///
3262/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3263/// explicit conversion function (because no implicit conversion functions
3264/// were available). This is a recovery mode.
3265///
3266/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3267/// showing which conversion was picked.
3268///
3269/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3270/// conversion function that could convert to integral or enumeration type.
3271///
3272/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3273/// usable conversion function.
3274///
3275/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3276/// function, which may be an extension in this case.
3277///
3278/// \returns The expression, converted to an integral or enumeration type if
3279/// successful.
John McCall60d7b3a2010-08-24 06:29:42 +00003280ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003281Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003282 const PartialDiagnostic &NotIntDiag,
3283 const PartialDiagnostic &IncompleteDiag,
3284 const PartialDiagnostic &ExplicitConvDiag,
3285 const PartialDiagnostic &ExplicitConvNote,
3286 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003287 const PartialDiagnostic &AmbigNote,
3288 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00003289 // We can't perform any more checking for type-dependent expressions.
3290 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00003291 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003292
3293 // If the expression already has integral or enumeration type, we're golden.
3294 QualType T = From->getType();
3295 if (T->isIntegralOrEnumerationType())
John McCall9ae2f072010-08-23 23:25:46 +00003296 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003297
3298 // FIXME: Check for missing '()' if T is a function type?
3299
3300 // If we don't have a class type in C++, there's no way we can get an
3301 // expression of integral or enumeration type.
3302 const RecordType *RecordTy = T->getAs<RecordType>();
3303 if (!RecordTy || !getLangOptions().CPlusPlus) {
3304 Diag(Loc, NotIntDiag)
3305 << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00003306 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003307 }
3308
3309 // We must have a complete class type.
3310 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00003311 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003312
3313 // Look for a conversion to an integral or enumeration type.
3314 UnresolvedSet<4> ViableConversions;
3315 UnresolvedSet<4> ExplicitConversions;
3316 const UnresolvedSetImpl *Conversions
3317 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3318
3319 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3320 E = Conversions->end();
3321 I != E;
3322 ++I) {
3323 if (CXXConversionDecl *Conversion
3324 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3325 if (Conversion->getConversionType().getNonReferenceType()
3326 ->isIntegralOrEnumerationType()) {
3327 if (Conversion->isExplicit())
3328 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3329 else
3330 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3331 }
3332 }
3333
3334 switch (ViableConversions.size()) {
3335 case 0:
3336 if (ExplicitConversions.size() == 1) {
3337 DeclAccessPair Found = ExplicitConversions[0];
3338 CXXConversionDecl *Conversion
3339 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3340
3341 // The user probably meant to invoke the given explicit
3342 // conversion; use it.
3343 QualType ConvTy
3344 = Conversion->getConversionType().getNonReferenceType();
3345 std::string TypeStr;
3346 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3347
3348 Diag(Loc, ExplicitConvDiag)
3349 << T << ConvTy
3350 << FixItHint::CreateInsertion(From->getLocStart(),
3351 "static_cast<" + TypeStr + ">(")
3352 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3353 ")");
3354 Diag(Conversion->getLocation(), ExplicitConvNote)
3355 << ConvTy->isEnumeralType() << ConvTy;
3356
3357 // If we aren't in a SFINAE context, build a call to the
3358 // explicit conversion function.
3359 if (isSFINAEContext())
3360 return ExprError();
3361
3362 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCall9ae2f072010-08-23 23:25:46 +00003363 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003364 }
3365
3366 // We'll complain below about a non-integral condition type.
3367 break;
3368
3369 case 1: {
3370 // Apply this conversion.
3371 DeclAccessPair Found = ViableConversions[0];
3372 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003373
3374 CXXConversionDecl *Conversion
3375 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3376 QualType ConvTy
3377 = Conversion->getConversionType().getNonReferenceType();
3378 if (ConvDiag.getDiagID()) {
3379 if (isSFINAEContext())
3380 return ExprError();
3381
3382 Diag(Loc, ConvDiag)
3383 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3384 }
3385
John McCall9ae2f072010-08-23 23:25:46 +00003386 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003387 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorc30614b2010-06-29 23:17:37 +00003388 break;
3389 }
3390
3391 default:
3392 Diag(Loc, AmbigDiag)
3393 << T << From->getSourceRange();
3394 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3395 CXXConversionDecl *Conv
3396 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3397 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3398 Diag(Conv->getLocation(), AmbigNote)
3399 << ConvTy->isEnumeralType() << ConvTy;
3400 }
John McCall9ae2f072010-08-23 23:25:46 +00003401 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003402 }
3403
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003404 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00003405 Diag(Loc, NotIntDiag)
3406 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003407
John McCall9ae2f072010-08-23 23:25:46 +00003408 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003409}
3410
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003411/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003412/// candidate functions, using the given function call arguments. If
3413/// @p SuppressUserConversions, then don't allow user-defined
3414/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003415///
3416/// \para PartialOverloading true if we are performing "partial" overloading
3417/// based on an incomplete set of function arguments. This feature is used by
3418/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003419void
3420Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003421 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003422 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003423 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003424 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003425 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003426 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003427 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003428 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003429 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00003430 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003431
Douglas Gregor88a35142008-12-22 05:46:06 +00003432 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003433 if (!isa<CXXConstructorDecl>(Method)) {
3434 // If we get here, it's because we're calling a member function
3435 // that is named without a member access expression (e.g.,
3436 // "this->f") that was either written explicitly or created
3437 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003438 // function, e.g., X::f(). We use an empty type for the implied
3439 // object argument (C++ [over.call.func]p3), and the acting context
3440 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003441 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00003442 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003443 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003444 return;
3445 }
3446 // We treat a constructor like a non-member function, since its object
3447 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003448 }
3449
Douglas Gregorfd476482009-11-13 23:59:09 +00003450 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003451 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003452
Douglas Gregor7edfb692009-11-23 12:27:39 +00003453 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003454 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003455
Douglas Gregor66724ea2009-11-14 01:20:54 +00003456 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3457 // C++ [class.copy]p3:
3458 // A member function template is never instantiated to perform the copy
3459 // of a class object to an object of its class type.
3460 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3461 if (NumArgs == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00003462 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003463 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3464 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003465 return;
3466 }
3467
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003468 // Add this candidate
3469 CandidateSet.push_back(OverloadCandidate());
3470 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003471 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003472 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003473 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003474 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003475 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003476
3477 unsigned NumArgsInProto = Proto->getNumArgs();
3478
3479 // (C++ 13.3.2p2): A candidate function having fewer than m
3480 // parameters is viable only if it has an ellipsis in its parameter
3481 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003482 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3483 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003484 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003485 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003486 return;
3487 }
3488
3489 // (C++ 13.3.2p2): A candidate function having more than m parameters
3490 // is viable only if the (m+1)st parameter has a default argument
3491 // (8.3.6). For the purposes of overload resolution, the
3492 // parameter list is truncated on the right, so that there are
3493 // exactly m parameters.
3494 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003495 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003496 // Not enough arguments.
3497 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003498 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003499 return;
3500 }
3501
3502 // Determine the implicit conversion sequences for each of the
3503 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003504 Candidate.Conversions.resize(NumArgs);
3505 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3506 if (ArgIdx < NumArgsInProto) {
3507 // (C++ 13.3.2p3): for F to be a viable function, there shall
3508 // exist for each argument an implicit conversion sequence
3509 // (13.3.3.1) that converts that argument to the corresponding
3510 // parameter of F.
3511 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003512 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003513 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003514 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003515 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003516 if (Candidate.Conversions[ArgIdx].isBad()) {
3517 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003518 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003519 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003520 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003521 } else {
3522 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3523 // argument for which there is no corresponding parameter is
3524 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003525 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003526 }
3527 }
3528}
3529
Douglas Gregor063daf62009-03-13 18:40:31 +00003530/// \brief Add all of the function declarations in the given function set to
3531/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003532void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003533 Expr **Args, unsigned NumArgs,
3534 OverloadCandidateSet& CandidateSet,
3535 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003536 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003537 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3538 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003539 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003540 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003541 cast<CXXMethodDecl>(FD)->getParent(),
3542 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003543 CandidateSet, SuppressUserConversions);
3544 else
John McCall9aa472c2010-03-19 07:35:19 +00003545 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003546 SuppressUserConversions);
3547 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003548 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003549 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3550 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003551 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003552 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003553 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00003554 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003555 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003556 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003557 else
John McCall9aa472c2010-03-19 07:35:19 +00003558 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003559 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003560 Args, NumArgs, CandidateSet,
3561 SuppressUserConversions);
3562 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003563 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003564}
3565
John McCall314be4e2009-11-17 07:50:12 +00003566/// AddMethodCandidate - Adds a named decl (which is some kind of
3567/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003568void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003569 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00003570 Expr **Args, unsigned NumArgs,
3571 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003572 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003573 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003574 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003575
3576 if (isa<UsingShadowDecl>(Decl))
3577 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3578
3579 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3580 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3581 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003582 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3583 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00003584 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003585 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003586 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003587 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003588 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00003589 ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003590 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003591 }
3592}
3593
Douglas Gregor96176b32008-11-18 23:14:02 +00003594/// AddMethodCandidate - Adds the given C++ member function to the set
3595/// of candidate functions, using the given function call arguments
3596/// and the object argument (@c Object). For example, in a call
3597/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3598/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3599/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003600/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003601void
John McCall9aa472c2010-03-19 07:35:19 +00003602Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003603 CXXRecordDecl *ActingContext, QualType ObjectType,
3604 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003605 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003606 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003607 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003608 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003609 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003610 assert(!isa<CXXConstructorDecl>(Method) &&
3611 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003612
Douglas Gregor3f396022009-09-28 04:47:19 +00003613 if (!CandidateSet.isNewCandidate(Method))
3614 return;
3615
Douglas Gregor7edfb692009-11-23 12:27:39 +00003616 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003617 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003618
Douglas Gregor96176b32008-11-18 23:14:02 +00003619 // Add this candidate
3620 CandidateSet.push_back(OverloadCandidate());
3621 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003622 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003623 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003624 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003625 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003626
3627 unsigned NumArgsInProto = Proto->getNumArgs();
3628
3629 // (C++ 13.3.2p2): A candidate function having fewer than m
3630 // parameters is viable only if it has an ellipsis in its parameter
3631 // list (8.3.5).
3632 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3633 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003634 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003635 return;
3636 }
3637
3638 // (C++ 13.3.2p2): A candidate function having more than m parameters
3639 // is viable only if the (m+1)st parameter has a default argument
3640 // (8.3.6). For the purposes of overload resolution, the
3641 // parameter list is truncated on the right, so that there are
3642 // exactly m parameters.
3643 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3644 if (NumArgs < MinRequiredArgs) {
3645 // Not enough arguments.
3646 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003647 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003648 return;
3649 }
3650
3651 Candidate.Viable = true;
3652 Candidate.Conversions.resize(NumArgs + 1);
3653
John McCall701c89e2009-12-03 04:06:58 +00003654 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003655 // The implicit object argument is ignored.
3656 Candidate.IgnoreObjectArgument = true;
3657 else {
3658 // Determine the implicit conversion sequence for the object
3659 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003660 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003661 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3662 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003663 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003664 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003665 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003666 return;
3667 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003668 }
3669
3670 // Determine the implicit conversion sequences for each of the
3671 // arguments.
3672 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3673 if (ArgIdx < NumArgsInProto) {
3674 // (C++ 13.3.2p3): for F to be a viable function, there shall
3675 // exist for each argument an implicit conversion sequence
3676 // (13.3.3.1) that converts that argument to the corresponding
3677 // parameter of F.
3678 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003679 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003680 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003681 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003682 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003683 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003684 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003685 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003686 break;
3687 }
3688 } else {
3689 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3690 // argument for which there is no corresponding parameter is
3691 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003692 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003693 }
3694 }
3695}
Douglas Gregora9333192010-05-08 17:41:32 +00003696
Douglas Gregor6b906862009-08-21 00:16:32 +00003697/// \brief Add a C++ member function template as a candidate to the candidate
3698/// set, using template argument deduction to produce an appropriate member
3699/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003700void
Douglas Gregor6b906862009-08-21 00:16:32 +00003701Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003702 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003703 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003704 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003705 QualType ObjectType,
3706 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003707 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003708 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003709 if (!CandidateSet.isNewCandidate(MethodTmpl))
3710 return;
3711
Douglas Gregor6b906862009-08-21 00:16:32 +00003712 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003713 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003714 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003715 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003716 // candidate functions in the usual way.113) A given name can refer to one
3717 // or more function templates and also to a set of overloaded non-template
3718 // functions. In such a case, the candidate functions generated from each
3719 // function template are combined with the set of non-template candidate
3720 // functions.
John McCall5769d612010-02-08 23:07:23 +00003721 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003722 FunctionDecl *Specialization = 0;
3723 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003724 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003725 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003726 CandidateSet.push_back(OverloadCandidate());
3727 OverloadCandidate &Candidate = CandidateSet.back();
3728 Candidate.FoundDecl = FoundDecl;
3729 Candidate.Function = MethodTmpl->getTemplatedDecl();
3730 Candidate.Viable = false;
3731 Candidate.FailureKind = ovl_fail_bad_deduction;
3732 Candidate.IsSurrogate = false;
3733 Candidate.IgnoreObjectArgument = false;
3734 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3735 Info);
3736 return;
3737 }
Mike Stump1eb44332009-09-09 15:08:12 +00003738
Douglas Gregor6b906862009-08-21 00:16:32 +00003739 // Add the function template specialization produced by template argument
3740 // deduction as a candidate.
3741 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003742 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003743 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003744 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003745 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003746 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003747}
3748
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003749/// \brief Add a C++ function template specialization as a candidate
3750/// in the candidate set, using template argument deduction to produce
3751/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003752void
Douglas Gregore53060f2009-06-25 22:08:12 +00003753Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003754 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003755 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003756 Expr **Args, unsigned NumArgs,
3757 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003758 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003759 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3760 return;
3761
Douglas Gregore53060f2009-06-25 22:08:12 +00003762 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003763 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003764 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003765 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003766 // candidate functions in the usual way.113) A given name can refer to one
3767 // or more function templates and also to a set of overloaded non-template
3768 // functions. In such a case, the candidate functions generated from each
3769 // function template are combined with the set of non-template candidate
3770 // functions.
John McCall5769d612010-02-08 23:07:23 +00003771 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003772 FunctionDecl *Specialization = 0;
3773 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003774 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003775 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003776 CandidateSet.push_back(OverloadCandidate());
3777 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003778 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003779 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3780 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003781 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003782 Candidate.IsSurrogate = false;
3783 Candidate.IgnoreObjectArgument = false;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003784 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3785 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003786 return;
3787 }
Mike Stump1eb44332009-09-09 15:08:12 +00003788
Douglas Gregore53060f2009-06-25 22:08:12 +00003789 // Add the function template specialization produced by template argument
3790 // deduction as a candidate.
3791 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003792 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003793 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003794}
Mike Stump1eb44332009-09-09 15:08:12 +00003795
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003796/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003797/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003798/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003799/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003800/// (which may or may not be the same type as the type that the
3801/// conversion function produces).
3802void
3803Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003804 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003805 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003806 Expr *From, QualType ToType,
3807 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003808 assert(!Conversion->getDescribedFunctionTemplate() &&
3809 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003810 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003811 if (!CandidateSet.isNewCandidate(Conversion))
3812 return;
3813
Douglas Gregor7edfb692009-11-23 12:27:39 +00003814 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003815 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003816
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003817 // Add this candidate
3818 CandidateSet.push_back(OverloadCandidate());
3819 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003820 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003821 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003822 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003823 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003824 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003825 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003826 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003827 Candidate.Viable = true;
3828 Candidate.Conversions.resize(1);
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003829
Douglas Gregorbca39322010-08-19 15:37:02 +00003830 // C++ [over.match.funcs]p4:
3831 // For conversion functions, the function is considered to be a member of
3832 // the class of the implicit implied object argument for the purpose of
3833 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003834 //
3835 // Determine the implicit conversion sequence for the implicit
3836 // object parameter.
3837 QualType ImplicitParamType = From->getType();
3838 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3839 ImplicitParamType = FromPtrType->getPointeeType();
3840 CXXRecordDecl *ConversionContext
3841 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3842
3843 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003844 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003845 ConversionContext);
3846
John McCall1d318332010-01-12 00:44:57 +00003847 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003848 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003849 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003850 return;
3851 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003852
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003853 // We won't go through a user-define type conversion function to convert a
3854 // derived to base as such conversions are given Conversion Rank. They only
3855 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3856 QualType FromCanon
3857 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3858 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3859 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3860 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003861 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003862 return;
3863 }
3864
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003865 // To determine what the conversion from the result of calling the
3866 // conversion function to the type we're eventually trying to
3867 // convert to (ToType), we need to synthesize a call to the
3868 // conversion function and attempt copy initialization from it. This
3869 // makes sure that we get the right semantics with respect to
3870 // lvalues/rvalues and the type. Fortunately, we can allocate this
3871 // call on the stack and we don't need its arguments to be
3872 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003873 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003874 From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00003875 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3876 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00003877 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00003878 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00003879
3880 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003881 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3882 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00003883 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor63982352010-07-13 18:40:04 +00003884 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003885 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003886 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00003887 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003888 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003889 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003890
John McCall1d318332010-01-12 00:44:57 +00003891 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003892 case ImplicitConversionSequence::StandardConversion:
3893 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003894
3895 // C++ [over.ics.user]p3:
3896 // If the user-defined conversion is specified by a specialization of a
3897 // conversion function template, the second standard conversion sequence
3898 // shall have exact match rank.
3899 if (Conversion->getPrimaryTemplate() &&
3900 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3901 Candidate.Viable = false;
3902 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3903 }
3904
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003905 break;
3906
3907 case ImplicitConversionSequence::BadConversion:
3908 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003909 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003910 break;
3911
3912 default:
Mike Stump1eb44332009-09-09 15:08:12 +00003913 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003914 "Can only end up with a standard conversion sequence or failure");
3915 }
3916}
3917
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003918/// \brief Adds a conversion function template specialization
3919/// candidate to the overload set, using template argument deduction
3920/// to deduce the template arguments of the conversion function
3921/// template from the type that we are converting to (C++
3922/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00003923void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003924Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003925 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003926 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003927 Expr *From, QualType ToType,
3928 OverloadCandidateSet &CandidateSet) {
3929 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3930 "Only conversion function templates permitted here");
3931
Douglas Gregor3f396022009-09-28 04:47:19 +00003932 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3933 return;
3934
John McCall5769d612010-02-08 23:07:23 +00003935 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003936 CXXConversionDecl *Specialization = 0;
3937 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00003938 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003939 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003940 CandidateSet.push_back(OverloadCandidate());
3941 OverloadCandidate &Candidate = CandidateSet.back();
3942 Candidate.FoundDecl = FoundDecl;
3943 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3944 Candidate.Viable = false;
3945 Candidate.FailureKind = ovl_fail_bad_deduction;
3946 Candidate.IsSurrogate = false;
3947 Candidate.IgnoreObjectArgument = false;
3948 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3949 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003950 return;
3951 }
Mike Stump1eb44332009-09-09 15:08:12 +00003952
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003953 // Add the conversion function template specialization produced by
3954 // template argument deduction as a candidate.
3955 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003956 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00003957 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003958}
3959
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003960/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3961/// converts the given @c Object to a function pointer via the
3962/// conversion function @c Conversion, and then attempts to call it
3963/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3964/// the type of function that we'll eventually be calling.
3965void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003966 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003967 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00003968 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00003969 QualType ObjectType,
3970 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003971 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003972 if (!CandidateSet.isNewCandidate(Conversion))
3973 return;
3974
Douglas Gregor7edfb692009-11-23 12:27:39 +00003975 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003976 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003977
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003978 CandidateSet.push_back(OverloadCandidate());
3979 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003980 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003981 Candidate.Function = 0;
3982 Candidate.Surrogate = Conversion;
3983 Candidate.Viable = true;
3984 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003985 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003986 Candidate.Conversions.resize(NumArgs + 1);
3987
3988 // Determine the implicit conversion sequence for the implicit
3989 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003990 ImplicitConversionSequence ObjectInit
John McCall120d63c2010-08-24 20:38:10 +00003991 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
3992 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003993 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003994 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003995 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00003996 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003997 return;
3998 }
3999
4000 // The first conversion is actually a user-defined conversion whose
4001 // first conversion is ObjectInit's standard conversion (which is
4002 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00004003 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004004 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004005 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004006 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00004007 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004008 = Candidate.Conversions[0].UserDefined.Before;
4009 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4010
Mike Stump1eb44332009-09-09 15:08:12 +00004011 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004012 unsigned NumArgsInProto = Proto->getNumArgs();
4013
4014 // (C++ 13.3.2p2): A candidate function having fewer than m
4015 // parameters is viable only if it has an ellipsis in its parameter
4016 // list (8.3.5).
4017 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4018 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004019 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004020 return;
4021 }
4022
4023 // Function types don't have any default arguments, so just check if
4024 // we have enough arguments.
4025 if (NumArgs < NumArgsInProto) {
4026 // Not enough arguments.
4027 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004028 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004029 return;
4030 }
4031
4032 // Determine the implicit conversion sequences for each of the
4033 // arguments.
4034 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4035 if (ArgIdx < NumArgsInProto) {
4036 // (C++ 13.3.2p3): for F to be a viable function, there shall
4037 // exist for each argument an implicit conversion sequence
4038 // (13.3.3.1) that converts that argument to the corresponding
4039 // parameter of F.
4040 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004041 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004042 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004043 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004044 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00004045 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004046 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004047 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004048 break;
4049 }
4050 } else {
4051 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4052 // argument for which there is no corresponding parameter is
4053 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004054 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004055 }
4056 }
4057}
4058
Douglas Gregor063daf62009-03-13 18:40:31 +00004059/// \brief Add overload candidates for overloaded operators that are
4060/// member functions.
4061///
4062/// Add the overloaded operator candidates that are member functions
4063/// for the operator Op that was used in an operator expression such
4064/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4065/// CandidateSet will store the added overload candidates. (C++
4066/// [over.match.oper]).
4067void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4068 SourceLocation OpLoc,
4069 Expr **Args, unsigned NumArgs,
4070 OverloadCandidateSet& CandidateSet,
4071 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004072 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4073
4074 // C++ [over.match.oper]p3:
4075 // For a unary operator @ with an operand of a type whose
4076 // cv-unqualified version is T1, and for a binary operator @ with
4077 // a left operand of a type whose cv-unqualified version is T1 and
4078 // a right operand of a type whose cv-unqualified version is T2,
4079 // three sets of candidate functions, designated member
4080 // candidates, non-member candidates and built-in candidates, are
4081 // constructed as follows:
4082 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00004083
4084 // -- If T1 is a class type, the set of member candidates is the
4085 // result of the qualified lookup of T1::operator@
4086 // (13.3.1.1.1); otherwise, the set of member candidates is
4087 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00004088 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004089 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004090 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004091 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004092
John McCalla24dc2e2009-11-17 02:14:36 +00004093 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4094 LookupQualifiedName(Operators, T1Rec->getDecl());
4095 Operators.suppressDiagnostics();
4096
Mike Stump1eb44332009-09-09 15:08:12 +00004097 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004098 OperEnd = Operators.end();
4099 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00004100 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00004101 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00004102 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00004103 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00004104 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004105}
4106
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004107/// AddBuiltinCandidate - Add a candidate for a built-in
4108/// operator. ResultTy and ParamTys are the result and parameter types
4109/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004110/// arguments being passed to the candidate. IsAssignmentOperator
4111/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004112/// operator. NumContextualBoolArguments is the number of arguments
4113/// (at the beginning of the argument list) that will be contextually
4114/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00004115void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004116 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004117 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004118 bool IsAssignmentOperator,
4119 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00004120 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004121 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004122
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004123 // Add this candidate
4124 CandidateSet.push_back(OverloadCandidate());
4125 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004126 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004127 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004128 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004129 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004130 Candidate.BuiltinTypes.ResultTy = ResultTy;
4131 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4132 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4133
4134 // Determine the implicit conversion sequences for each of the
4135 // arguments.
4136 Candidate.Viable = true;
4137 Candidate.Conversions.resize(NumArgs);
4138 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004139 // C++ [over.match.oper]p4:
4140 // For the built-in assignment operators, conversions of the
4141 // left operand are restricted as follows:
4142 // -- no temporaries are introduced to hold the left operand, and
4143 // -- no user-defined conversions are applied to the left
4144 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00004145 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004146 //
4147 // We block these conversions by turning off user-defined
4148 // conversions, since that is the only way that initialization of
4149 // a reference to a non-class type can occur from something that
4150 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004151 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004152 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004153 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00004154 Candidate.Conversions[ArgIdx]
4155 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004156 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004157 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004158 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004159 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004160 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004161 }
John McCall1d318332010-01-12 00:44:57 +00004162 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004163 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004164 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004165 break;
4166 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004167 }
4168}
4169
4170/// BuiltinCandidateTypeSet - A set of types that will be used for the
4171/// candidate operator functions for built-in operators (C++
4172/// [over.built]). The types are separated into pointer types and
4173/// enumeration types.
4174class BuiltinCandidateTypeSet {
4175 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004176 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004177
4178 /// PointerTypes - The set of pointer types that will be used in the
4179 /// built-in candidates.
4180 TypeSet PointerTypes;
4181
Sebastian Redl78eb8742009-04-19 21:53:20 +00004182 /// MemberPointerTypes - The set of member pointer types that will be
4183 /// used in the built-in candidates.
4184 TypeSet MemberPointerTypes;
4185
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004186 /// EnumerationTypes - The set of enumeration types that will be
4187 /// used in the built-in candidates.
4188 TypeSet EnumerationTypes;
4189
Douglas Gregor26bcf672010-05-19 03:21:00 +00004190 /// \brief The set of vector types that will be used in the built-in
4191 /// candidates.
4192 TypeSet VectorTypes;
4193
Douglas Gregor5842ba92009-08-24 15:23:48 +00004194 /// Sema - The semantic analysis instance where we are building the
4195 /// candidate type set.
4196 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004197
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004198 /// Context - The AST context in which we will build the type sets.
4199 ASTContext &Context;
4200
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004201 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4202 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00004203 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004204
4205public:
4206 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004207 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004208
Mike Stump1eb44332009-09-09 15:08:12 +00004209 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00004210 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004211
Douglas Gregor573d9c32009-10-21 23:19:44 +00004212 void AddTypesConvertedFrom(QualType Ty,
4213 SourceLocation Loc,
4214 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004215 bool AllowExplicitConversions,
4216 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004217
4218 /// pointer_begin - First pointer type found;
4219 iterator pointer_begin() { return PointerTypes.begin(); }
4220
Sebastian Redl78eb8742009-04-19 21:53:20 +00004221 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004222 iterator pointer_end() { return PointerTypes.end(); }
4223
Sebastian Redl78eb8742009-04-19 21:53:20 +00004224 /// member_pointer_begin - First member pointer type found;
4225 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4226
4227 /// member_pointer_end - Past the last member pointer type found;
4228 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4229
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004230 /// enumeration_begin - First enumeration type found;
4231 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4232
Sebastian Redl78eb8742009-04-19 21:53:20 +00004233 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004234 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004235
4236 iterator vector_begin() { return VectorTypes.begin(); }
4237 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004238};
4239
Sebastian Redl78eb8742009-04-19 21:53:20 +00004240/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004241/// the set of pointer types along with any more-qualified variants of
4242/// that type. For example, if @p Ty is "int const *", this routine
4243/// will add "int const *", "int const volatile *", "int const
4244/// restrict *", and "int const volatile restrict *" to the set of
4245/// pointer types. Returns true if the add of @p Ty itself succeeded,
4246/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004247///
4248/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004249bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00004250BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4251 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00004252
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004253 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004254 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004255 return false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004256
4257 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00004258 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004259 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004260 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004261 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004262 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004263 buildObjCPtr = true;
4264 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004265 else
4266 assert(false && "type was not a pointer type!");
4267 }
4268 else
4269 PointeeTy = PointerTy->getPointeeType();
4270
Sebastian Redla9efada2009-11-18 20:39:26 +00004271 // Don't add qualified variants of arrays. For one, they're not allowed
4272 // (the qualifier would sink to the element type), and for another, the
4273 // only overload situation where it matters is subscript or pointer +- int,
4274 // and those shouldn't have qualifier variants anyway.
4275 if (PointeeTy->isArrayType())
4276 return true;
John McCall0953e762009-09-24 19:53:00 +00004277 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00004278 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00004279 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004280 bool hasVolatile = VisibleQuals.hasVolatile();
4281 bool hasRestrict = VisibleQuals.hasRestrict();
4282
John McCall0953e762009-09-24 19:53:00 +00004283 // Iterate through all strict supersets of BaseCVR.
4284 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4285 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004286 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4287 // in the types.
4288 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4289 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00004290 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004291 if (!buildObjCPtr)
4292 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4293 else
4294 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004295 }
4296
4297 return true;
4298}
4299
Sebastian Redl78eb8742009-04-19 21:53:20 +00004300/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4301/// to the set of pointer types along with any more-qualified variants of
4302/// that type. For example, if @p Ty is "int const *", this routine
4303/// will add "int const *", "int const volatile *", "int const
4304/// restrict *", and "int const volatile restrict *" to the set of
4305/// pointer types. Returns true if the add of @p Ty itself succeeded,
4306/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004307///
4308/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004309bool
4310BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4311 QualType Ty) {
4312 // Insert this type.
4313 if (!MemberPointerTypes.insert(Ty))
4314 return false;
4315
John McCall0953e762009-09-24 19:53:00 +00004316 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4317 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00004318
John McCall0953e762009-09-24 19:53:00 +00004319 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004320 // Don't add qualified variants of arrays. For one, they're not allowed
4321 // (the qualifier would sink to the element type), and for another, the
4322 // only overload situation where it matters is subscript or pointer +- int,
4323 // and those shouldn't have qualifier variants anyway.
4324 if (PointeeTy->isArrayType())
4325 return true;
John McCall0953e762009-09-24 19:53:00 +00004326 const Type *ClassTy = PointerTy->getClass();
4327
4328 // Iterate through all strict supersets of the pointee type's CVR
4329 // qualifiers.
4330 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4331 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4332 if ((CVR | BaseCVR) != CVR) continue;
4333
4334 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4335 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00004336 }
4337
4338 return true;
4339}
4340
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004341/// AddTypesConvertedFrom - Add each of the types to which the type @p
4342/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00004343/// primarily interested in pointer types and enumeration types. We also
4344/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004345/// AllowUserConversions is true if we should look at the conversion
4346/// functions of a class type, and AllowExplicitConversions if we
4347/// should also include the explicit conversion functions of a class
4348/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004349void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004350BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004351 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004352 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004353 bool AllowExplicitConversions,
4354 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004355 // Only deal with canonical types.
4356 Ty = Context.getCanonicalType(Ty);
4357
4358 // Look through reference types; they aren't part of the type of an
4359 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004360 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004361 Ty = RefTy->getPointeeType();
4362
4363 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004364 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004365
Sebastian Redla65b5512009-11-05 16:36:20 +00004366 // If we're dealing with an array type, decay to the pointer.
4367 if (Ty->isArrayType())
4368 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004369 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4370 PointerTypes.insert(Ty);
4371 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004372 // Insert our type, and its more-qualified variants, into the set
4373 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004374 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004375 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00004376 } else if (Ty->isMemberPointerType()) {
4377 // Member pointers are far easier, since the pointee can't be converted.
4378 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4379 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004380 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00004381 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004382 } else if (Ty->isVectorType()) {
4383 VectorTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004384 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004385 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004386 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00004387 // No conversion functions in incomplete types.
4388 return;
4389 }
Mike Stump1eb44332009-09-09 15:08:12 +00004390
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004391 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00004392 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00004393 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004394 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004395 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004396 NamedDecl *D = I.getDecl();
4397 if (isa<UsingShadowDecl>(D))
4398 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004399
Mike Stump1eb44332009-09-09 15:08:12 +00004400 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004401 // about which builtin types we can convert to.
John McCall32daa422010-03-31 01:36:47 +00004402 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004403 continue;
4404
John McCall32daa422010-03-31 01:36:47 +00004405 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004406 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004407 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004408 VisibleQuals);
4409 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004410 }
4411 }
4412 }
4413}
4414
Douglas Gregor19b7b152009-08-24 13:43:27 +00004415/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4416/// the volatile- and non-volatile-qualified assignment operators for the
4417/// given type to the candidate set.
4418static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4419 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004420 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004421 unsigned NumArgs,
4422 OverloadCandidateSet &CandidateSet) {
4423 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004424
Douglas Gregor19b7b152009-08-24 13:43:27 +00004425 // T& operator=(T&, T)
4426 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4427 ParamTypes[1] = T;
4428 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4429 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004430
Douglas Gregor19b7b152009-08-24 13:43:27 +00004431 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4432 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004433 ParamTypes[0]
4434 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004435 ParamTypes[1] = T;
4436 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004437 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004438 }
4439}
Mike Stump1eb44332009-09-09 15:08:12 +00004440
Sebastian Redl9994a342009-10-25 17:03:50 +00004441/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4442/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004443static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4444 Qualifiers VRQuals;
4445 const RecordType *TyRec;
4446 if (const MemberPointerType *RHSMPType =
4447 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004448 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004449 else
4450 TyRec = ArgExpr->getType()->getAs<RecordType>();
4451 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004452 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004453 VRQuals.addVolatile();
4454 VRQuals.addRestrict();
4455 return VRQuals;
4456 }
4457
4458 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004459 if (!ClassDecl->hasDefinition())
4460 return VRQuals;
4461
John McCalleec51cf2010-01-20 00:46:10 +00004462 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004463 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004464
John McCalleec51cf2010-01-20 00:46:10 +00004465 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004466 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004467 NamedDecl *D = I.getDecl();
4468 if (isa<UsingShadowDecl>(D))
4469 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4470 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004471 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4472 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4473 CanTy = ResTypeRef->getPointeeType();
4474 // Need to go down the pointer/mempointer chain and add qualifiers
4475 // as see them.
4476 bool done = false;
4477 while (!done) {
4478 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4479 CanTy = ResTypePtr->getPointeeType();
4480 else if (const MemberPointerType *ResTypeMPtr =
4481 CanTy->getAs<MemberPointerType>())
4482 CanTy = ResTypeMPtr->getPointeeType();
4483 else
4484 done = true;
4485 if (CanTy.isVolatileQualified())
4486 VRQuals.addVolatile();
4487 if (CanTy.isRestrictQualified())
4488 VRQuals.addRestrict();
4489 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4490 return VRQuals;
4491 }
4492 }
4493 }
4494 return VRQuals;
4495}
4496
Douglas Gregor74253732008-11-19 15:42:04 +00004497/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4498/// operator overloads to the candidate set (C++ [over.built]), based
4499/// on the operator @p Op and the arguments given. For example, if the
4500/// operator is a binary '+', this routine might add "int
4501/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004502void
Mike Stump1eb44332009-09-09 15:08:12 +00004503Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004504 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00004505 Expr **Args, unsigned NumArgs,
4506 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004507 // The set of "promoted arithmetic types", which are the arithmetic
4508 // types are that preserved by promotion (C++ [over.built]p2). Note
4509 // that the first few of these types are the promoted integral
4510 // types; these types need to be first.
4511 // FIXME: What about complex?
4512 const unsigned FirstIntegralType = 0;
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00004513 const unsigned LastIntegralType = 15;
4514 const unsigned FirstPromotedIntegralType = 9,
4515 LastPromotedIntegralType = 15;
4516 const unsigned FirstPromotedArithmeticType = 9,
4517 LastPromotedArithmeticType = 18;
4518 const unsigned NumArithmeticTypes = 18;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004519 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00004520 Context.BoolTy, Context.CharTy, Context.WCharTy,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00004521 Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004522 Context.SignedCharTy, Context.ShortTy,
4523 Context.UnsignedCharTy, Context.UnsignedShortTy,
4524 Context.IntTy, Context.LongTy, Context.LongLongTy,
4525 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4526 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4527 };
Douglas Gregor652371a2009-10-21 22:01:30 +00004528 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4529 "Invalid first promoted integral type");
4530 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4531 == Context.UnsignedLongLongTy &&
4532 "Invalid last promoted integral type");
4533 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4534 "Invalid first promoted arithmetic type");
4535 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4536 == Context.LongDoubleTy &&
4537 "Invalid last promoted arithmetic type");
4538
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004539 // Find all of the types that the arguments can convert to, but only
4540 // if the operator we're looking at has built-in operator candidates
4541 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004542 Qualifiers VisibleTypeConversionsQuals;
4543 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004544 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4545 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4546
Douglas Gregorfec56e72010-11-03 17:00:07 +00004547 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
4548 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4549 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
4550 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4551 OpLoc,
4552 true,
4553 (Op == OO_Exclaim ||
4554 Op == OO_AmpAmp ||
4555 Op == OO_PipePipe),
4556 VisibleTypeConversionsQuals);
4557 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004558
Douglas Gregor661b4932010-09-12 04:28:07 +00004559 // C++ [over.built]p1:
4560 // If there is a user-written candidate with the same name and parameter
4561 // types as a built-in candidate operator function, the built-in operator
4562 // function is hidden and is not included in the set of candidate functions.
4563 //
4564 // The text is actually in a note, but if we don't implement it then we end
4565 // up with ambiguities when the user provides an overloaded operator for
4566 // an enumeration type. Note that only enumeration types have this problem,
4567 // so we track which enumeration types we've seen operators for.
4568 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4569 UserDefinedBinaryOperators;
4570
Douglas Gregorfec56e72010-11-03 17:00:07 +00004571 /// Set of (canonical) types that we've already handled.
4572 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4573
4574 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4575 if (CandidateTypes[ArgIdx].enumeration_begin()
4576 != CandidateTypes[ArgIdx].enumeration_end()) {
4577 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
4578 CEnd = CandidateSet.end();
4579 C != CEnd; ++C) {
4580 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
4581 continue;
4582
4583 // Check if the first parameter is of enumeration type.
4584 QualType FirstParamType
4585 = C->Function->getParamDecl(0)->getType().getUnqualifiedType();
4586 if (!FirstParamType->isEnumeralType())
4587 continue;
4588
4589 // Check if the second parameter is of enumeration type.
4590 QualType SecondParamType
4591 = C->Function->getParamDecl(1)->getType().getUnqualifiedType();
4592 if (!SecondParamType->isEnumeralType())
4593 continue;
Douglas Gregor661b4932010-09-12 04:28:07 +00004594
Douglas Gregorfec56e72010-11-03 17:00:07 +00004595 // Add this operator to the set of known user-defined operators.
4596 UserDefinedBinaryOperators.insert(
4597 std::make_pair(Context.getCanonicalType(FirstParamType),
4598 Context.getCanonicalType(SecondParamType)));
4599 }
Douglas Gregor661b4932010-09-12 04:28:07 +00004600 }
4601 }
4602
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004603 bool isComparison = false;
4604 switch (Op) {
4605 case OO_None:
4606 case NUM_OVERLOADED_OPERATORS:
4607 assert(false && "Expected an overloaded operator");
4608 break;
4609
Douglas Gregor74253732008-11-19 15:42:04 +00004610 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00004611 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00004612 goto UnaryStar;
4613 else
4614 goto BinaryStar;
4615 break;
4616
4617 case OO_Plus: // '+' is either unary or binary
4618 if (NumArgs == 1)
4619 goto UnaryPlus;
4620 else
4621 goto BinaryPlus;
4622 break;
4623
4624 case OO_Minus: // '-' is either unary or binary
4625 if (NumArgs == 1)
4626 goto UnaryMinus;
4627 else
4628 goto BinaryMinus;
4629 break;
4630
4631 case OO_Amp: // '&' is either unary or binary
4632 if (NumArgs == 1)
4633 goto UnaryAmp;
4634 else
4635 goto BinaryAmp;
4636
4637 case OO_PlusPlus:
4638 case OO_MinusMinus:
4639 // C++ [over.built]p3:
4640 //
4641 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4642 // is either volatile or empty, there exist candidate operator
4643 // functions of the form
4644 //
4645 // VQ T& operator++(VQ T&);
4646 // T operator++(VQ T&, int);
4647 //
4648 // C++ [over.built]p4:
4649 //
4650 // For every pair (T, VQ), where T is an arithmetic type other
4651 // than bool, and VQ is either volatile or empty, there exist
4652 // candidate operator functions of the form
4653 //
4654 // VQ T& operator--(VQ T&);
4655 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00004656 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00004657 Arith < NumArithmeticTypes; ++Arith) {
4658 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00004659 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004660 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00004661
4662 // Non-volatile version.
4663 if (NumArgs == 1)
4664 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4665 else
4666 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004667 // heuristic to reduce number of builtin candidates in the set.
4668 // Add volatile version only if there are conversions to a volatile type.
4669 if (VisibleTypeConversionsQuals.hasVolatile()) {
4670 // Volatile version
4671 ParamTypes[0]
4672 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4673 if (NumArgs == 1)
4674 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4675 else
4676 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4677 }
Douglas Gregor74253732008-11-19 15:42:04 +00004678 }
4679
4680 // C++ [over.built]p5:
4681 //
4682 // For every pair (T, VQ), where T is a cv-qualified or
4683 // cv-unqualified object type, and VQ is either volatile or
4684 // empty, there exist candidate operator functions of the form
4685 //
4686 // T*VQ& operator++(T*VQ&);
4687 // T*VQ& operator--(T*VQ&);
4688 // T* operator++(T*VQ&, int);
4689 // T* operator--(T*VQ&, int);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004690 for (BuiltinCandidateTypeSet::iterator
4691 Ptr = CandidateTypes[0].pointer_begin(),
4692 PtrEnd = CandidateTypes[0].pointer_end();
4693 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor74253732008-11-19 15:42:04 +00004694 // Skip pointer types that aren't pointers to object types.
Eli Friedman13578692010-08-05 02:49:48 +00004695 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00004696 continue;
4697
Mike Stump1eb44332009-09-09 15:08:12 +00004698 QualType ParamTypes[2] = {
4699 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00004700 };
Mike Stump1eb44332009-09-09 15:08:12 +00004701
Douglas Gregor74253732008-11-19 15:42:04 +00004702 // Without volatile
4703 if (NumArgs == 1)
4704 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4705 else
4706 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4707
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004708 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4709 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004710 // With volatile
John McCall0953e762009-09-24 19:53:00 +00004711 ParamTypes[0]
4712 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00004713 if (NumArgs == 1)
4714 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4715 else
4716 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4717 }
4718 }
4719 break;
4720
4721 UnaryStar:
4722 // C++ [over.built]p6:
4723 // For every cv-qualified or cv-unqualified object type T, there
4724 // exist candidate operator functions of the form
4725 //
4726 // T& operator*(T*);
4727 //
4728 // C++ [over.built]p7:
4729 // For every function type T, there exist candidate operator
4730 // functions of the form
4731 // T& operator*(T*);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004732 for (BuiltinCandidateTypeSet::iterator
4733 Ptr = CandidateTypes[0].pointer_begin(),
4734 PtrEnd = CandidateTypes[0].pointer_end();
4735 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor74253732008-11-19 15:42:04 +00004736 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00004737 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004738 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00004739 &ParamTy, Args, 1, CandidateSet);
4740 }
4741 break;
4742
4743 UnaryPlus:
4744 // C++ [over.built]p8:
4745 // For every type T, there exist candidate operator functions of
4746 // the form
4747 //
4748 // T* operator+(T*);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004749 for (BuiltinCandidateTypeSet::iterator
4750 Ptr = CandidateTypes[0].pointer_begin(),
4751 PtrEnd = CandidateTypes[0].pointer_end();
4752 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor74253732008-11-19 15:42:04 +00004753 QualType ParamTy = *Ptr;
4754 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4755 }
Mike Stump1eb44332009-09-09 15:08:12 +00004756
Douglas Gregor74253732008-11-19 15:42:04 +00004757 // Fall through
4758
4759 UnaryMinus:
4760 // C++ [over.built]p9:
4761 // For every promoted arithmetic type T, there exist candidate
4762 // operator functions of the form
4763 //
4764 // T operator+(T);
4765 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004766 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00004767 Arith < LastPromotedArithmeticType; ++Arith) {
4768 QualType ArithTy = ArithmeticTypes[Arith];
4769 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4770 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004771
4772 // Extension: We also add these operators for vector types.
Douglas Gregorfec56e72010-11-03 17:00:07 +00004773 for (BuiltinCandidateTypeSet::iterator
4774 Vec = CandidateTypes[0].vector_begin(),
4775 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00004776 Vec != VecEnd; ++Vec) {
4777 QualType VecTy = *Vec;
4778 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4779 }
Douglas Gregor74253732008-11-19 15:42:04 +00004780 break;
4781
4782 case OO_Tilde:
4783 // C++ [over.built]p10:
4784 // For every promoted integral type T, there exist candidate
4785 // operator functions of the form
4786 //
4787 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004788 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00004789 Int < LastPromotedIntegralType; ++Int) {
4790 QualType IntTy = ArithmeticTypes[Int];
4791 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4792 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004793
4794 // Extension: We also add this operator for vector types.
Douglas Gregorfec56e72010-11-03 17:00:07 +00004795 for (BuiltinCandidateTypeSet::iterator
4796 Vec = CandidateTypes[0].vector_begin(),
4797 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00004798 Vec != VecEnd; ++Vec) {
4799 QualType VecTy = *Vec;
4800 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4801 }
Douglas Gregor74253732008-11-19 15:42:04 +00004802 break;
4803
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004804 case OO_New:
4805 case OO_Delete:
4806 case OO_Array_New:
4807 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004808 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00004809 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004810 break;
4811
4812 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00004813 UnaryAmp:
4814 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004815 // C++ [over.match.oper]p3:
4816 // -- For the operator ',', the unary operator '&', or the
4817 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004818 break;
4819
Douglas Gregor19b7b152009-08-24 13:43:27 +00004820 case OO_EqualEqual:
4821 case OO_ExclaimEqual:
4822 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00004823 // For every pointer to member type T, there exist candidate operator
4824 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00004825 //
4826 // bool operator==(T,T);
4827 // bool operator!=(T,T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004828 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4829 for (BuiltinCandidateTypeSet::iterator
4830 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
4831 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
4832 MemPtr != MemPtrEnd;
4833 ++MemPtr) {
4834 // Don't add the same builtin candidate twice.
4835 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
4836 continue;
4837
4838 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4839 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4840 }
Douglas Gregor19b7b152009-08-24 13:43:27 +00004841 }
Douglas Gregorfec56e72010-11-03 17:00:07 +00004842 AddedTypes.clear();
4843
Douglas Gregor19b7b152009-08-24 13:43:27 +00004844 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00004845
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004846 case OO_Less:
4847 case OO_Greater:
4848 case OO_LessEqual:
4849 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004850 // C++ [over.built]p15:
4851 //
4852 // For every pointer or enumeration type T, there exist
4853 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004854 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004855 // bool operator<(T, T);
4856 // bool operator>(T, T);
4857 // bool operator<=(T, T);
4858 // bool operator>=(T, T);
4859 // bool operator==(T, T);
4860 // bool operator!=(T, T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004861 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4862 for (BuiltinCandidateTypeSet::iterator
4863 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
4864 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
4865 Ptr != PtrEnd; ++Ptr) {
4866 // Don't add the same builtin candidate twice.
4867 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
4868 continue;
4869
4870 QualType ParamTypes[2] = { *Ptr, *Ptr };
Douglas Gregor661b4932010-09-12 04:28:07 +00004871 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004872 }
4873 for (BuiltinCandidateTypeSet::iterator
4874 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
4875 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
4876 Enum != EnumEnd; ++Enum) {
4877 // Don't add the same builtin candidate twice.
4878 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
4879 continue;
4880
4881 QualType ParamTypes[2] = { *Enum, *Enum };
4882 CanQualType CanonType = Context.getCanonicalType(*Enum);
4883 if (!UserDefinedBinaryOperators.count(
4884 std::make_pair(CanonType, CanonType)))
4885 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4886 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004887 }
Douglas Gregorfec56e72010-11-03 17:00:07 +00004888 AddedTypes.clear();
4889
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004890 // Fall through.
4891 isComparison = true;
4892
Douglas Gregor74253732008-11-19 15:42:04 +00004893 BinaryPlus:
4894 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004895 if (!isComparison) {
4896 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4897
4898 // C++ [over.built]p13:
4899 //
4900 // For every cv-qualified or cv-unqualified object type T
4901 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004902 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004903 // T* operator+(T*, ptrdiff_t);
4904 // T& operator[](T*, ptrdiff_t); [BELOW]
4905 // T* operator-(T*, ptrdiff_t);
4906 // T* operator+(ptrdiff_t, T*);
4907 // T& operator[](ptrdiff_t, T*); [BELOW]
4908 //
4909 // C++ [over.built]p14:
4910 //
4911 // For every T, where T is a pointer to object type, there
4912 // exist candidate operator functions of the form
4913 //
4914 // ptrdiff_t operator-(T, T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004915 for (BuiltinCandidateTypeSet::iterator
4916 Ptr = CandidateTypes[0].pointer_begin(),
4917 PtrEnd = CandidateTypes[0].pointer_end();
4918 Ptr != PtrEnd; ++Ptr) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004919 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4920
4921 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4922 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4923
Douglas Gregorfec56e72010-11-03 17:00:07 +00004924 if (Op == OO_Minus) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004925 // ptrdiff_t operator-(T, T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004926 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
4927 continue;
4928
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004929 ParamTypes[1] = *Ptr;
4930 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4931 Args, 2, CandidateSet);
4932 }
4933 }
Douglas Gregorfec56e72010-11-03 17:00:07 +00004934
4935 for (BuiltinCandidateTypeSet::iterator
4936 Ptr = CandidateTypes[1].pointer_begin(),
4937 PtrEnd = CandidateTypes[1].pointer_end();
4938 Ptr != PtrEnd; ++Ptr) {
4939 if (Op == OO_Plus) {
4940 // T* operator+(ptrdiff_t, T*);
4941 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
4942 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4943 } else {
4944 // ptrdiff_t operator-(T, T);
4945 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
4946 continue;
4947
4948 QualType ParamTypes[2] = { *Ptr, *Ptr };
4949 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4950 Args, 2, CandidateSet);
4951 }
4952 }
4953
4954 AddedTypes.clear();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004955 }
4956 // Fall through
4957
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004958 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00004959 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004960 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004961 // C++ [over.built]p12:
4962 //
4963 // For every pair of promoted arithmetic types L and R, there
4964 // exist candidate operator functions of the form
4965 //
4966 // LR operator*(L, R);
4967 // LR operator/(L, R);
4968 // LR operator+(L, R);
4969 // LR operator-(L, R);
4970 // bool operator<(L, R);
4971 // bool operator>(L, R);
4972 // bool operator<=(L, R);
4973 // bool operator>=(L, R);
4974 // bool operator==(L, R);
4975 // bool operator!=(L, R);
4976 //
4977 // where LR is the result of the usual arithmetic conversions
4978 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004979 //
4980 // C++ [over.built]p24:
4981 //
4982 // For every pair of promoted arithmetic types L and R, there exist
4983 // candidate operator functions of the form
4984 //
4985 // LR operator?(bool, L, R);
4986 //
4987 // where LR is the result of the usual arithmetic conversions
4988 // between types L and R.
4989 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004990 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004991 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004992 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004993 Right < LastPromotedArithmeticType; ++Right) {
4994 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00004995 QualType Result
4996 = isComparison
4997 ? Context.BoolTy
4998 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004999 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5000 }
5001 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00005002
5003 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5004 // conditional operator for vector types.
Douglas Gregorfec56e72010-11-03 17:00:07 +00005005 for (BuiltinCandidateTypeSet::iterator
5006 Vec1 = CandidateTypes[0].vector_begin(),
5007 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005008 Vec1 != Vec1End; ++Vec1)
5009 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorfec56e72010-11-03 17:00:07 +00005010 Vec2 = CandidateTypes[1].vector_begin(),
5011 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005012 Vec2 != Vec2End; ++Vec2) {
5013 QualType LandR[2] = { *Vec1, *Vec2 };
5014 QualType Result;
5015 if (isComparison)
5016 Result = Context.BoolTy;
5017 else {
5018 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5019 Result = *Vec1;
5020 else
5021 Result = *Vec2;
5022 }
5023
5024 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5025 }
5026
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005027 break;
5028
5029 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00005030 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005031 case OO_Caret:
5032 case OO_Pipe:
5033 case OO_LessLess:
5034 case OO_GreaterGreater:
5035 // C++ [over.built]p17:
5036 //
5037 // For every pair of promoted integral types L and R, there
5038 // exist candidate operator functions of the form
5039 //
5040 // LR operator%(L, R);
5041 // LR operator&(L, R);
5042 // LR operator^(L, R);
5043 // LR operator|(L, R);
5044 // L operator<<(L, R);
5045 // L operator>>(L, R);
5046 //
5047 // where LR is the result of the usual arithmetic conversions
5048 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00005049 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005050 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005051 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005052 Right < LastPromotedIntegralType; ++Right) {
5053 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
5054 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5055 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00005056 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005057 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5058 }
5059 }
5060 break;
5061
5062 case OO_Equal:
5063 // C++ [over.built]p20:
5064 //
5065 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00005066 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005067 // empty, there exist candidate operator functions of the form
5068 //
5069 // VQ T& operator=(VQ T&, T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005070 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5071 for (BuiltinCandidateTypeSet::iterator
5072 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5073 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5074 Enum != EnumEnd; ++Enum) {
5075 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5076 continue;
5077
5078 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
5079 CandidateSet);
5080 }
5081
5082 for (BuiltinCandidateTypeSet::iterator
5083 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5084 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5085 MemPtr != MemPtrEnd; ++MemPtr) {
5086 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5087 continue;
5088
5089 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
5090 CandidateSet);
5091 }
5092 }
5093 AddedTypes.clear();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005094
5095 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005096
5097 case OO_PlusEqual:
5098 case OO_MinusEqual:
5099 // C++ [over.built]p19:
5100 //
5101 // For every pair (T, VQ), where T is any type and VQ is either
5102 // volatile or empty, there exist candidate operator functions
5103 // of the form
5104 //
5105 // T*VQ& operator=(T*VQ&, T*);
5106 //
5107 // C++ [over.built]p21:
5108 //
5109 // For every pair (T, VQ), where T is a cv-qualified or
5110 // cv-unqualified object type and VQ is either volatile or
5111 // empty, there exist candidate operator functions of the form
5112 //
5113 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5114 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005115 for (BuiltinCandidateTypeSet::iterator
5116 Ptr = CandidateTypes[0].pointer_begin(),
5117 PtrEnd = CandidateTypes[0].pointer_end();
5118 Ptr != PtrEnd; ++Ptr) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005119 QualType ParamTypes[2];
5120 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
5121
Douglas Gregorfec56e72010-11-03 17:00:07 +00005122 // If this is operator=, keep track of the builtin candidates we added.
5123 if (Op == OO_Equal)
5124 AddedTypes.insert(Context.getCanonicalType(*Ptr));
5125
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005126 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005127 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005128 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5129 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005130
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005131 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5132 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00005133 // volatile version
John McCall0953e762009-09-24 19:53:00 +00005134 ParamTypes[0]
5135 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005136 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5137 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00005138 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005139 }
Douglas Gregorfec56e72010-11-03 17:00:07 +00005140
5141 if (Op == OO_Equal) {
5142 for (BuiltinCandidateTypeSet::iterator
5143 Ptr = CandidateTypes[1].pointer_begin(),
5144 PtrEnd = CandidateTypes[1].pointer_end();
5145 Ptr != PtrEnd; ++Ptr) {
5146 // Make sure we don't add the same candidate twice.
5147 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5148 continue;
5149
5150 QualType ParamTypes[2] = { Context.getLValueReferenceType(*Ptr), *Ptr };
5151
5152 // non-volatile version
5153 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5154 /*IsAssigmentOperator=*/true);
5155
5156 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5157 VisibleTypeConversionsQuals.hasVolatile()) {
5158 // volatile version
5159 ParamTypes[0]
5160 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
5161 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5162 /*IsAssigmentOperator=*/true);
5163 }
5164 }
5165 AddedTypes.clear();
5166 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005167 // Fall through.
5168
5169 case OO_StarEqual:
5170 case OO_SlashEqual:
5171 // C++ [over.built]p18:
5172 //
5173 // For every triple (L, VQ, R), where L is an arithmetic type,
5174 // VQ is either volatile or empty, and R is a promoted
5175 // arithmetic type, there exist candidate operator functions of
5176 // the form
5177 //
5178 // VQ L& operator=(VQ L&, R);
5179 // VQ L& operator*=(VQ L&, R);
5180 // VQ L& operator/=(VQ L&, R);
5181 // VQ L& operator+=(VQ L&, R);
5182 // VQ L& operator-=(VQ L&, R);
5183 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005184 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005185 Right < LastPromotedArithmeticType; ++Right) {
5186 QualType ParamTypes[2];
5187 ParamTypes[1] = ArithmeticTypes[Right];
5188
5189 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005190 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005191 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5192 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005193
5194 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005195 if (VisibleTypeConversionsQuals.hasVolatile()) {
5196 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
5197 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5198 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5199 /*IsAssigmentOperator=*/Op == OO_Equal);
5200 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005201 }
5202 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00005203
5204 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
Douglas Gregorfec56e72010-11-03 17:00:07 +00005205 for (BuiltinCandidateTypeSet::iterator
5206 Vec1 = CandidateTypes[0].vector_begin(),
5207 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005208 Vec1 != Vec1End; ++Vec1)
5209 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorfec56e72010-11-03 17:00:07 +00005210 Vec2 = CandidateTypes[1].vector_begin(),
5211 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005212 Vec2 != Vec2End; ++Vec2) {
5213 QualType ParamTypes[2];
5214 ParamTypes[1] = *Vec2;
5215 // Add this built-in operator as a candidate (VQ is empty).
5216 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
5217 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5218 /*IsAssigmentOperator=*/Op == OO_Equal);
5219
5220 // Add this built-in operator as a candidate (VQ is 'volatile').
5221 if (VisibleTypeConversionsQuals.hasVolatile()) {
5222 ParamTypes[0] = Context.getVolatileType(*Vec1);
5223 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5224 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5225 /*IsAssigmentOperator=*/Op == OO_Equal);
5226 }
5227 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005228 break;
5229
5230 case OO_PercentEqual:
5231 case OO_LessLessEqual:
5232 case OO_GreaterGreaterEqual:
5233 case OO_AmpEqual:
5234 case OO_CaretEqual:
5235 case OO_PipeEqual:
5236 // C++ [over.built]p22:
5237 //
5238 // For every triple (L, VQ, R), where L is an integral type, VQ
5239 // is either volatile or empty, and R is a promoted integral
5240 // type, there exist candidate operator functions of the form
5241 //
5242 // VQ L& operator%=(VQ L&, R);
5243 // VQ L& operator<<=(VQ L&, R);
5244 // VQ L& operator>>=(VQ L&, R);
5245 // VQ L& operator&=(VQ L&, R);
5246 // VQ L& operator^=(VQ L&, R);
5247 // VQ L& operator|=(VQ L&, R);
5248 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005249 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005250 Right < LastPromotedIntegralType; ++Right) {
5251 QualType ParamTypes[2];
5252 ParamTypes[1] = ArithmeticTypes[Right];
5253
5254 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005255 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005256 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00005257 if (VisibleTypeConversionsQuals.hasVolatile()) {
5258 // Add this built-in operator as a candidate (VQ is 'volatile').
5259 ParamTypes[0] = ArithmeticTypes[Left];
5260 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5261 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5262 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5263 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005264 }
5265 }
5266 break;
5267
Douglas Gregor74253732008-11-19 15:42:04 +00005268 case OO_Exclaim: {
5269 // C++ [over.operator]p23:
5270 //
5271 // There also exist candidate operator functions of the form
5272 //
Mike Stump1eb44332009-09-09 15:08:12 +00005273 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00005274 // bool operator&&(bool, bool); [BELOW]
5275 // bool operator||(bool, bool); [BELOW]
5276 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005277 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5278 /*IsAssignmentOperator=*/false,
5279 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00005280 break;
5281 }
5282
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005283 case OO_AmpAmp:
5284 case OO_PipePipe: {
5285 // C++ [over.operator]p23:
5286 //
5287 // There also exist candidate operator functions of the form
5288 //
Douglas Gregor74253732008-11-19 15:42:04 +00005289 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005290 // bool operator&&(bool, bool);
5291 // bool operator||(bool, bool);
5292 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005293 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5294 /*IsAssignmentOperator=*/false,
5295 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005296 break;
5297 }
5298
5299 case OO_Subscript:
5300 // C++ [over.built]p13:
5301 //
5302 // For every cv-qualified or cv-unqualified object type T there
5303 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00005304 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005305 // T* operator+(T*, ptrdiff_t); [ABOVE]
5306 // T& operator[](T*, ptrdiff_t);
5307 // T* operator-(T*, ptrdiff_t); [ABOVE]
5308 // T* operator+(ptrdiff_t, T*); [ABOVE]
5309 // T& operator[](ptrdiff_t, T*);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005310 for (BuiltinCandidateTypeSet::iterator
5311 Ptr = CandidateTypes[0].pointer_begin(),
5312 PtrEnd = CandidateTypes[0].pointer_end();
5313 Ptr != PtrEnd; ++Ptr) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005314 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00005315 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005316 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005317
5318 // T& operator[](T*, ptrdiff_t)
5319 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005320 }
5321
5322 for (BuiltinCandidateTypeSet::iterator
5323 Ptr = CandidateTypes[1].pointer_begin(),
5324 PtrEnd = CandidateTypes[1].pointer_end();
5325 Ptr != PtrEnd; ++Ptr) {
5326 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
5327 QualType PointeeType = (*Ptr)->getPointeeType();
5328 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
5329
5330 // T& operator[](ptrdiff_t, T*)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005331 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005332 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005333 break;
5334
5335 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005336 // C++ [over.built]p11:
5337 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5338 // C1 is the same type as C2 or is a derived class of C2, T is an object
5339 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5340 // there exist candidate operator functions of the form
Douglas Gregorfec56e72010-11-03 17:00:07 +00005341 //
5342 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5343 //
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005344 // where CV12 is the union of CV1 and CV2.
5345 {
Douglas Gregorfec56e72010-11-03 17:00:07 +00005346 for (BuiltinCandidateTypeSet::iterator
5347 Ptr = CandidateTypes[0].pointer_begin(),
5348 PtrEnd = CandidateTypes[0].pointer_end();
5349 Ptr != PtrEnd; ++Ptr) {
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005350 QualType C1Ty = (*Ptr);
5351 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005352 QualifierCollector Q1;
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00005353 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5354 if (!isa<RecordType>(C1))
5355 continue;
5356 // heuristic to reduce number of builtin candidates in the set.
5357 // Add volatile/restrict version only if there are conversions to a
5358 // volatile/restrict type.
5359 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5360 continue;
5361 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5362 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005363 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorfec56e72010-11-03 17:00:07 +00005364 MemPtr = CandidateTypes[1].member_pointer_begin(),
5365 MemPtrEnd = CandidateTypes[1].member_pointer_end();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005366 MemPtr != MemPtrEnd; ++MemPtr) {
5367 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5368 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00005369 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005370 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5371 break;
5372 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5373 // build CV12 T&
5374 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005375 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5376 T.isVolatileQualified())
5377 continue;
5378 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5379 T.isRestrictQualified())
5380 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005381 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005382 QualType ResultTy = Context.getLValueReferenceType(T);
5383 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5384 }
5385 }
5386 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005387 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005388
5389 case OO_Conditional:
5390 // Note that we don't consider the first argument, since it has been
5391 // contextually converted to bool long ago. The candidates below are
5392 // therefore added as binary.
5393 //
Douglas Gregor5a1f97e2010-10-15 00:50:56 +00005394 // C++ [over.built]p25:
5395 // For every type T, where T is a pointer, pointer-to-member, or scoped
5396 // enumeration type, there exist candidate operator functions of the form
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005397 //
5398 // T operator?(bool, T, T);
5399 //
Douglas Gregorfec56e72010-11-03 17:00:07 +00005400 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5401 for (BuiltinCandidateTypeSet::iterator
5402 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5403 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5404 Ptr != PtrEnd; ++Ptr) {
5405 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5406 continue;
5407
5408 QualType ParamTypes[2] = { *Ptr, *Ptr };
5409 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5410 }
5411
5412 for (BuiltinCandidateTypeSet::iterator
5413 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5414 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5415 MemPtr != MemPtrEnd; ++MemPtr) {
5416 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5417 continue;
5418
5419 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5420 AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5421 }
5422
5423 if (getLangOptions().CPlusPlus0x) {
5424 for (BuiltinCandidateTypeSet::iterator
5425 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5426 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5427 Enum != EnumEnd; ++Enum) {
5428 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5429 continue;
5430
5431 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5432 continue;
5433
5434 QualType ParamTypes[2] = { *Enum, *Enum };
5435 AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5436 }
5437 }
Douglas Gregor5a1f97e2010-10-15 00:50:56 +00005438 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005439 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005440 }
5441}
5442
Douglas Gregorfa047642009-02-04 00:32:51 +00005443/// \brief Add function candidates found via argument-dependent lookup
5444/// to the set of overloading candidates.
5445///
5446/// This routine performs argument-dependent name lookup based on the
5447/// given function name (which may also be an operator name) and adds
5448/// all of the overload candidates found by ADL to the overload
5449/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00005450void
Douglas Gregorfa047642009-02-04 00:32:51 +00005451Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00005452 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00005453 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00005454 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005455 OverloadCandidateSet& CandidateSet,
5456 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00005457 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00005458
John McCalla113e722010-01-26 06:04:06 +00005459 // FIXME: This approach for uniquing ADL results (and removing
5460 // redundant candidates from the set) relies on pointer-equality,
5461 // which means we need to key off the canonical decl. However,
5462 // always going back to the canonical decl might not get us the
5463 // right set of default arguments. What default arguments are
5464 // we supposed to consider on ADL candidates, anyway?
5465
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005466 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00005467 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00005468
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005469 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005470 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5471 CandEnd = CandidateSet.end();
5472 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00005473 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00005474 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00005475 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00005476 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00005477 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005478
5479 // For each of the ADL candidates we found, add it to the overload
5480 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00005481 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00005482 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00005483 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00005484 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005485 continue;
5486
John McCall9aa472c2010-03-19 07:35:19 +00005487 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00005488 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005489 } else
John McCall6e266892010-01-26 03:27:55 +00005490 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00005491 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00005492 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00005493 }
Douglas Gregorfa047642009-02-04 00:32:51 +00005494}
5495
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005496/// isBetterOverloadCandidate - Determines whether the first overload
5497/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00005498bool
John McCall120d63c2010-08-24 20:38:10 +00005499isBetterOverloadCandidate(Sema &S,
5500 const OverloadCandidate& Cand1,
5501 const OverloadCandidate& Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005502 SourceLocation Loc,
5503 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005504 // Define viable functions to be better candidates than non-viable
5505 // functions.
5506 if (!Cand2.Viable)
5507 return Cand1.Viable;
5508 else if (!Cand1.Viable)
5509 return false;
5510
Douglas Gregor88a35142008-12-22 05:46:06 +00005511 // C++ [over.match.best]p1:
5512 //
5513 // -- if F is a static member function, ICS1(F) is defined such
5514 // that ICS1(F) is neither better nor worse than ICS1(G) for
5515 // any function G, and, symmetrically, ICS1(G) is neither
5516 // better nor worse than ICS1(F).
5517 unsigned StartArg = 0;
5518 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5519 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005520
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005521 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00005522 // A viable function F1 is defined to be a better function than another
5523 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005524 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005525 unsigned NumArgs = Cand1.Conversions.size();
5526 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5527 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005528 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00005529 switch (CompareImplicitConversionSequences(S,
5530 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005531 Cand2.Conversions[ArgIdx])) {
5532 case ImplicitConversionSequence::Better:
5533 // Cand1 has a better conversion sequence.
5534 HasBetterConversion = true;
5535 break;
5536
5537 case ImplicitConversionSequence::Worse:
5538 // Cand1 can't be better than Cand2.
5539 return false;
5540
5541 case ImplicitConversionSequence::Indistinguishable:
5542 // Do nothing.
5543 break;
5544 }
5545 }
5546
Mike Stump1eb44332009-09-09 15:08:12 +00005547 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005548 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005549 if (HasBetterConversion)
5550 return true;
5551
Mike Stump1eb44332009-09-09 15:08:12 +00005552 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005553 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00005554 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005555 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5556 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005557
5558 // -- F1 and F2 are function template specializations, and the function
5559 // template for F1 is more specialized than the template for F2
5560 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005561 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00005562 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5563 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005564 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00005565 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5566 Cand2.Function->getPrimaryTemplate(),
5567 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00005568 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5569 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005570 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005571
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005572 // -- the context is an initialization by user-defined conversion
5573 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5574 // from the return type of F1 to the destination type (i.e.,
5575 // the type of the entity being initialized) is a better
5576 // conversion sequence than the standard conversion sequence
5577 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005578 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005579 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005580 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00005581 switch (CompareStandardConversionSequences(S,
5582 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005583 Cand2.FinalConversion)) {
5584 case ImplicitConversionSequence::Better:
5585 // Cand1 has a better conversion sequence.
5586 return true;
5587
5588 case ImplicitConversionSequence::Worse:
5589 // Cand1 can't be better than Cand2.
5590 return false;
5591
5592 case ImplicitConversionSequence::Indistinguishable:
5593 // Do nothing
5594 break;
5595 }
5596 }
5597
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005598 return false;
5599}
5600
Mike Stump1eb44332009-09-09 15:08:12 +00005601/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00005602/// within an overload candidate set.
5603///
5604/// \param CandidateSet the set of candidate functions.
5605///
5606/// \param Loc the location of the function name (or operator symbol) for
5607/// which overload resolution occurs.
5608///
Mike Stump1eb44332009-09-09 15:08:12 +00005609/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00005610/// function, Best points to the candidate function found.
5611///
5612/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00005613OverloadingResult
5614OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005615 iterator& Best,
5616 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005617 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00005618 Best = end();
5619 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5620 if (Cand->Viable)
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005621 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5622 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005623 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005624 }
5625
5626 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00005627 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005628 return OR_No_Viable_Function;
5629
5630 // Make sure that this function is better than every other viable
5631 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00005632 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00005633 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005634 Cand != Best &&
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005635 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5636 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00005637 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005638 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005639 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005640 }
Mike Stump1eb44332009-09-09 15:08:12 +00005641
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005642 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005643 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005644 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005645 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005646 return OR_Deleted;
5647
Douglas Gregore0762c92009-06-19 23:52:42 +00005648 // C++ [basic.def.odr]p2:
5649 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00005650 // when referred to from a potentially-evaluated expression. [Note: this
5651 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00005652 // (clause 13), user-defined conversions (12.3.2), allocation function for
5653 // placement new (5.3.4), as well as non-default initialization (8.5).
5654 if (Best->Function)
John McCall120d63c2010-08-24 20:38:10 +00005655 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor9b623632010-10-12 23:32:35 +00005656
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005657 return OR_Success;
5658}
5659
John McCall3c80f572010-01-12 02:15:36 +00005660namespace {
5661
5662enum OverloadCandidateKind {
5663 oc_function,
5664 oc_method,
5665 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005666 oc_function_template,
5667 oc_method_template,
5668 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00005669 oc_implicit_default_constructor,
5670 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005671 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00005672};
5673
John McCall220ccbf2010-01-13 00:25:19 +00005674OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5675 FunctionDecl *Fn,
5676 std::string &Description) {
5677 bool isTemplate = false;
5678
5679 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5680 isTemplate = true;
5681 Description = S.getTemplateArgumentBindingsText(
5682 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5683 }
John McCallb1622a12010-01-06 09:43:14 +00005684
5685 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00005686 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005687 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005688
John McCall3c80f572010-01-12 02:15:36 +00005689 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5690 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005691 }
5692
5693 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5694 // This actually gets spelled 'candidate function' for now, but
5695 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00005696 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005697 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00005698
Douglas Gregor3e9438b2010-09-27 22:37:28 +00005699 assert(Meth->isCopyAssignmentOperator()
John McCallb1622a12010-01-06 09:43:14 +00005700 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00005701 return oc_implicit_copy_assignment;
5702 }
5703
John McCall220ccbf2010-01-13 00:25:19 +00005704 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00005705}
5706
5707} // end anonymous namespace
5708
5709// Notes the location of an overload candidate.
5710void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00005711 std::string FnDesc;
5712 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5713 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5714 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00005715}
5716
John McCall1d318332010-01-12 00:44:57 +00005717/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5718/// "lead" diagnostic; it will be given two arguments, the source and
5719/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00005720void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5721 Sema &S,
5722 SourceLocation CaretLoc,
5723 const PartialDiagnostic &PDiag) const {
5724 S.Diag(CaretLoc, PDiag)
5725 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00005726 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00005727 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5728 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00005729 }
John McCall81201622010-01-08 04:41:39 +00005730}
5731
John McCall1d318332010-01-12 00:44:57 +00005732namespace {
5733
John McCalladbb8f82010-01-13 09:16:55 +00005734void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5735 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5736 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00005737 assert(Cand->Function && "for now, candidate must be a function");
5738 FunctionDecl *Fn = Cand->Function;
5739
5740 // There's a conversion slot for the object argument if this is a
5741 // non-constructor method. Note that 'I' corresponds the
5742 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00005743 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00005744 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00005745 if (I == 0)
5746 isObjectArgument = true;
5747 else
5748 I--;
John McCall220ccbf2010-01-13 00:25:19 +00005749 }
5750
John McCall220ccbf2010-01-13 00:25:19 +00005751 std::string FnDesc;
5752 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5753
John McCalladbb8f82010-01-13 09:16:55 +00005754 Expr *FromExpr = Conv.Bad.FromExpr;
5755 QualType FromTy = Conv.Bad.getFromType();
5756 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00005757
John McCall5920dbb2010-02-02 02:42:52 +00005758 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00005759 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00005760 Expr *E = FromExpr->IgnoreParens();
5761 if (isa<UnaryOperator>(E))
5762 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00005763 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00005764
5765 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5766 << (unsigned) FnKind << FnDesc
5767 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5768 << ToTy << Name << I+1;
5769 return;
5770 }
5771
John McCall258b2032010-01-23 08:10:49 +00005772 // Do some hand-waving analysis to see if the non-viability is due
5773 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00005774 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5775 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5776 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5777 CToTy = RT->getPointeeType();
5778 else {
5779 // TODO: detect and diagnose the full richness of const mismatches.
5780 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5781 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5782 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5783 }
5784
5785 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5786 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5787 // It is dumb that we have to do this here.
5788 while (isa<ArrayType>(CFromTy))
5789 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5790 while (isa<ArrayType>(CToTy))
5791 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5792
5793 Qualifiers FromQs = CFromTy.getQualifiers();
5794 Qualifiers ToQs = CToTy.getQualifiers();
5795
5796 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5797 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5798 << (unsigned) FnKind << FnDesc
5799 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5800 << FromTy
5801 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5802 << (unsigned) isObjectArgument << I+1;
5803 return;
5804 }
5805
5806 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5807 assert(CVR && "unexpected qualifiers mismatch");
5808
5809 if (isObjectArgument) {
5810 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5811 << (unsigned) FnKind << FnDesc
5812 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5813 << FromTy << (CVR - 1);
5814 } else {
5815 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5816 << (unsigned) FnKind << FnDesc
5817 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5818 << FromTy << (CVR - 1) << I+1;
5819 }
5820 return;
5821 }
5822
John McCall258b2032010-01-23 08:10:49 +00005823 // Diagnose references or pointers to incomplete types differently,
5824 // since it's far from impossible that the incompleteness triggered
5825 // the failure.
5826 QualType TempFromTy = FromTy.getNonReferenceType();
5827 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5828 TempFromTy = PTy->getPointeeType();
5829 if (TempFromTy->isIncompleteType()) {
5830 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5831 << (unsigned) FnKind << FnDesc
5832 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5833 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5834 return;
5835 }
5836
Douglas Gregor85789812010-06-30 23:01:39 +00005837 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005838 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00005839 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5840 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5841 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5842 FromPtrTy->getPointeeType()) &&
5843 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5844 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5845 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5846 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005847 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00005848 }
5849 } else if (const ObjCObjectPointerType *FromPtrTy
5850 = FromTy->getAs<ObjCObjectPointerType>()) {
5851 if (const ObjCObjectPointerType *ToPtrTy
5852 = ToTy->getAs<ObjCObjectPointerType>())
5853 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5854 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5855 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5856 FromPtrTy->getPointeeType()) &&
5857 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005858 BaseToDerivedConversion = 2;
5859 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5860 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5861 !FromTy->isIncompleteType() &&
5862 !ToRefTy->getPointeeType()->isIncompleteType() &&
5863 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5864 BaseToDerivedConversion = 3;
5865 }
5866
5867 if (BaseToDerivedConversion) {
Douglas Gregor85789812010-06-30 23:01:39 +00005868 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005869 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00005870 << (unsigned) FnKind << FnDesc
5871 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005872 << (BaseToDerivedConversion - 1)
Douglas Gregor85789812010-06-30 23:01:39 +00005873 << FromTy << ToTy << I+1;
5874 return;
5875 }
5876
John McCall651f3ee2010-01-14 03:28:57 +00005877 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00005878 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5879 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00005880 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00005881 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00005882}
5883
5884void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5885 unsigned NumFormalArgs) {
5886 // TODO: treat calls to a missing default constructor as a special case
5887
5888 FunctionDecl *Fn = Cand->Function;
5889 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5890
5891 unsigned MinParams = Fn->getMinRequiredArguments();
5892
5893 // at least / at most / exactly
Douglas Gregora18592e2010-05-08 18:13:28 +00005894 // FIXME: variadic templates "at most" should account for parameter packs
John McCalladbb8f82010-01-13 09:16:55 +00005895 unsigned mode, modeCount;
5896 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00005897 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5898 (Cand->FailureKind == ovl_fail_bad_deduction &&
5899 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005900 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5901 mode = 0; // "at least"
5902 else
5903 mode = 2; // "exactly"
5904 modeCount = MinParams;
5905 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00005906 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5907 (Cand->FailureKind == ovl_fail_bad_deduction &&
5908 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005909 if (MinParams != FnTy->getNumArgs())
5910 mode = 1; // "at most"
5911 else
5912 mode = 2; // "exactly"
5913 modeCount = FnTy->getNumArgs();
5914 }
5915
5916 std::string Description;
5917 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5918
5919 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00005920 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5921 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00005922}
5923
John McCall342fec42010-02-01 18:53:26 +00005924/// Diagnose a failed template-argument deduction.
5925void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5926 Expr **Args, unsigned NumArgs) {
5927 FunctionDecl *Fn = Cand->Function; // pattern
5928
Douglas Gregora9333192010-05-08 17:41:32 +00005929 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00005930 NamedDecl *ParamD;
5931 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5932 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5933 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00005934 switch (Cand->DeductionFailure.Result) {
5935 case Sema::TDK_Success:
5936 llvm_unreachable("TDK_success while diagnosing bad deduction");
5937
5938 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00005939 assert(ParamD && "no parameter found for incomplete deduction result");
5940 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5941 << ParamD->getDeclName();
5942 return;
5943 }
5944
John McCall57e97782010-08-05 09:05:08 +00005945 case Sema::TDK_Underqualified: {
5946 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5947 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5948
5949 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5950
5951 // Param will have been canonicalized, but it should just be a
5952 // qualified version of ParamD, so move the qualifiers to that.
5953 QualifierCollector Qs(S.Context);
5954 Qs.strip(Param);
5955 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5956 assert(S.Context.hasSameType(Param, NonCanonParam));
5957
5958 // Arg has also been canonicalized, but there's nothing we can do
5959 // about that. It also doesn't matter as much, because it won't
5960 // have any template parameters in it (because deduction isn't
5961 // done on dependent types).
5962 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5963
5964 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5965 << ParamD->getDeclName() << Arg << NonCanonParam;
5966 return;
5967 }
5968
5969 case Sema::TDK_Inconsistent: {
Douglas Gregorf1a84452010-05-08 19:15:54 +00005970 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00005971 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005972 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005973 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005974 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005975 which = 1;
5976 else {
Douglas Gregora9333192010-05-08 17:41:32 +00005977 which = 2;
5978 }
5979
5980 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5981 << which << ParamD->getDeclName()
5982 << *Cand->DeductionFailure.getFirstArg()
5983 << *Cand->DeductionFailure.getSecondArg();
5984 return;
5985 }
Douglas Gregora18592e2010-05-08 18:13:28 +00005986
Douglas Gregorf1a84452010-05-08 19:15:54 +00005987 case Sema::TDK_InvalidExplicitArguments:
5988 assert(ParamD && "no parameter found for invalid explicit arguments");
5989 if (ParamD->getDeclName())
5990 S.Diag(Fn->getLocation(),
5991 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5992 << ParamD->getDeclName();
5993 else {
5994 int index = 0;
5995 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5996 index = TTP->getIndex();
5997 else if (NonTypeTemplateParmDecl *NTTP
5998 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5999 index = NTTP->getIndex();
6000 else
6001 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6002 S.Diag(Fn->getLocation(),
6003 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6004 << (index + 1);
6005 }
6006 return;
6007
Douglas Gregora18592e2010-05-08 18:13:28 +00006008 case Sema::TDK_TooManyArguments:
6009 case Sema::TDK_TooFewArguments:
6010 DiagnoseArityMismatch(S, Cand, NumArgs);
6011 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00006012
6013 case Sema::TDK_InstantiationDepth:
6014 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6015 return;
6016
6017 case Sema::TDK_SubstitutionFailure: {
6018 std::string ArgString;
6019 if (TemplateArgumentList *Args
6020 = Cand->DeductionFailure.getTemplateArgumentList())
6021 ArgString = S.getTemplateArgumentBindingsText(
6022 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6023 *Args);
6024 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6025 << ArgString;
6026 return;
6027 }
Douglas Gregora9333192010-05-08 17:41:32 +00006028
John McCall342fec42010-02-01 18:53:26 +00006029 // TODO: diagnose these individually, then kill off
6030 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00006031 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00006032 case Sema::TDK_FailedOverloadResolution:
6033 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6034 return;
6035 }
6036}
6037
6038/// Generates a 'note' diagnostic for an overload candidate. We've
6039/// already generated a primary error at the call site.
6040///
6041/// It really does need to be a single diagnostic with its caret
6042/// pointed at the candidate declaration. Yes, this creates some
6043/// major challenges of technical writing. Yes, this makes pointing
6044/// out problems with specific arguments quite awkward. It's still
6045/// better than generating twenty screens of text for every failed
6046/// overload.
6047///
6048/// It would be great to be able to express per-candidate problems
6049/// more richly for those diagnostic clients that cared, but we'd
6050/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00006051void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6052 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00006053 FunctionDecl *Fn = Cand->Function;
6054
John McCall81201622010-01-08 04:41:39 +00006055 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00006056 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00006057 std::string FnDesc;
6058 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00006059
6060 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00006061 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00006062 return;
John McCall81201622010-01-08 04:41:39 +00006063 }
6064
John McCall220ccbf2010-01-13 00:25:19 +00006065 // We don't really have anything else to say about viable candidates.
6066 if (Cand->Viable) {
6067 S.NoteOverloadCandidate(Fn);
6068 return;
6069 }
John McCall1d318332010-01-12 00:44:57 +00006070
John McCalladbb8f82010-01-13 09:16:55 +00006071 switch (Cand->FailureKind) {
6072 case ovl_fail_too_many_arguments:
6073 case ovl_fail_too_few_arguments:
6074 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00006075
John McCalladbb8f82010-01-13 09:16:55 +00006076 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00006077 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6078
John McCall717e8912010-01-23 05:17:32 +00006079 case ovl_fail_trivial_conversion:
6080 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00006081 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00006082 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006083
John McCallb1bdc622010-02-25 01:37:24 +00006084 case ovl_fail_bad_conversion: {
6085 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6086 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00006087 if (Cand->Conversions[I].isBad())
6088 return DiagnoseBadConversion(S, Cand, I);
6089
6090 // FIXME: this currently happens when we're called from SemaInit
6091 // when user-conversion overload fails. Figure out how to handle
6092 // those conditions and diagnose them well.
6093 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006094 }
John McCallb1bdc622010-02-25 01:37:24 +00006095 }
John McCalla1d7d622010-01-08 00:58:21 +00006096}
6097
6098void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6099 // Desugar the type of the surrogate down to a function type,
6100 // retaining as many typedefs as possible while still showing
6101 // the function type (and, therefore, its parameter types).
6102 QualType FnType = Cand->Surrogate->getConversionType();
6103 bool isLValueReference = false;
6104 bool isRValueReference = false;
6105 bool isPointer = false;
6106 if (const LValueReferenceType *FnTypeRef =
6107 FnType->getAs<LValueReferenceType>()) {
6108 FnType = FnTypeRef->getPointeeType();
6109 isLValueReference = true;
6110 } else if (const RValueReferenceType *FnTypeRef =
6111 FnType->getAs<RValueReferenceType>()) {
6112 FnType = FnTypeRef->getPointeeType();
6113 isRValueReference = true;
6114 }
6115 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6116 FnType = FnTypePtr->getPointeeType();
6117 isPointer = true;
6118 }
6119 // Desugar down to a function type.
6120 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6121 // Reconstruct the pointer/reference as appropriate.
6122 if (isPointer) FnType = S.Context.getPointerType(FnType);
6123 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6124 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6125
6126 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6127 << FnType;
6128}
6129
6130void NoteBuiltinOperatorCandidate(Sema &S,
6131 const char *Opc,
6132 SourceLocation OpLoc,
6133 OverloadCandidate *Cand) {
6134 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6135 std::string TypeStr("operator");
6136 TypeStr += Opc;
6137 TypeStr += "(";
6138 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6139 if (Cand->Conversions.size() == 1) {
6140 TypeStr += ")";
6141 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6142 } else {
6143 TypeStr += ", ";
6144 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6145 TypeStr += ")";
6146 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6147 }
6148}
6149
6150void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6151 OverloadCandidate *Cand) {
6152 unsigned NoOperands = Cand->Conversions.size();
6153 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6154 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00006155 if (ICS.isBad()) break; // all meaningless after first invalid
6156 if (!ICS.isAmbiguous()) continue;
6157
John McCall120d63c2010-08-24 20:38:10 +00006158 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006159 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00006160 }
6161}
6162
John McCall1b77e732010-01-15 23:32:50 +00006163SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6164 if (Cand->Function)
6165 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00006166 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00006167 return Cand->Surrogate->getLocation();
6168 return SourceLocation();
6169}
6170
John McCallbf65c0b2010-01-12 00:48:53 +00006171struct CompareOverloadCandidatesForDisplay {
6172 Sema &S;
6173 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00006174
6175 bool operator()(const OverloadCandidate *L,
6176 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00006177 // Fast-path this check.
6178 if (L == R) return false;
6179
John McCall81201622010-01-08 04:41:39 +00006180 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00006181 if (L->Viable) {
6182 if (!R->Viable) return true;
6183
6184 // TODO: introduce a tri-valued comparison for overload
6185 // candidates. Would be more worthwhile if we had a sort
6186 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00006187 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6188 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00006189 } else if (R->Viable)
6190 return false;
John McCall81201622010-01-08 04:41:39 +00006191
John McCall1b77e732010-01-15 23:32:50 +00006192 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00006193
John McCall1b77e732010-01-15 23:32:50 +00006194 // Criteria by which we can sort non-viable candidates:
6195 if (!L->Viable) {
6196 // 1. Arity mismatches come after other candidates.
6197 if (L->FailureKind == ovl_fail_too_many_arguments ||
6198 L->FailureKind == ovl_fail_too_few_arguments)
6199 return false;
6200 if (R->FailureKind == ovl_fail_too_many_arguments ||
6201 R->FailureKind == ovl_fail_too_few_arguments)
6202 return true;
John McCall81201622010-01-08 04:41:39 +00006203
John McCall717e8912010-01-23 05:17:32 +00006204 // 2. Bad conversions come first and are ordered by the number
6205 // of bad conversions and quality of good conversions.
6206 if (L->FailureKind == ovl_fail_bad_conversion) {
6207 if (R->FailureKind != ovl_fail_bad_conversion)
6208 return true;
6209
6210 // If there's any ordering between the defined conversions...
6211 // FIXME: this might not be transitive.
6212 assert(L->Conversions.size() == R->Conversions.size());
6213
6214 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00006215 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6216 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00006217 switch (CompareImplicitConversionSequences(S,
6218 L->Conversions[I],
6219 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00006220 case ImplicitConversionSequence::Better:
6221 leftBetter++;
6222 break;
6223
6224 case ImplicitConversionSequence::Worse:
6225 leftBetter--;
6226 break;
6227
6228 case ImplicitConversionSequence::Indistinguishable:
6229 break;
6230 }
6231 }
6232 if (leftBetter > 0) return true;
6233 if (leftBetter < 0) return false;
6234
6235 } else if (R->FailureKind == ovl_fail_bad_conversion)
6236 return false;
6237
John McCall1b77e732010-01-15 23:32:50 +00006238 // TODO: others?
6239 }
6240
6241 // Sort everything else by location.
6242 SourceLocation LLoc = GetLocationForCandidate(L);
6243 SourceLocation RLoc = GetLocationForCandidate(R);
6244
6245 // Put candidates without locations (e.g. builtins) at the end.
6246 if (LLoc.isInvalid()) return false;
6247 if (RLoc.isInvalid()) return true;
6248
6249 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00006250 }
6251};
6252
John McCall717e8912010-01-23 05:17:32 +00006253/// CompleteNonViableCandidate - Normally, overload resolution only
6254/// computes up to the first
6255void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6256 Expr **Args, unsigned NumArgs) {
6257 assert(!Cand->Viable);
6258
6259 // Don't do anything on failures other than bad conversion.
6260 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6261
6262 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00006263 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00006264 unsigned ConvCount = Cand->Conversions.size();
6265 while (true) {
6266 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6267 ConvIdx++;
6268 if (Cand->Conversions[ConvIdx - 1].isBad())
6269 break;
6270 }
6271
6272 if (ConvIdx == ConvCount)
6273 return;
6274
John McCallb1bdc622010-02-25 01:37:24 +00006275 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6276 "remaining conversion is initialized?");
6277
Douglas Gregor23ef6c02010-04-16 17:45:54 +00006278 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00006279 // operation somehow.
6280 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00006281
6282 const FunctionProtoType* Proto;
6283 unsigned ArgIdx = ConvIdx;
6284
6285 if (Cand->IsSurrogate) {
6286 QualType ConvType
6287 = Cand->Surrogate->getConversionType().getNonReferenceType();
6288 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6289 ConvType = ConvPtrType->getPointeeType();
6290 Proto = ConvType->getAs<FunctionProtoType>();
6291 ArgIdx--;
6292 } else if (Cand->Function) {
6293 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6294 if (isa<CXXMethodDecl>(Cand->Function) &&
6295 !isa<CXXConstructorDecl>(Cand->Function))
6296 ArgIdx--;
6297 } else {
6298 // Builtin binary operator with a bad first conversion.
6299 assert(ConvCount <= 3);
6300 for (; ConvIdx != ConvCount; ++ConvIdx)
6301 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006302 = TryCopyInitialization(S, Args[ConvIdx],
6303 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6304 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006305 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00006306 return;
6307 }
6308
6309 // Fill in the rest of the conversions.
6310 unsigned NumArgsInProto = Proto->getNumArgs();
6311 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6312 if (ArgIdx < NumArgsInProto)
6313 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006314 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6315 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006316 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00006317 else
6318 Cand->Conversions[ConvIdx].setEllipsis();
6319 }
6320}
6321
John McCalla1d7d622010-01-08 00:58:21 +00006322} // end anonymous namespace
6323
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006324/// PrintOverloadCandidates - When overload resolution fails, prints
6325/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00006326/// set.
John McCall120d63c2010-08-24 20:38:10 +00006327void OverloadCandidateSet::NoteCandidates(Sema &S,
6328 OverloadCandidateDisplayKind OCD,
6329 Expr **Args, unsigned NumArgs,
6330 const char *Opc,
6331 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00006332 // Sort the candidates by viability and position. Sorting directly would
6333 // be prohibitive, so we make a set of pointers and sort those.
6334 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00006335 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6336 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00006337 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00006338 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00006339 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00006340 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006341 if (Cand->Function || Cand->IsSurrogate)
6342 Cands.push_back(Cand);
6343 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6344 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00006345 }
6346 }
6347
John McCallbf65c0b2010-01-12 00:48:53 +00006348 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00006349 CompareOverloadCandidatesForDisplay(S));
John McCall81201622010-01-08 04:41:39 +00006350
John McCall1d318332010-01-12 00:44:57 +00006351 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00006352
John McCall81201622010-01-08 04:41:39 +00006353 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall120d63c2010-08-24 20:38:10 +00006354 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006355 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00006356 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6357 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00006358
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006359 // Set an arbitrary limit on the number of candidate functions we'll spam
6360 // the user with. FIXME: This limit should depend on details of the
6361 // candidate list.
6362 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6363 break;
6364 }
6365 ++CandsShown;
6366
John McCalla1d7d622010-01-08 00:58:21 +00006367 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00006368 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00006369 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00006370 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006371 else {
6372 assert(Cand->Viable &&
6373 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00006374 // Generally we only see ambiguities including viable builtin
6375 // operators if overload resolution got screwed up by an
6376 // ambiguous user-defined conversion.
6377 //
6378 // FIXME: It's quite possible for different conversions to see
6379 // different ambiguities, though.
6380 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00006381 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00006382 ReportedAmbiguousConversions = true;
6383 }
John McCalla1d7d622010-01-08 00:58:21 +00006384
John McCall1d318332010-01-12 00:44:57 +00006385 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00006386 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006387 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006388 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006389
6390 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00006391 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006392}
6393
John McCall9aa472c2010-03-19 07:35:19 +00006394static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00006395 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00006396 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006397
John McCall9aa472c2010-03-19 07:35:19 +00006398 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006399}
6400
Douglas Gregor904eed32008-11-10 20:40:00 +00006401/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6402/// an overloaded function (C++ [over.over]), where @p From is an
6403/// expression with overloaded function type and @p ToType is the type
6404/// we're trying to resolve to. For example:
6405///
6406/// @code
6407/// int f(double);
6408/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00006409///
Douglas Gregor904eed32008-11-10 20:40:00 +00006410/// int (*pfd)(double) = f; // selects f(double)
6411/// @endcode
6412///
6413/// This routine returns the resulting FunctionDecl if it could be
6414/// resolved, and NULL otherwise. When @p Complain is true, this
6415/// routine will emit diagnostics if there is an error.
6416FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00006417Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00006418 bool Complain,
6419 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006420 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00006421 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00006422 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00006423 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00006424 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00006425 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00006426 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00006427 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006428 FunctionType = MemTypePtr->getPointeeType();
6429 IsMember = true;
6430 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006431
Douglas Gregor904eed32008-11-10 20:40:00 +00006432 // C++ [over.over]p1:
6433 // [...] [Note: any redundant set of parentheses surrounding the
6434 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00006435 // C++ [over.over]p1:
6436 // [...] The overloaded function name can be preceded by the &
6437 // operator.
John McCallc988fab2010-08-24 23:26:21 +00006438 // However, remember whether the expression has member-pointer form:
6439 // C++ [expr.unary.op]p4:
6440 // A pointer to member is only formed when an explicit & is used
6441 // and its operand is a qualified-id not enclosed in
6442 // parentheses.
John McCall9c72c602010-08-27 09:08:28 +00006443 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6444 OverloadExpr *OvlExpr = Ovl.Expression;
John McCallc988fab2010-08-24 23:26:21 +00006445
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006446 // We expect a pointer or reference to function, or a function pointer.
6447 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6448 if (!FunctionType->isFunctionType()) {
6449 if (Complain)
6450 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6451 << OvlExpr->getName() << ToType;
6452
6453 return 0;
6454 }
6455
John McCallfb97e752010-08-24 22:52:39 +00006456 // If the overload expression doesn't have the form of a pointer to
John McCallc988fab2010-08-24 23:26:21 +00006457 // member, don't try to convert it to a pointer-to-member type.
John McCall9c72c602010-08-27 09:08:28 +00006458 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCallfb97e752010-08-24 22:52:39 +00006459 if (!Complain) return 0;
6460
6461 // TODO: Should we condition this on whether any functions might
6462 // have matched, or is it more appropriate to do that in callers?
6463 // TODO: a fixit wouldn't hurt.
6464 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6465 << ToType << OvlExpr->getSourceRange();
6466 return 0;
6467 }
6468
6469 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6470 if (OvlExpr->hasExplicitTemplateArgs()) {
6471 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6472 ExplicitTemplateArgs = &ETABuffer;
6473 }
6474
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006475 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00006476
Douglas Gregor904eed32008-11-10 20:40:00 +00006477 // Look through all of the overloaded functions, searching for one
6478 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00006479 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00006480 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor9b623632010-10-12 23:32:35 +00006481
Douglas Gregor00aeb522009-07-08 23:33:52 +00006482 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00006483 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6484 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00006485 // Look through any using declarations to find the underlying function.
6486 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6487
Douglas Gregor904eed32008-11-10 20:40:00 +00006488 // C++ [over.over]p3:
6489 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00006490 // targets of type "pointer-to-function" or "reference-to-function."
6491 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00006492 // type "pointer-to-member-function."
6493 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006494
Mike Stump1eb44332009-09-09 15:08:12 +00006495 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00006496 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006497 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00006498 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00006499 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00006500 // static when converting to member pointer.
6501 if (Method->isStatic() == IsMember)
6502 continue;
6503 } else if (IsMember)
6504 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00006505
Douglas Gregor00aeb522009-07-08 23:33:52 +00006506 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006507 // If the name is a function template, template argument deduction is
6508 // done (14.8.2.2), and if the argument deduction succeeds, the
6509 // resulting template argument list is used to generate a single
6510 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00006511 // overloaded functions considered.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006512 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006513 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00006514 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00006515 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00006516 FunctionType, Specialization, Info)) {
6517 // FIXME: make a note of the failed deduction for diagnostics.
6518 (void)Result;
6519 } else {
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00006520 // Template argument deduction ensures that we have an exact match.
6521 // This function template specicalization works.
Douglas Gregor9b623632010-10-12 23:32:35 +00006522 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006523 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00006524 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor9b623632010-10-12 23:32:35 +00006525 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor83314aa2009-07-08 20:55:45 +00006526 }
John McCallba135432009-11-21 08:51:07 +00006527
6528 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00006529 }
Mike Stump1eb44332009-09-09 15:08:12 +00006530
Chandler Carruthbd647292009-12-29 06:17:27 +00006531 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006532 // Skip non-static functions when converting to pointer, and static
6533 // when converting to member pointer.
6534 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00006535 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006536
6537 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00006538 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006539 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00006540 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00006541 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00006542
Chandler Carruthbd647292009-12-29 06:17:27 +00006543 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00006544 QualType ResultTy;
6545 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6546 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6547 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00006548 Matches.push_back(std::make_pair(I.getPair(),
6549 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00006550 FoundNonTemplateFunction = true;
6551 }
Mike Stump1eb44332009-09-09 15:08:12 +00006552 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006553 }
6554
Douglas Gregor00aeb522009-07-08 23:33:52 +00006555 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006556 if (Matches.empty()) {
6557 if (Complain) {
6558 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6559 << OvlExpr->getName() << FunctionType;
6560 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6561 E = OvlExpr->decls_end();
6562 I != E; ++I)
6563 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6564 NoteOverloadCandidate(F);
6565 }
6566
Douglas Gregor00aeb522009-07-08 23:33:52 +00006567 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006568 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006569 FunctionDecl *Result = Matches[0].second;
Douglas Gregor9b623632010-10-12 23:32:35 +00006570 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00006571 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor9b623632010-10-12 23:32:35 +00006572 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00006573 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor9b623632010-10-12 23:32:35 +00006574 }
Sebastian Redl07ab2022009-10-17 21:12:09 +00006575 return Result;
6576 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00006577
6578 // C++ [over.over]p4:
6579 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00006580 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006581 // [...] and any given function template specialization F1 is
6582 // eliminated if the set contains a second function template
6583 // specialization whose function template is more specialized
6584 // than the function template of F1 according to the partial
6585 // ordering rules of 14.5.5.2.
6586
6587 // The algorithm specified above is quadratic. We instead use a
6588 // two-pass algorithm (similar to the one used to identify the
6589 // best viable function in an overload set) that identifies the
6590 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00006591
6592 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6593 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6594 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00006595
6596 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00006597 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00006598 TPOC_Other, From->getLocStart(),
6599 PDiag(),
6600 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006601 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00006602 PDiag(diag::note_ovl_candidate)
6603 << (unsigned) oc_function_template);
Douglas Gregor78c057e2010-09-12 08:16:09 +00006604 if (Result == MatchesCopy.end())
6605 return 0;
6606
John McCallc373d482010-01-27 01:50:18 +00006607 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00006608 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor9b623632010-10-12 23:32:35 +00006609 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00006610 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallc373d482010-01-27 01:50:18 +00006611 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00006612 }
Mike Stump1eb44332009-09-09 15:08:12 +00006613
Douglas Gregor312a2022009-09-26 03:56:17 +00006614 // [...] any function template specializations in the set are
6615 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00006616 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00006617 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00006618 ++I;
6619 else {
John McCall9aa472c2010-03-19 07:35:19 +00006620 Matches[I] = Matches[--N];
6621 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00006622 }
6623 }
Douglas Gregor312a2022009-09-26 03:56:17 +00006624
Mike Stump1eb44332009-09-09 15:08:12 +00006625 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00006626 // selected function.
John McCallc373d482010-01-27 01:50:18 +00006627 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006628 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00006629 FoundResult = Matches[0].first;
Douglas Gregor9b623632010-10-12 23:32:35 +00006630 if (Complain)
John McCall9aa472c2010-03-19 07:35:19 +00006631 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6632 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006633 }
Mike Stump1eb44332009-09-09 15:08:12 +00006634
Douglas Gregor00aeb522009-07-08 23:33:52 +00006635 // FIXME: We should probably return the same thing that BestViableFunction
6636 // returns (even if we issue the diagnostics here).
Douglas Gregor8e960432010-11-08 03:40:48 +00006637 if (Complain) {
6638 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
6639 << Matches[0].second->getDeclName();
6640 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6641 NoteOverloadCandidate(Matches[I].second);
6642 }
6643
Douglas Gregor904eed32008-11-10 20:40:00 +00006644 return 0;
6645}
6646
Douglas Gregor4b52e252009-12-21 23:17:24 +00006647/// \brief Given an expression that refers to an overloaded function, try to
6648/// resolve that overloaded function expression down to a single function.
6649///
6650/// This routine can only resolve template-ids that refer to a single function
6651/// template, where that template-id refers to a single template whose template
6652/// arguments are either provided by the template-id or have defaults,
6653/// as described in C++0x [temp.arg.explicit]p3.
6654FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6655 // C++ [over.over]p1:
6656 // [...] [Note: any redundant set of parentheses surrounding the
6657 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00006658 // C++ [over.over]p1:
6659 // [...] The overloaded function name can be preceded by the &
6660 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00006661
6662 if (From->getType() != Context.OverloadTy)
6663 return 0;
6664
John McCall9c72c602010-08-27 09:08:28 +00006665 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor4b52e252009-12-21 23:17:24 +00006666
6667 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00006668 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00006669 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00006670
6671 TemplateArgumentListInfo ExplicitTemplateArgs;
6672 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00006673
6674 // Look through all of the overloaded functions, searching for one
6675 // whose type matches exactly.
6676 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00006677 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6678 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00006679 // C++0x [temp.arg.explicit]p3:
6680 // [...] In contexts where deduction is done and fails, or in contexts
6681 // where deduction is not done, if a template argument list is
6682 // specified and it, along with any default template arguments,
6683 // identifies a single function template specialization, then the
6684 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00006685 FunctionTemplateDecl *FunctionTemplate
6686 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006687
6688 // C++ [over.over]p2:
6689 // If the name is a function template, template argument deduction is
6690 // done (14.8.2.2), and if the argument deduction succeeds, the
6691 // resulting template argument list is used to generate a single
6692 // function template specialization, which is added to the set of
6693 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00006694 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006695 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006696 if (TemplateDeductionResult Result
6697 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6698 Specialization, Info)) {
6699 // FIXME: make a note of the failed deduction for diagnostics.
6700 (void)Result;
6701 continue;
6702 }
6703
6704 // Multiple matches; we can't resolve to a single declaration.
6705 if (Matched)
6706 return 0;
6707
6708 Matched = Specialization;
6709 }
Douglas Gregor9b623632010-10-12 23:32:35 +00006710
Douglas Gregor4b52e252009-12-21 23:17:24 +00006711 return Matched;
6712}
6713
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006714/// \brief Add a single candidate to the overload set.
6715static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00006716 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00006717 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006718 Expr **Args, unsigned NumArgs,
6719 OverloadCandidateSet &CandidateSet,
6720 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00006721 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00006722 if (isa<UsingShadowDecl>(Callee))
6723 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6724
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006725 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00006726 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00006727 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006728 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006729 return;
John McCallba135432009-11-21 08:51:07 +00006730 }
6731
6732 if (FunctionTemplateDecl *FuncTemplate
6733 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00006734 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6735 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006736 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00006737 return;
6738 }
6739
6740 assert(false && "unhandled case in overloaded call candidate");
6741
6742 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006743}
6744
6745/// \brief Add the overload candidates named by callee and/or found by argument
6746/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00006747void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006748 Expr **Args, unsigned NumArgs,
6749 OverloadCandidateSet &CandidateSet,
6750 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00006751
6752#ifndef NDEBUG
6753 // Verify that ArgumentDependentLookup is consistent with the rules
6754 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006755 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006756 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6757 // and let Y be the lookup set produced by argument dependent
6758 // lookup (defined as follows). If X contains
6759 //
6760 // -- a declaration of a class member, or
6761 //
6762 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00006763 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006764 //
6765 // -- a declaration that is neither a function or a function
6766 // template
6767 //
6768 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00006769
John McCall3b4294e2009-12-16 12:17:52 +00006770 if (ULE->requiresADL()) {
6771 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6772 E = ULE->decls_end(); I != E; ++I) {
6773 assert(!(*I)->getDeclContext()->isRecord());
6774 assert(isa<UsingShadowDecl>(*I) ||
6775 !(*I)->getDeclContext()->isFunctionOrMethod());
6776 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00006777 }
6778 }
6779#endif
6780
John McCall3b4294e2009-12-16 12:17:52 +00006781 // It would be nice to avoid this copy.
6782 TemplateArgumentListInfo TABuffer;
6783 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6784 if (ULE->hasExplicitTemplateArgs()) {
6785 ULE->copyTemplateArgumentsInto(TABuffer);
6786 ExplicitTemplateArgs = &TABuffer;
6787 }
6788
6789 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6790 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00006791 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006792 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006793 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00006794
John McCall3b4294e2009-12-16 12:17:52 +00006795 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00006796 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6797 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006798 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006799 CandidateSet,
6800 PartialOverloading);
6801}
John McCall578b69b2009-12-16 08:11:27 +00006802
6803/// Attempts to recover from a call where no functions were found.
6804///
6805/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00006806static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006807BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00006808 UnresolvedLookupExpr *ULE,
6809 SourceLocation LParenLoc,
6810 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006811 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00006812
6813 CXXScopeSpec SS;
6814 if (ULE->getQualifier()) {
6815 SS.setScopeRep(ULE->getQualifier());
6816 SS.setRange(ULE->getQualifierRange());
6817 }
6818
John McCall3b4294e2009-12-16 12:17:52 +00006819 TemplateArgumentListInfo TABuffer;
6820 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6821 if (ULE->hasExplicitTemplateArgs()) {
6822 ULE->copyTemplateArgumentsInto(TABuffer);
6823 ExplicitTemplateArgs = &TABuffer;
6824 }
6825
John McCall578b69b2009-12-16 08:11:27 +00006826 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6827 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00006828 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallf312b1e2010-08-26 23:41:50 +00006829 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00006830
John McCall3b4294e2009-12-16 12:17:52 +00006831 assert(!R.empty() && "lookup results empty despite recovery");
6832
6833 // Build an implicit member call if appropriate. Just drop the
6834 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00006835 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00006836 if ((*R.begin())->isCXXClassMember())
6837 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6838 else if (ExplicitTemplateArgs)
6839 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6840 else
6841 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6842
6843 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006844 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00006845
6846 // This shouldn't cause an infinite loop because we're giving it
6847 // an expression with non-empty lookup results, which should never
6848 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00006849 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00006850 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006851}
Douglas Gregord7a95972010-06-08 17:35:15 +00006852
Douglas Gregorf6b89692008-11-26 05:54:23 +00006853/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00006854/// (which eventually refers to the declaration Func) and the call
6855/// arguments Args/NumArgs, attempt to resolve the function call down
6856/// to a specific function. If overload resolution succeeds, returns
6857/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00006858/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00006859/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00006860ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006861Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00006862 SourceLocation LParenLoc,
6863 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006864 SourceLocation RParenLoc) {
6865#ifndef NDEBUG
6866 if (ULE->requiresADL()) {
6867 // To do ADL, we must have found an unqualified name.
6868 assert(!ULE->getQualifier() && "qualified name with ADL");
6869
6870 // We don't perform ADL for implicit declarations of builtins.
6871 // Verify that this was correctly set up.
6872 FunctionDecl *F;
6873 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6874 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6875 F->getBuiltinID() && F->isImplicit())
6876 assert(0 && "performing ADL for builtin");
6877
6878 // We don't perform ADL in C.
6879 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6880 }
6881#endif
6882
John McCall5769d612010-02-08 23:07:23 +00006883 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00006884
John McCall3b4294e2009-12-16 12:17:52 +00006885 // Add the functions denoted by the callee to the set of candidate
6886 // functions, including those from argument-dependent lookup.
6887 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00006888
6889 // If we found nothing, try to recover.
6890 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6891 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00006892 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006893 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00006894 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006895
Douglas Gregorf6b89692008-11-26 05:54:23 +00006896 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006897 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00006898 case OR_Success: {
6899 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00006900 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00006901 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(), ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00006902 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall3b4294e2009-12-16 12:17:52 +00006903 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6904 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00006905
6906 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00006907 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00006908 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00006909 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006910 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006911 break;
6912
6913 case OR_Ambiguous:
6914 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00006915 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006916 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006917 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006918
6919 case OR_Deleted:
6920 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6921 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00006922 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006923 << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006924 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006925 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00006926 }
6927
Douglas Gregorff331c12010-07-25 18:17:45 +00006928 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00006929 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00006930}
6931
John McCall6e266892010-01-26 03:27:55 +00006932static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00006933 return Functions.size() > 1 ||
6934 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6935}
6936
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006937/// \brief Create a unary operation that may resolve to an overloaded
6938/// operator.
6939///
6940/// \param OpLoc The location of the operator itself (e.g., '*').
6941///
6942/// \param OpcIn The UnaryOperator::Opcode that describes this
6943/// operator.
6944///
6945/// \param Functions The set of non-member functions that will be
6946/// considered by overload resolution. The caller needs to build this
6947/// set based on the context using, e.g.,
6948/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6949/// set should not contain any member functions; those will be added
6950/// by CreateOverloadedUnaryOp().
6951///
6952/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00006953ExprResult
John McCall6e266892010-01-26 03:27:55 +00006954Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6955 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00006956 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006957 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006958
6959 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6960 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6961 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00006962 // TODO: provide better source location info.
6963 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006964
6965 Expr *Args[2] = { Input, 0 };
6966 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00006967
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006968 // For post-increment and post-decrement, add the implicit '0' as
6969 // the second argument, so that we know this is a post-increment or
6970 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00006971 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006972 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00006973 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
6974 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006975 NumArgs = 2;
6976 }
6977
6978 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00006979 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00006980 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00006981 Opc,
6982 Context.DependentTy,
6983 OpLoc));
6984
John McCallc373d482010-01-27 01:50:18 +00006985 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006986 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006987 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00006988 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006989 /*ADL*/ true, IsOverloaded(Fns),
6990 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006991 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6992 &Args[0], NumArgs,
6993 Context.DependentTy,
6994 OpLoc));
6995 }
6996
6997 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006998 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006999
7000 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00007001 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007002
7003 // Add operator candidates that are member functions.
7004 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7005
John McCall6e266892010-01-26 03:27:55 +00007006 // Add candidates from ADL.
7007 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00007008 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00007009 /*ExplicitTemplateArgs*/ 0,
7010 CandidateSet);
7011
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007012 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00007013 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007014
7015 // Perform overload resolution.
7016 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007017 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007018 case OR_Success: {
7019 // We found a built-in operator or an overloaded operator.
7020 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00007021
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007022 if (FnDecl) {
7023 // We matched an overloaded operator. Build a call to that
7024 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00007025
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007026 // Convert the arguments.
7027 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00007028 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007029
John McCall6bb80172010-03-30 21:47:33 +00007030 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7031 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007032 return ExprError();
7033 } else {
7034 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007035 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00007036 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007037 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00007038 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00007039 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00007040 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00007041 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007042 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00007043 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007044 }
7045
John McCallb697e082010-05-06 18:15:07 +00007046 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7047
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007048 // Determine the result type
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007049 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00007050
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007051 // Build the actual expression node.
7052 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7053 SourceLocation());
7054 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00007055
Eli Friedman4c3b8962009-11-18 03:58:17 +00007056 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00007057 CallExpr *TheCall =
Anders Carlsson26a2a072009-10-13 21:19:37 +00007058 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall9ae2f072010-08-23 23:25:46 +00007059 Args, NumArgs, ResultTy, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00007060
John McCall9ae2f072010-08-23 23:25:46 +00007061 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00007062 FnDecl))
7063 return ExprError();
7064
John McCall9ae2f072010-08-23 23:25:46 +00007065 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +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.
7070 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007071 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007072 return ExprError();
7073
7074 break;
7075 }
7076 }
7077
7078 case OR_No_Viable_Function:
7079 // No viable function; fall through to handling this as a
7080 // built-in operator, which will produce an error message for us.
7081 break;
7082
7083 case OR_Ambiguous:
7084 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7085 << UnaryOperator::getOpcodeStr(Opc)
7086 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007087 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7088 Args, NumArgs,
7089 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007090 return ExprError();
7091
7092 case OR_Deleted:
7093 Diag(OpLoc, diag::err_ovl_deleted_oper)
7094 << Best->Function->isDeleted()
7095 << UnaryOperator::getOpcodeStr(Opc)
7096 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007097 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007098 return ExprError();
7099 }
7100
7101 // Either we found no viable overloaded operator or we matched a
7102 // built-in operator. In either case, fall through to trying to
7103 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00007104 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007105}
7106
Douglas Gregor063daf62009-03-13 18:40:31 +00007107/// \brief Create a binary operation that may resolve to an overloaded
7108/// operator.
7109///
7110/// \param OpLoc The location of the operator itself (e.g., '+').
7111///
7112/// \param OpcIn The BinaryOperator::Opcode that describes this
7113/// operator.
7114///
7115/// \param Functions The set of non-member functions that will be
7116/// considered by overload resolution. The caller needs to build this
7117/// set based on the context using, e.g.,
7118/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7119/// set should not contain any member functions; those will be added
7120/// by CreateOverloadedBinOp().
7121///
7122/// \param LHS Left-hand argument.
7123/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00007124ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00007125Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00007126 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00007127 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00007128 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00007129 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007130 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00007131
7132 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7133 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7134 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7135
7136 // If either side is type-dependent, create an appropriate dependent
7137 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007138 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00007139 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007140 // If there are no functions to store, just build a dependent
7141 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00007142 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007143 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
7144 Context.DependentTy, OpLoc));
7145
7146 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7147 Context.DependentTy,
7148 Context.DependentTy,
7149 Context.DependentTy,
7150 OpLoc));
7151 }
John McCall6e266892010-01-26 03:27:55 +00007152
7153 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00007154 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007155 // TODO: provide better source location info in DNLoc component.
7156 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00007157 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007158 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007159 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007160 /*ADL*/ true, IsOverloaded(Fns),
7161 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00007162 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00007163 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00007164 Context.DependentTy,
7165 OpLoc));
7166 }
7167
7168 // If this is the .* operator, which is not overloadable, just
7169 // create a built-in binary operator.
John McCall2de56d12010-08-25 11:45:40 +00007170 if (Opc == BO_PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007171 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007172
Sebastian Redl275c2b42009-11-18 23:10:33 +00007173 // If this is the assignment operator, we only perform overload resolution
7174 // if the left-hand side is a class or enumeration type. This is actually
7175 // a hack. The standard requires that we do overload resolution between the
7176 // various built-in candidates, but as DR507 points out, this can lead to
7177 // problems. So we do it this way, which pretty much follows what GCC does.
7178 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00007179 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007180 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007181
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007182 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007183 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007184
7185 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00007186 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00007187
7188 // Add operator candidates that are member functions.
7189 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7190
John McCall6e266892010-01-26 03:27:55 +00007191 // Add candidates from ADL.
7192 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7193 Args, 2,
7194 /*ExplicitTemplateArgs*/ 0,
7195 CandidateSet);
7196
Douglas Gregor063daf62009-03-13 18:40:31 +00007197 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00007198 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00007199
7200 // Perform overload resolution.
7201 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007202 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007203 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00007204 // We found a built-in operator or an overloaded operator.
7205 FunctionDecl *FnDecl = Best->Function;
7206
7207 if (FnDecl) {
7208 // We matched an overloaded operator. Build a call to that
7209 // operator.
7210
7211 // Convert the arguments.
7212 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00007213 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00007214 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007215
John McCall60d7b3a2010-08-24 06:29:42 +00007216 ExprResult Arg1
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007217 = PerformCopyInitialization(
7218 InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007219 Context,
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007220 FnDecl->getParamDecl(0)),
7221 SourceLocation(),
7222 Owned(Args[1]));
7223 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007224 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007225
Douglas Gregor5fccd362010-03-03 23:55:11 +00007226 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007227 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007228 return ExprError();
7229
7230 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007231 } else {
7232 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007233 ExprResult Arg0
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007234 = PerformCopyInitialization(
7235 InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007236 Context,
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007237 FnDecl->getParamDecl(0)),
7238 SourceLocation(),
7239 Owned(Args[0]));
7240 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007241 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007242
John McCall60d7b3a2010-08-24 06:29:42 +00007243 ExprResult Arg1
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007244 = PerformCopyInitialization(
7245 InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007246 Context,
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007247 FnDecl->getParamDecl(1)),
7248 SourceLocation(),
7249 Owned(Args[1]));
7250 if (Arg1.isInvalid())
7251 return ExprError();
7252 Args[0] = LHS = Arg0.takeAs<Expr>();
7253 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007254 }
7255
John McCallb697e082010-05-06 18:15:07 +00007256 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7257
Douglas Gregor063daf62009-03-13 18:40:31 +00007258 // Determine the result type
7259 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007260 = FnDecl->getType()->getAs<FunctionType>()
7261 ->getCallResultType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00007262
7263 // Build the actual expression node.
7264 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00007265 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007266 UsualUnaryConversions(FnExpr);
7267
John McCall9ae2f072010-08-23 23:25:46 +00007268 CXXOperatorCallExpr *TheCall =
7269 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7270 Args, 2, ResultTy, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007271
John McCall9ae2f072010-08-23 23:25:46 +00007272 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00007273 FnDecl))
7274 return ExprError();
7275
John McCall9ae2f072010-08-23 23:25:46 +00007276 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00007277 } else {
7278 // We matched a built-in operator. Convert the arguments, then
7279 // break out so that we will build the appropriate built-in
7280 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007281 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007282 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007283 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007284 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00007285 return ExprError();
7286
7287 break;
7288 }
7289 }
7290
Douglas Gregor33074752009-09-30 21:46:01 +00007291 case OR_No_Viable_Function: {
7292 // C++ [over.match.oper]p9:
7293 // If the operator is the operator , [...] and there are no
7294 // viable functions, then the operator is assumed to be the
7295 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00007296 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00007297 break;
7298
Sebastian Redl8593c782009-05-21 11:50:50 +00007299 // For class as left operand for assignment or compound assigment operator
7300 // do not fall through to handling in built-in, but report that no overloaded
7301 // assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00007302 ExprResult Result = ExprError();
Douglas Gregor33074752009-09-30 21:46:01 +00007303 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00007304 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00007305 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7306 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007307 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00007308 } else {
7309 // No viable function; try to create a built-in operation, which will
7310 // produce an error. Then, show the non-viable candidates.
7311 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00007312 }
Douglas Gregor33074752009-09-30 21:46:01 +00007313 assert(Result.isInvalid() &&
7314 "C++ binary operator overloading is missing candidates!");
7315 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00007316 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7317 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00007318 return move(Result);
7319 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007320
7321 case OR_Ambiguous:
7322 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7323 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007324 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007325 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7326 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007327 return ExprError();
7328
7329 case OR_Deleted:
7330 Diag(OpLoc, diag::err_ovl_deleted_oper)
7331 << Best->Function->isDeleted()
7332 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007333 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007334 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00007335 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00007336 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007337
Douglas Gregor33074752009-09-30 21:46:01 +00007338 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007339 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007340}
7341
John McCall60d7b3a2010-08-24 06:29:42 +00007342ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +00007343Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7344 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007345 Expr *Base, Expr *Idx) {
7346 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +00007347 DeclarationName OpName =
7348 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7349
7350 // If either side is type-dependent, create an appropriate dependent
7351 // expression.
7352 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7353
John McCallc373d482010-01-27 01:50:18 +00007354 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007355 // CHECKME: no 'operator' keyword?
7356 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7357 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00007358 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007359 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007360 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007361 /*ADL*/ true, /*Overloaded*/ false,
7362 UnresolvedSetIterator(),
7363 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00007364 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00007365
Sebastian Redlf322ed62009-10-29 20:17:01 +00007366 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7367 Args, 2,
7368 Context.DependentTy,
7369 RLoc));
7370 }
7371
7372 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007373 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007374
7375 // Subscript can only be overloaded as a member function.
7376
7377 // Add operator candidates that are member functions.
7378 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7379
7380 // Add builtin operator candidates.
7381 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7382
7383 // Perform overload resolution.
7384 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007385 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00007386 case OR_Success: {
7387 // We found a built-in operator or an overloaded operator.
7388 FunctionDecl *FnDecl = Best->Function;
7389
7390 if (FnDecl) {
7391 // We matched an overloaded operator. Build a call to that
7392 // operator.
7393
John McCall9aa472c2010-03-19 07:35:19 +00007394 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007395 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00007396
Sebastian Redlf322ed62009-10-29 20:17:01 +00007397 // Convert the arguments.
7398 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007399 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007400 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007401 return ExprError();
7402
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007403 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007404 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007405 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007406 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007407 FnDecl->getParamDecl(0)),
7408 SourceLocation(),
7409 Owned(Args[1]));
7410 if (InputInit.isInvalid())
7411 return ExprError();
7412
7413 Args[1] = InputInit.takeAs<Expr>();
7414
Sebastian Redlf322ed62009-10-29 20:17:01 +00007415 // Determine the result type
7416 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007417 = FnDecl->getType()->getAs<FunctionType>()
7418 ->getCallResultType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007419
7420 // Build the actual expression node.
7421 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7422 LLoc);
7423 UsualUnaryConversions(FnExpr);
7424
John McCall9ae2f072010-08-23 23:25:46 +00007425 CXXOperatorCallExpr *TheCall =
7426 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7427 FnExpr, Args, 2,
7428 ResultTy, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007429
John McCall9ae2f072010-08-23 23:25:46 +00007430 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007431 FnDecl))
7432 return ExprError();
7433
John McCall9ae2f072010-08-23 23:25:46 +00007434 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007435 } else {
7436 // We matched a built-in operator. Convert the arguments, then
7437 // break out so that we will build the appropriate built-in
7438 // operator node.
7439 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007440 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00007441 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007442 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007443 return ExprError();
7444
7445 break;
7446 }
7447 }
7448
7449 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00007450 if (CandidateSet.empty())
7451 Diag(LLoc, diag::err_ovl_no_oper)
7452 << Args[0]->getType() << /*subscript*/ 0
7453 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7454 else
7455 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7456 << Args[0]->getType()
7457 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007458 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7459 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +00007460 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00007461 }
7462
7463 case OR_Ambiguous:
7464 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7465 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007466 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7467 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007468 return ExprError();
7469
7470 case OR_Deleted:
7471 Diag(LLoc, diag::err_ovl_deleted_oper)
7472 << Best->Function->isDeleted() << "[]"
7473 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007474 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7475 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007476 return ExprError();
7477 }
7478
7479 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +00007480 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007481}
7482
Douglas Gregor88a35142008-12-22 05:46:06 +00007483/// BuildCallToMemberFunction - Build a call to a member
7484/// function. MemExpr is the expression that refers to the member
7485/// function (and includes the object parameter), Args/NumArgs are the
7486/// arguments to the function call (not including the object
7487/// parameter). The caller needs to validate that the member
7488/// expression refers to a member function or an overloaded member
7489/// function.
John McCall60d7b3a2010-08-24 06:29:42 +00007490ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007491Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7492 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +00007493 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007494 // Dig out the member expression. This holds both the object
7495 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00007496 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7497
John McCall129e2df2009-11-30 22:42:35 +00007498 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00007499 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00007500 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007501 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00007502 if (isa<MemberExpr>(NakedMemExpr)) {
7503 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00007504 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00007505 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00007506 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00007507 } else {
7508 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007509 Qualifier = UnresExpr->getQualifier();
7510
John McCall701c89e2009-12-03 04:06:58 +00007511 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00007512
Douglas Gregor88a35142008-12-22 05:46:06 +00007513 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00007514 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00007515
John McCallaa81e162009-12-01 22:10:20 +00007516 // FIXME: avoid copy.
7517 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7518 if (UnresExpr->hasExplicitTemplateArgs()) {
7519 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7520 TemplateArgs = &TemplateArgsBuffer;
7521 }
7522
John McCall129e2df2009-11-30 22:42:35 +00007523 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7524 E = UnresExpr->decls_end(); I != E; ++I) {
7525
John McCall701c89e2009-12-03 04:06:58 +00007526 NamedDecl *Func = *I;
7527 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7528 if (isa<UsingShadowDecl>(Func))
7529 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7530
John McCall129e2df2009-11-30 22:42:35 +00007531 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007532 // If explicit template arguments were provided, we can't call a
7533 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00007534 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007535 continue;
7536
John McCall9aa472c2010-03-19 07:35:19 +00007537 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00007538 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00007539 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007540 } else {
John McCall129e2df2009-11-30 22:42:35 +00007541 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00007542 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00007543 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00007544 CandidateSet,
7545 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007546 }
Douglas Gregordec06662009-08-21 18:42:58 +00007547 }
Mike Stump1eb44332009-09-09 15:08:12 +00007548
John McCall129e2df2009-11-30 22:42:35 +00007549 DeclarationName DeclName = UnresExpr->getMemberName();
7550
Douglas Gregor88a35142008-12-22 05:46:06 +00007551 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007552 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
7553 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007554 case OR_Success:
7555 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007556 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00007557 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007558 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00007559 break;
7560
7561 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00007562 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00007563 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007564 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007565 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007566 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007567 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007568
7569 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00007570 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007571 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007572 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007573 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007574 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007575
7576 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00007577 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007578 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00007579 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007580 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007581 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007582 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007583 }
7584
John McCall6bb80172010-03-30 21:47:33 +00007585 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00007586
John McCallaa81e162009-12-01 22:10:20 +00007587 // If overload resolution picked a static member, build a
7588 // non-member call based on that function.
7589 if (Method->isStatic()) {
7590 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7591 Args, NumArgs, RParenLoc);
7592 }
7593
John McCall129e2df2009-11-30 22:42:35 +00007594 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00007595 }
7596
7597 assert(Method && "Member call to something that isn't a method?");
John McCall9ae2f072010-08-23 23:25:46 +00007598 CXXMemberCallExpr *TheCall =
7599 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
7600 Method->getCallResultType(),
7601 RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +00007602
Anders Carlssoneed3e692009-10-10 00:06:20 +00007603 // Check for a valid return type.
7604 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +00007605 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +00007606 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00007607
Douglas Gregor88a35142008-12-22 05:46:06 +00007608 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00007609 // We only need to do this if there was actually an overload; otherwise
7610 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00007611 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00007612 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00007613 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7614 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00007615 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007616 MemExpr->setBase(ObjectArg);
7617
7618 // Convert the rest of the arguments
Douglas Gregor5f970ee2010-05-04 18:18:31 +00007619 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +00007620 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00007621 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00007622 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007623
John McCall9ae2f072010-08-23 23:25:46 +00007624 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +00007625 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00007626
John McCall9ae2f072010-08-23 23:25:46 +00007627 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +00007628}
7629
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007630/// BuildCallToObjectOfClassType - Build a call to an object of class
7631/// type (C++ [over.call.object]), which can end up invoking an
7632/// overloaded function call operator (@c operator()) or performing a
7633/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +00007634ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007635Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00007636 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007637 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007638 SourceLocation RParenLoc) {
7639 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00007640 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007641
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007642 // C++ [over.call.object]p1:
7643 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00007644 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007645 // candidate functions includes at least the function call
7646 // operators of T. The function call operators of T are obtained by
7647 // ordinary lookup of the name operator() in the context of
7648 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00007649 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00007650 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00007651
7652 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007653 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00007654 << Object->getSourceRange()))
7655 return true;
7656
John McCalla24dc2e2009-11-17 02:14:36 +00007657 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7658 LookupQualifiedName(R, Record->getDecl());
7659 R.suppressDiagnostics();
7660
Douglas Gregor593564b2009-11-15 07:48:03 +00007661 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00007662 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007663 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00007664 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00007665 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00007666 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00007667
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007668 // C++ [over.call.object]p2:
7669 // In addition, for each conversion function declared in T of the
7670 // form
7671 //
7672 // operator conversion-type-id () cv-qualifier;
7673 //
7674 // where cv-qualifier is the same cv-qualification as, or a
7675 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00007676 // denotes the type "pointer to function of (P1,...,Pn) returning
7677 // R", or the type "reference to pointer to function of
7678 // (P1,...,Pn) returning R", or the type "reference to function
7679 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007680 // is also considered as a candidate function. Similarly,
7681 // surrogate call functions are added to the set of candidate
7682 // functions for each conversion function declared in an
7683 // accessible base class provided the function is not hidden
7684 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00007685 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00007686 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00007687 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00007688 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00007689 NamedDecl *D = *I;
7690 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7691 if (isa<UsingShadowDecl>(D))
7692 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7693
Douglas Gregor4a27d702009-10-21 06:18:39 +00007694 // Skip over templated conversion functions; they aren't
7695 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00007696 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00007697 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007698
John McCall701c89e2009-12-03 04:06:58 +00007699 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00007700
Douglas Gregor4a27d702009-10-21 06:18:39 +00007701 // Strip the reference type (if any) and then the pointer type (if
7702 // any) to get down to what might be a function type.
7703 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7704 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7705 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007706
Douglas Gregor4a27d702009-10-21 06:18:39 +00007707 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00007708 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00007709 Object->getType(), Args, NumArgs,
7710 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007711 }
Mike Stump1eb44332009-09-09 15:08:12 +00007712
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007713 // Perform overload resolution.
7714 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007715 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7716 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007717 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007718 // Overload resolution succeeded; we'll build the appropriate call
7719 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007720 break;
7721
7722 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00007723 if (CandidateSet.empty())
7724 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7725 << Object->getType() << /*call*/ 1
7726 << Object->getSourceRange();
7727 else
7728 Diag(Object->getSourceRange().getBegin(),
7729 diag::err_ovl_no_viable_object_call)
7730 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007731 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007732 break;
7733
7734 case OR_Ambiguous:
7735 Diag(Object->getSourceRange().getBegin(),
7736 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00007737 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007738 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007739 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007740
7741 case OR_Deleted:
7742 Diag(Object->getSourceRange().getBegin(),
7743 diag::err_ovl_deleted_object_call)
7744 << Best->Function->isDeleted()
7745 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007746 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007747 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007748 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007749
Douglas Gregorff331c12010-07-25 18:17:45 +00007750 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007751 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007752
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007753 if (Best->Function == 0) {
7754 // Since there is no function declaration, this is one of the
7755 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00007756 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007757 = cast<CXXConversionDecl>(
7758 Best->Conversions[0].UserDefined.ConversionFunction);
7759
John McCall9aa472c2010-03-19 07:35:19 +00007760 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007761 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007762
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007763 // We selected one of the surrogate functions that converts the
7764 // object parameter to a function pointer. Perform the conversion
7765 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007766
7767 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007768 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00007769 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7770 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007771
John McCallf312b1e2010-08-26 23:41:50 +00007772 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007773 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007774 }
7775
John McCall9aa472c2010-03-19 07:35:19 +00007776 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007777 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007778
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007779 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7780 // that calls this method, using Object for the implicit object
7781 // parameter and passing along the remaining arguments.
7782 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00007783 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007784
7785 unsigned NumArgsInProto = Proto->getNumArgs();
7786 unsigned NumArgsToCheck = NumArgs;
7787
7788 // Build the full argument list for the method call (the
7789 // implicit object parameter is placed at the beginning of the
7790 // list).
7791 Expr **MethodArgs;
7792 if (NumArgs < NumArgsInProto) {
7793 NumArgsToCheck = NumArgsInProto;
7794 MethodArgs = new Expr*[NumArgsInProto + 1];
7795 } else {
7796 MethodArgs = new Expr*[NumArgs + 1];
7797 }
7798 MethodArgs[0] = Object;
7799 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7800 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00007801
7802 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00007803 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007804 UsualUnaryConversions(NewFn);
7805
7806 // Once we've built TheCall, all of the expressions are properly
7807 // owned.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007808 QualType ResultTy = Method->getCallResultType();
John McCall9ae2f072010-08-23 23:25:46 +00007809 CXXOperatorCallExpr *TheCall =
7810 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7811 MethodArgs, NumArgs + 1,
7812 ResultTy, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007813 delete [] MethodArgs;
7814
John McCall9ae2f072010-08-23 23:25:46 +00007815 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +00007816 Method))
7817 return true;
7818
Douglas Gregor518fda12009-01-13 05:10:00 +00007819 // We may have default arguments. If so, we need to allocate more
7820 // slots in the call for them.
7821 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007822 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00007823 else if (NumArgs > NumArgsInProto)
7824 NumArgsToCheck = NumArgsInProto;
7825
Chris Lattner312531a2009-04-12 08:11:20 +00007826 bool IsError = false;
7827
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007828 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00007829 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007830 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007831 TheCall->setArg(0, Object);
7832
Chris Lattner312531a2009-04-12 08:11:20 +00007833
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007834 // Check the argument types.
7835 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007836 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00007837 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007838 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00007839
Douglas Gregor518fda12009-01-13 05:10:00 +00007840 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00007841
John McCall60d7b3a2010-08-24 06:29:42 +00007842 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +00007843 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007844 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +00007845 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +00007846 SourceLocation(), Arg);
Anders Carlsson3faa4862010-01-29 18:43:53 +00007847
7848 IsError |= InputInit.isInvalid();
7849 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007850 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00007851 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +00007852 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7853 if (DefArg.isInvalid()) {
7854 IsError = true;
7855 break;
7856 }
7857
7858 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007859 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007860
7861 TheCall->setArg(i + 1, Arg);
7862 }
7863
7864 // If this is a variadic call, handle args passed through "...".
7865 if (Proto->isVariadic()) {
7866 // Promote the arguments (C99 6.5.2.2p7).
7867 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7868 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00007869 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007870 TheCall->setArg(i + 1, Arg);
7871 }
7872 }
7873
Chris Lattner312531a2009-04-12 08:11:20 +00007874 if (IsError) return true;
7875
John McCall9ae2f072010-08-23 23:25:46 +00007876 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00007877 return true;
7878
John McCall182f7092010-08-24 06:09:16 +00007879 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007880}
7881
Douglas Gregor8ba10742008-11-20 16:27:02 +00007882/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00007883/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00007884/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +00007885ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00007886Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007887 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00007888
John McCall5769d612010-02-08 23:07:23 +00007889 SourceLocation Loc = Base->getExprLoc();
7890
Douglas Gregor8ba10742008-11-20 16:27:02 +00007891 // C++ [over.ref]p1:
7892 //
7893 // [...] An expression x->m is interpreted as (x.operator->())->m
7894 // for a class object x of type T if T::operator->() exists and if
7895 // the operator is selected as the best match function by the
7896 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00007897 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00007898 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00007899 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007900
John McCall5769d612010-02-08 23:07:23 +00007901 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00007902 PDiag(diag::err_typecheck_incomplete_tag)
7903 << Base->getSourceRange()))
7904 return ExprError();
7905
John McCalla24dc2e2009-11-17 02:14:36 +00007906 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7907 LookupQualifiedName(R, BaseRecord->getDecl());
7908 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00007909
7910 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00007911 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007912 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00007913 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00007914 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00007915
7916 // Perform overload resolution.
7917 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007918 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007919 case OR_Success:
7920 // Overload resolution succeeded; we'll build the call below.
7921 break;
7922
7923 case OR_No_Viable_Function:
7924 if (CandidateSet.empty())
7925 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007926 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007927 else
7928 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007929 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007930 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007931 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007932
7933 case OR_Ambiguous:
7934 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00007935 << "->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007936 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007937 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007938
7939 case OR_Deleted:
7940 Diag(OpLoc, diag::err_ovl_deleted_oper)
7941 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00007942 << "->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007943 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007944 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007945 }
7946
John McCall9aa472c2010-03-19 07:35:19 +00007947 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007948 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00007949
Douglas Gregor8ba10742008-11-20 16:27:02 +00007950 // Convert the object parameter.
7951 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007952 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7953 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007954 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00007955
Douglas Gregor8ba10742008-11-20 16:27:02 +00007956 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00007957 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7958 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007959 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007960
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007961 QualType ResultTy = Method->getCallResultType();
John McCall9ae2f072010-08-23 23:25:46 +00007962 CXXOperatorCallExpr *TheCall =
7963 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7964 &Base, 1, ResultTy, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007965
John McCall9ae2f072010-08-23 23:25:46 +00007966 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00007967 Method))
7968 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00007969 return Owned(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00007970}
7971
Douglas Gregor904eed32008-11-10 20:40:00 +00007972/// FixOverloadedFunctionReference - E is an expression that refers to
7973/// a C++ overloaded function (possibly with some parentheses and
7974/// perhaps a '&' around it). We have resolved the overloaded function
7975/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00007976/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00007977Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00007978 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00007979 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007980 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7981 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007982 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00007983 return PE;
Douglas Gregor699ee522009-11-20 19:42:02 +00007984
7985 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7986 }
7987
7988 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007989 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7990 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00007991 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00007992 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00007993 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +00007994 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +00007995 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00007996 return ICE;
Douglas Gregor699ee522009-11-20 19:42:02 +00007997
John McCallf871d0c2010-08-07 06:22:56 +00007998 return ImplicitCastExpr::Create(Context, ICE->getType(),
7999 ICE->getCastKind(),
8000 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00008001 ICE->getValueKind());
Douglas Gregor699ee522009-11-20 19:42:02 +00008002 }
8003
8004 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00008005 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00008006 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00008007 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8008 if (Method->isStatic()) {
8009 // Do nothing: static member functions aren't any different
8010 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00008011 } else {
John McCallf7a1a742009-11-24 19:00:30 +00008012 // Fix the sub expression, which really has to be an
8013 // UnresolvedLookupExpr holding an overloaded member function
8014 // or template.
John McCall6bb80172010-03-30 21:47:33 +00008015 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8016 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00008017 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008018 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +00008019
John McCallba135432009-11-21 08:51:07 +00008020 assert(isa<DeclRefExpr>(SubExpr)
8021 && "fixed to something other than a decl ref");
8022 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8023 && "fixed to a member ref with no nested name qualifier");
8024
8025 // We have taken the address of a pointer to member
8026 // function. Perform the computation here so that we get the
8027 // appropriate pointer to member type.
8028 QualType ClassType
8029 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8030 QualType MemPtrType
8031 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8032
John McCall2de56d12010-08-25 11:45:40 +00008033 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
John McCallba135432009-11-21 08:51:07 +00008034 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00008035 }
8036 }
John McCall6bb80172010-03-30 21:47:33 +00008037 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8038 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00008039 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008040 return UnOp;
Anders Carlsson96ad5332009-10-21 17:16:23 +00008041
John McCall2de56d12010-08-25 11:45:40 +00008042 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +00008043 Context.getPointerType(SubExpr->getType()),
8044 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00008045 }
John McCallba135432009-11-21 08:51:07 +00008046
8047 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00008048 // FIXME: avoid copy.
8049 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00008050 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00008051 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8052 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00008053 }
8054
John McCallba135432009-11-21 08:51:07 +00008055 return DeclRefExpr::Create(Context,
8056 ULE->getQualifier(),
8057 ULE->getQualifierRange(),
8058 Fn,
8059 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00008060 Fn->getType(),
8061 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00008062 }
8063
John McCall129e2df2009-11-30 22:42:35 +00008064 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00008065 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00008066 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8067 if (MemExpr->hasExplicitTemplateArgs()) {
8068 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8069 TemplateArgs = &TemplateArgsBuffer;
8070 }
John McCalld5532b62009-11-23 01:53:49 +00008071
John McCallaa81e162009-12-01 22:10:20 +00008072 Expr *Base;
8073
8074 // If we're filling in
8075 if (MemExpr->isImplicitAccess()) {
8076 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8077 return DeclRefExpr::Create(Context,
8078 MemExpr->getQualifier(),
8079 MemExpr->getQualifierRange(),
8080 Fn,
8081 MemExpr->getMemberLoc(),
8082 Fn->getType(),
8083 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00008084 } else {
8085 SourceLocation Loc = MemExpr->getMemberLoc();
8086 if (MemExpr->getQualifier())
8087 Loc = MemExpr->getQualifierRange().getBegin();
8088 Base = new (Context) CXXThisExpr(Loc,
8089 MemExpr->getBaseType(),
8090 /*isImplicit=*/true);
8091 }
John McCallaa81e162009-12-01 22:10:20 +00008092 } else
John McCall3fa5cae2010-10-26 07:05:15 +00008093 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +00008094
8095 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00008096 MemExpr->isArrow(),
8097 MemExpr->getQualifier(),
8098 MemExpr->getQualifierRange(),
8099 Fn,
John McCall6bb80172010-03-30 21:47:33 +00008100 Found,
Abramo Bagnara25777432010-08-11 22:01:17 +00008101 MemExpr->getMemberNameInfo(),
John McCallaa81e162009-12-01 22:10:20 +00008102 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00008103 Fn->getType());
8104 }
8105
John McCall3fa5cae2010-10-26 07:05:15 +00008106 llvm_unreachable("Invalid reference to overloaded function");
8107 return E;
Douglas Gregor904eed32008-11-10 20:40:00 +00008108}
8109
John McCall60d7b3a2010-08-24 06:29:42 +00008110ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8111 DeclAccessPair Found,
8112 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00008113 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00008114}
8115
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008116} // end namespace clang