blob: 06c097c620c636d748051dc1aaa153c1ce9d6edf [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCall0e800c92010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000036
John McCallf89e55a2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
John Wiegley429bb272011-04-08 18:41:53 +000039static ExprResult
John McCallf89e55a2010-11-18 06:31:45 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41 SourceLocation Loc = SourceLocation()) {
John Wiegley429bb272011-04-08 18:41:53 +000042 ExprResult E = S.Owned(new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc));
43 E = S.DefaultFunctionArrayConversion(E.take());
44 if (E.isInvalid())
45 return ExprError();
46 return move(E);
John McCallf89e55a2010-11-18 06:31:45 +000047}
48
John McCall120d63c2010-08-24 20:38:10 +000049static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
50 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000051 StandardConversionSequence &SCS,
52 bool CStyle);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000053
54static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
55 QualType &ToType,
56 bool InOverloadResolution,
57 StandardConversionSequence &SCS,
58 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000059static OverloadingResult
60IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
61 UserDefinedConversionSequence& User,
62 OverloadCandidateSet& Conversions,
63 bool AllowExplicit);
64
65
66static ImplicitConversionSequence::CompareKind
67CompareStandardConversionSequences(Sema &S,
68 const StandardConversionSequence& SCS1,
69 const StandardConversionSequence& SCS2);
70
71static ImplicitConversionSequence::CompareKind
72CompareQualificationConversions(Sema &S,
73 const StandardConversionSequence& SCS1,
74 const StandardConversionSequence& SCS2);
75
76static ImplicitConversionSequence::CompareKind
77CompareDerivedToBaseConversions(Sema &S,
78 const StandardConversionSequence& SCS1,
79 const StandardConversionSequence& SCS2);
80
81
82
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000083/// GetConversionCategory - Retrieve the implicit conversion
84/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000085ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000086GetConversionCategory(ImplicitConversionKind Kind) {
87 static const ImplicitConversionCategory
88 Category[(int)ICK_Num_Conversion_Kinds] = {
89 ICC_Identity,
90 ICC_Lvalue_Transformation,
91 ICC_Lvalue_Transformation,
92 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000093 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000094 ICC_Qualification_Adjustment,
95 ICC_Promotion,
96 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000097 ICC_Promotion,
98 ICC_Conversion,
99 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000100 ICC_Conversion,
101 ICC_Conversion,
102 ICC_Conversion,
103 ICC_Conversion,
104 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000105 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000106 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000107 ICC_Conversion,
108 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000109 ICC_Conversion
110 };
111 return Category[(int)Kind];
112}
113
114/// GetConversionRank - Retrieve the implicit conversion rank
115/// corresponding to the given implicit conversion kind.
116ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
117 static const ImplicitConversionRank
118 Rank[(int)ICK_Num_Conversion_Kinds] = {
119 ICR_Exact_Match,
120 ICR_Exact_Match,
121 ICR_Exact_Match,
122 ICR_Exact_Match,
123 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000124 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000125 ICR_Promotion,
126 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000127 ICR_Promotion,
128 ICR_Conversion,
129 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000130 ICR_Conversion,
131 ICR_Conversion,
132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000135 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000136 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000137 ICR_Conversion,
138 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000139 ICR_Complex_Real_Conversion,
140 ICR_Conversion,
141 ICR_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000142 };
143 return Rank[(int)Kind];
144}
145
146/// GetImplicitConversionName - Return the name of this kind of
147/// implicit conversion.
148const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000149 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000150 "No conversion",
151 "Lvalue-to-rvalue",
152 "Array-to-pointer",
153 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000154 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000155 "Qualification",
156 "Integral promotion",
157 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000158 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000159 "Integral conversion",
160 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000161 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000162 "Floating-integral conversion",
163 "Pointer conversion",
164 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000165 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000166 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000167 "Derived-to-base conversion",
168 "Vector conversion",
169 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000170 "Complex-real conversion",
171 "Block Pointer conversion",
172 "Transparent Union Conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000173 };
174 return Name[Kind];
175}
176
Douglas Gregor60d62c22008-10-31 16:23:19 +0000177/// StandardConversionSequence - Set the standard conversion
178/// sequence to the identity conversion.
179void StandardConversionSequence::setAsIdentityConversion() {
180 First = ICK_Identity;
181 Second = ICK_Identity;
182 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000183 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000184 ReferenceBinding = false;
185 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000186 IsLvalueReference = true;
187 BindsToFunctionLvalue = false;
188 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000189 BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000190 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000191}
192
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000193/// getRank - Retrieve the rank of this standard conversion sequence
194/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
195/// implicit conversions.
196ImplicitConversionRank StandardConversionSequence::getRank() const {
197 ImplicitConversionRank Rank = ICR_Exact_Match;
198 if (GetConversionRank(First) > Rank)
199 Rank = GetConversionRank(First);
200 if (GetConversionRank(Second) > Rank)
201 Rank = GetConversionRank(Second);
202 if (GetConversionRank(Third) > Rank)
203 Rank = GetConversionRank(Third);
204 return Rank;
205}
206
207/// isPointerConversionToBool - Determines whether this conversion is
208/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000209/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000210/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000211bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000212 // Note that FromType has not necessarily been transformed by the
213 // array-to-pointer or function-to-pointer implicit conversions, so
214 // check for their presence as well as checking whether FromType is
215 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000216 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000217 (getFromType()->isPointerType() ||
218 getFromType()->isObjCObjectPointerType() ||
219 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000220 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000221 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
222 return true;
223
224 return false;
225}
226
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000227/// isPointerConversionToVoidPointer - Determines whether this
228/// conversion is a conversion of a pointer to a void pointer. This is
229/// used as part of the ranking of standard conversion sequences (C++
230/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000231bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000232StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000233isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000234 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000235 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000236
237 // Note that FromType has not necessarily been transformed by the
238 // array-to-pointer implicit conversion, so check for its presence
239 // and redo the conversion to get a pointer.
240 if (First == ICK_Array_To_Pointer)
241 FromType = Context.getArrayDecayedType(FromType);
242
Douglas Gregorf9af5242011-04-15 20:45:44 +0000243 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000244 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000245 return ToPtrType->getPointeeType()->isVoidType();
246
247 return false;
248}
249
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000250/// DebugPrint - Print this standard conversion sequence to standard
251/// error. Useful for debugging overloading issues.
252void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000253 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000254 bool PrintedSomething = false;
255 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000256 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000257 PrintedSomething = true;
258 }
259
260 if (Second != ICK_Identity) {
261 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000262 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000263 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000264 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000265
266 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000267 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000268 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000269 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000270 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000271 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000272 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000273 PrintedSomething = true;
274 }
275
276 if (Third != ICK_Identity) {
277 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000278 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000279 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000280 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000281 PrintedSomething = true;
282 }
283
284 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000285 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000286 }
287}
288
289/// DebugPrint - Print this user-defined conversion sequence to standard
290/// error. Useful for debugging overloading issues.
291void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000292 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000293 if (Before.First || Before.Second || Before.Third) {
294 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000295 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000296 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000297 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000298 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000299 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000300 After.DebugPrint();
301 }
302}
303
304/// DebugPrint - Print this implicit conversion sequence to standard
305/// error. Useful for debugging overloading issues.
306void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000307 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000308 switch (ConversionKind) {
309 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000310 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000311 Standard.DebugPrint();
312 break;
313 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000314 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000315 UserDefined.DebugPrint();
316 break;
317 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000318 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000319 break;
John McCall1d318332010-01-12 00:44:57 +0000320 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000321 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000322 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000323 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000324 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000325 break;
326 }
327
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000328 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000329}
330
John McCall1d318332010-01-12 00:44:57 +0000331void AmbiguousConversionSequence::construct() {
332 new (&conversions()) ConversionSet();
333}
334
335void AmbiguousConversionSequence::destruct() {
336 conversions().~ConversionSet();
337}
338
339void
340AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
341 FromTypePtr = O.FromTypePtr;
342 ToTypePtr = O.ToTypePtr;
343 new (&conversions()) ConversionSet(O.conversions());
344}
345
Douglas Gregora9333192010-05-08 17:41:32 +0000346namespace {
347 // Structure used by OverloadCandidate::DeductionFailureInfo to store
348 // template parameter and template argument information.
349 struct DFIParamWithArguments {
350 TemplateParameter Param;
351 TemplateArgument FirstArg;
352 TemplateArgument SecondArg;
353 };
354}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000355
Douglas Gregora9333192010-05-08 17:41:32 +0000356/// \brief Convert from Sema's representation of template deduction information
357/// to the form used in overload-candidate information.
358OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000359static MakeDeductionFailureInfo(ASTContext &Context,
360 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000361 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000362 OverloadCandidate::DeductionFailureInfo Result;
363 Result.Result = static_cast<unsigned>(TDK);
364 Result.Data = 0;
365 switch (TDK) {
366 case Sema::TDK_Success:
367 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000368 case Sema::TDK_TooManyArguments:
369 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000370 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000371
Douglas Gregora9333192010-05-08 17:41:32 +0000372 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000373 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000374 Result.Data = Info.Param.getOpaqueValue();
375 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000376
Douglas Gregora9333192010-05-08 17:41:32 +0000377 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000378 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000379 // FIXME: Should allocate from normal heap so that we can free this later.
380 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000381 Saved->Param = Info.Param;
382 Saved->FirstArg = Info.FirstArg;
383 Saved->SecondArg = Info.SecondArg;
384 Result.Data = Saved;
385 break;
386 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000387
Douglas Gregora9333192010-05-08 17:41:32 +0000388 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000389 Result.Data = Info.take();
390 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000391
Douglas Gregora9333192010-05-08 17:41:32 +0000392 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000393 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000394 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000395 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000396
Douglas Gregora9333192010-05-08 17:41:32 +0000397 return Result;
398}
John McCall1d318332010-01-12 00:44:57 +0000399
Douglas Gregora9333192010-05-08 17:41:32 +0000400void OverloadCandidate::DeductionFailureInfo::Destroy() {
401 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
402 case Sema::TDK_Success:
403 case Sema::TDK_InstantiationDepth:
404 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000405 case Sema::TDK_TooManyArguments:
406 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000407 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000408 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000409
Douglas Gregora9333192010-05-08 17:41:32 +0000410 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000411 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000412 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000413 Data = 0;
414 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000415
416 case Sema::TDK_SubstitutionFailure:
417 // FIXME: Destroy the template arugment list?
418 Data = 0;
419 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000420
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000421 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000422 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000423 case Sema::TDK_FailedOverloadResolution:
424 break;
425 }
426}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000427
428TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000429OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
430 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
431 case Sema::TDK_Success:
432 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000433 case Sema::TDK_TooManyArguments:
434 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000435 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000436 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000437
Douglas Gregora9333192010-05-08 17:41:32 +0000438 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000439 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000440 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000441
442 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000443 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000444 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000445
Douglas Gregora9333192010-05-08 17:41:32 +0000446 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000447 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000448 case Sema::TDK_FailedOverloadResolution:
449 break;
450 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000451
Douglas Gregora9333192010-05-08 17:41:32 +0000452 return TemplateParameter();
453}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000454
Douglas Gregorec20f462010-05-08 20:07:26 +0000455TemplateArgumentList *
456OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
457 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
458 case Sema::TDK_Success:
459 case Sema::TDK_InstantiationDepth:
460 case Sema::TDK_TooManyArguments:
461 case Sema::TDK_TooFewArguments:
462 case Sema::TDK_Incomplete:
463 case Sema::TDK_InvalidExplicitArguments:
464 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000465 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000466 return 0;
467
468 case Sema::TDK_SubstitutionFailure:
469 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000470
Douglas Gregorec20f462010-05-08 20:07:26 +0000471 // Unhandled
472 case Sema::TDK_NonDeducedMismatch:
473 case Sema::TDK_FailedOverloadResolution:
474 break;
475 }
476
477 return 0;
478}
479
Douglas Gregora9333192010-05-08 17:41:32 +0000480const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
481 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
482 case Sema::TDK_Success:
483 case Sema::TDK_InstantiationDepth:
484 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000485 case Sema::TDK_TooManyArguments:
486 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000487 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000488 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000489 return 0;
490
Douglas Gregora9333192010-05-08 17:41:32 +0000491 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000492 case Sema::TDK_Underqualified:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000493 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000494
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000495 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000496 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000497 case Sema::TDK_FailedOverloadResolution:
498 break;
499 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000500
Douglas Gregora9333192010-05-08 17:41:32 +0000501 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000502}
Douglas Gregora9333192010-05-08 17:41:32 +0000503
504const TemplateArgument *
505OverloadCandidate::DeductionFailureInfo::getSecondArg() {
506 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
507 case Sema::TDK_Success:
508 case Sema::TDK_InstantiationDepth:
509 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000510 case Sema::TDK_TooManyArguments:
511 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000512 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000513 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000514 return 0;
515
Douglas Gregora9333192010-05-08 17:41:32 +0000516 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000517 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000518 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
519
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000520 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000521 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000522 case Sema::TDK_FailedOverloadResolution:
523 break;
524 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000525
Douglas Gregora9333192010-05-08 17:41:32 +0000526 return 0;
527}
528
529void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000530 inherited::clear();
531 Functions.clear();
532}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000533
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000534// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000535// overload of the declarations in Old. This routine returns false if
536// New and Old cannot be overloaded, e.g., if New has the same
537// signature as some function in Old (C++ 1.3.10) or if the Old
538// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000539// it does return false, MatchedDecl will point to the decl that New
540// cannot be overloaded with. This decl may be a UsingShadowDecl on
541// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000542//
543// Example: Given the following input:
544//
545// void f(int, float); // #1
546// void f(int, int); // #2
547// int f(int, int); // #3
548//
549// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000550// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000551//
John McCall51fa86f2009-12-02 08:47:38 +0000552// When we process #2, Old contains only the FunctionDecl for #1. By
553// comparing the parameter types, we see that #1 and #2 are overloaded
554// (since they have different signatures), so this routine returns
555// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000556//
John McCall51fa86f2009-12-02 08:47:38 +0000557// When we process #3, Old is an overload set containing #1 and #2. We
558// compare the signatures of #3 to #1 (they're overloaded, so we do
559// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
560// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000561// signature), IsOverload returns false and MatchedDecl will be set to
562// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000563//
564// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
565// into a class by a using declaration. The rules for whether to hide
566// shadow declarations ignore some properties which otherwise figure
567// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000568Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000569Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
570 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000571 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000572 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000573 NamedDecl *OldD = *I;
574
575 bool OldIsUsingDecl = false;
576 if (isa<UsingShadowDecl>(OldD)) {
577 OldIsUsingDecl = true;
578
579 // We can always introduce two using declarations into the same
580 // context, even if they have identical signatures.
581 if (NewIsUsingDecl) continue;
582
583 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
584 }
585
586 // If either declaration was introduced by a using declaration,
587 // we'll need to use slightly different rules for matching.
588 // Essentially, these rules are the normal rules, except that
589 // function templates hide function templates with different
590 // return types or template parameter lists.
591 bool UseMemberUsingDeclRules =
592 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
593
John McCall51fa86f2009-12-02 08:47:38 +0000594 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000595 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
596 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
597 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
598 continue;
599 }
600
John McCall871b2e72009-12-09 03:35:25 +0000601 Match = *I;
602 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000603 }
John McCall51fa86f2009-12-02 08:47:38 +0000604 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000605 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
606 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
607 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
608 continue;
609 }
610
John McCall871b2e72009-12-09 03:35:25 +0000611 Match = *I;
612 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000613 }
John McCalld7945c62010-11-10 03:01:53 +0000614 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000615 // We can overload with these, which can show up when doing
616 // redeclaration checks for UsingDecls.
617 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000618 } else if (isa<TagDecl>(OldD)) {
619 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000620 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
621 // Optimistically assume that an unresolved using decl will
622 // overload; if it doesn't, we'll have to diagnose during
623 // template instantiation.
624 } else {
John McCall68263142009-11-18 22:49:29 +0000625 // (C++ 13p1):
626 // Only function declarations can be overloaded; object and type
627 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000628 Match = *I;
629 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000630 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000631 }
John McCall68263142009-11-18 22:49:29 +0000632
John McCall871b2e72009-12-09 03:35:25 +0000633 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000634}
635
John McCallad00b772010-06-16 08:42:20 +0000636bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
637 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000638 // If both of the functions are extern "C", then they are not
639 // overloads.
640 if (Old->isExternC() && New->isExternC())
641 return false;
642
John McCall68263142009-11-18 22:49:29 +0000643 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
644 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
645
646 // C++ [temp.fct]p2:
647 // A function template can be overloaded with other function templates
648 // and with normal (non-template) functions.
649 if ((OldTemplate == 0) != (NewTemplate == 0))
650 return true;
651
652 // Is the function New an overload of the function Old?
653 QualType OldQType = Context.getCanonicalType(Old->getType());
654 QualType NewQType = Context.getCanonicalType(New->getType());
655
656 // Compare the signatures (C++ 1.3.10) of the two functions to
657 // determine whether they are overloads. If we find any mismatch
658 // in the signature, they are overloads.
659
660 // If either of these functions is a K&R-style function (no
661 // prototype), then we consider them to have matching signatures.
662 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
663 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
664 return false;
665
John McCallf4c73712011-01-19 06:33:43 +0000666 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
667 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000668
669 // The signature of a function includes the types of its
670 // parameters (C++ 1.3.10), which includes the presence or absence
671 // of the ellipsis; see C++ DR 357).
672 if (OldQType != NewQType &&
673 (OldType->getNumArgs() != NewType->getNumArgs() ||
674 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000675 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000676 return true;
677
678 // C++ [temp.over.link]p4:
679 // The signature of a function template consists of its function
680 // signature, its return type and its template parameter list. The names
681 // of the template parameters are significant only for establishing the
682 // relationship between the template parameters and the rest of the
683 // signature.
684 //
685 // We check the return type and template parameter lists for function
686 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000687 //
688 // However, we don't consider either of these when deciding whether
689 // a member introduced by a shadow declaration is hidden.
690 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000691 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
692 OldTemplate->getTemplateParameters(),
693 false, TPL_TemplateMatch) ||
694 OldType->getResultType() != NewType->getResultType()))
695 return true;
696
697 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000698 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +0000699 //
700 // As part of this, also check whether one of the member functions
701 // is static, in which case they are not overloads (C++
702 // 13.1p2). While not part of the definition of the signature,
703 // this check is important to determine whether these functions
704 // can be overloaded.
705 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
706 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
707 if (OldMethod && NewMethod &&
708 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000709 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-01-26 21:20:37 +0000710 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
711 if (!UseUsingDeclRules &&
712 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
713 (OldMethod->getRefQualifier() == RQ_None ||
714 NewMethod->getRefQualifier() == RQ_None)) {
715 // C++0x [over.load]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000716 // - Member function declarations with the same name and the same
717 // parameter-type-list as well as member function template
718 // declarations with the same name, the same parameter-type-list, and
719 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorb145ee62011-01-26 21:20:37 +0000720 // them, but not all, have a ref-qualifier (8.3.5).
721 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
722 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
723 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
724 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000725
John McCall68263142009-11-18 22:49:29 +0000726 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +0000727 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000728
John McCall68263142009-11-18 22:49:29 +0000729 // The signatures match; this is not an overload.
730 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000731}
732
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000733/// TryImplicitConversion - Attempt to perform an implicit conversion
734/// from the given expression (Expr) to the given type (ToType). This
735/// function returns an implicit conversion sequence that can be used
736/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000737///
738/// void f(float f);
739/// void g(int i) { f(i); }
740///
741/// this routine would produce an implicit conversion sequence to
742/// describe the initialization of f from i, which will be a standard
743/// conversion sequence containing an lvalue-to-rvalue conversion (C++
744/// 4.1) followed by a floating-integral conversion (C++ 4.9).
745//
746/// Note that this routine only determines how the conversion can be
747/// performed; it does not actually perform the conversion. As such,
748/// it will not produce any diagnostics if no conversion is available,
749/// but will instead return an implicit conversion sequence of kind
750/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000751///
752/// If @p SuppressUserConversions, then user-defined conversions are
753/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000754/// If @p AllowExplicit, then explicit user-defined conversions are
755/// permitted.
John McCall120d63c2010-08-24 20:38:10 +0000756static ImplicitConversionSequence
757TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
758 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000759 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000760 bool InOverloadResolution,
761 bool CStyle) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000762 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +0000763 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000764 ICS.Standard, CStyle)) {
John McCall1d318332010-01-12 00:44:57 +0000765 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000766 return ICS;
767 }
768
John McCall120d63c2010-08-24 20:38:10 +0000769 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000770 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000771 return ICS;
772 }
773
Douglas Gregor604eb652010-08-11 02:15:33 +0000774 // C++ [over.ics.user]p4:
775 // A conversion of an expression of class type to the same class
776 // type is given Exact Match rank, and a conversion of an
777 // expression of class type to a base class of that type is
778 // given Conversion rank, in spite of the fact that a copy/move
779 // constructor (i.e., a user-defined conversion function) is
780 // called for those cases.
781 QualType FromType = From->getType();
782 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +0000783 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
784 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000785 ICS.setStandard();
786 ICS.Standard.setAsIdentityConversion();
787 ICS.Standard.setFromType(FromType);
788 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000789
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000790 // We don't actually check at this point whether there is a valid
791 // copy/move constructor, since overloading just assumes that it
792 // exists. When we actually perform initialization, we'll find the
793 // appropriate constructor to copy the returned object, if needed.
794 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000795
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000796 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +0000797 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000798 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000799
Douglas Gregor604eb652010-08-11 02:15:33 +0000800 return ICS;
801 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000802
Douglas Gregor604eb652010-08-11 02:15:33 +0000803 if (SuppressUserConversions) {
804 // We're not in the case above, so there is no conversion that
805 // we can perform.
806 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000807 return ICS;
808 }
809
810 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000811 OverloadCandidateSet Conversions(From->getExprLoc());
812 OverloadingResult UserDefResult
John McCall120d63c2010-08-24 20:38:10 +0000813 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000814 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000815
816 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000817 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000818 // C++ [over.ics.user]p4:
819 // A conversion of an expression of class type to the same class
820 // type is given Exact Match rank, and a conversion of an
821 // expression of class type to a base class of that type is
822 // given Conversion rank, in spite of the fact that a copy
823 // constructor (i.e., a user-defined conversion function) is
824 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000825 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000826 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000827 QualType FromCanon
John McCall120d63c2010-08-24 20:38:10 +0000828 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
829 QualType ToCanon
830 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000831 if (Constructor->isCopyConstructor() &&
John McCall120d63c2010-08-24 20:38:10 +0000832 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000833 // Turn this into a "standard" conversion sequence, so that it
834 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000835 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000836 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000837 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000838 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000839 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000840 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000841 ICS.Standard.Second = ICK_Derived_To_Base;
842 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000843 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000844
845 // C++ [over.best.ics]p4:
846 // However, when considering the argument of a user-defined
847 // conversion function that is a candidate by 13.3.1.3 when
848 // invoked for the copying of the temporary in the second step
849 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
850 // 13.3.1.6 in all cases, only standard conversion sequences and
851 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000852 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000853 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000854 }
John McCallcefd3ad2010-01-13 22:30:33 +0000855 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000856 ICS.setAmbiguous();
857 ICS.Ambiguous.setFromType(From->getType());
858 ICS.Ambiguous.setToType(ToType);
859 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
860 Cand != Conversions.end(); ++Cand)
861 if (Cand->Viable)
862 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000863 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000864 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000865 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000866
867 return ICS;
868}
869
John McCall120d63c2010-08-24 20:38:10 +0000870bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
871 const InitializedEntity &Entity,
872 Expr *Initializer,
873 bool SuppressUserConversions,
874 bool AllowExplicitConversions,
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000875 bool InOverloadResolution,
876 bool CStyle) {
John McCall120d63c2010-08-24 20:38:10 +0000877 ImplicitConversionSequence ICS
878 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
879 SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000880 AllowExplicitConversions,
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000881 InOverloadResolution,
882 CStyle);
John McCall120d63c2010-08-24 20:38:10 +0000883 if (ICS.isBad()) return true;
884
885 // Perform the actual conversion.
886 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
887 return false;
888}
889
Douglas Gregor575c63a2010-04-16 22:27:05 +0000890/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +0000891/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +0000892/// converted expression. Flavor is the kind of conversion we're
893/// performing, used in the error message. If @p AllowExplicit,
894/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +0000895ExprResult
896Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +0000897 AssignmentAction Action, bool AllowExplicit) {
898 ImplicitConversionSequence ICS;
899 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
900}
901
John Wiegley429bb272011-04-08 18:41:53 +0000902ExprResult
903Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +0000904 AssignmentAction Action, bool AllowExplicit,
905 ImplicitConversionSequence& ICS) {
John McCall120d63c2010-08-24 20:38:10 +0000906 ICS = clang::TryImplicitConversion(*this, From, ToType,
907 /*SuppressUserConversions=*/false,
908 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000909 /*InOverloadResolution=*/false,
910 /*CStyle=*/false);
Douglas Gregor575c63a2010-04-16 22:27:05 +0000911 return PerformImplicitConversion(From, ToType, ICS, Action);
912}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000913
914/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +0000915/// conversion that strips "noreturn" off the nested function type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000916static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000917 QualType ToType, QualType &ResultTy) {
918 if (Context.hasSameUnqualifiedType(FromType, ToType))
919 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000920
John McCall00ccbef2010-12-21 00:44:39 +0000921 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
922 // where F adds one of the following at most once:
923 // - a pointer
924 // - a member pointer
925 // - a block pointer
926 CanQualType CanTo = Context.getCanonicalType(ToType);
927 CanQualType CanFrom = Context.getCanonicalType(FromType);
928 Type::TypeClass TyClass = CanTo->getTypeClass();
929 if (TyClass != CanFrom->getTypeClass()) return false;
930 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
931 if (TyClass == Type::Pointer) {
932 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
933 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
934 } else if (TyClass == Type::BlockPointer) {
935 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
936 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
937 } else if (TyClass == Type::MemberPointer) {
938 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
939 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
940 } else {
941 return false;
942 }
Douglas Gregor43c79c22009-12-09 00:47:37 +0000943
John McCall00ccbef2010-12-21 00:44:39 +0000944 TyClass = CanTo->getTypeClass();
945 if (TyClass != CanFrom->getTypeClass()) return false;
946 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
947 return false;
948 }
949
950 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
951 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
952 if (!EInfo.getNoReturn()) return false;
953
954 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
955 assert(QualType(FromFn, 0).isCanonical());
956 if (QualType(FromFn, 0) != CanTo) return false;
957
958 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +0000959 return true;
960}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000961
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000962/// \brief Determine whether the conversion from FromType to ToType is a valid
963/// vector conversion.
964///
965/// \param ICK Will be set to the vector conversion kind, if this is a vector
966/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000967static bool IsVectorConversion(ASTContext &Context, QualType FromType,
968 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000969 // We need at least one of these types to be a vector type to have a vector
970 // conversion.
971 if (!ToType->isVectorType() && !FromType->isVectorType())
972 return false;
973
974 // Identical types require no conversions.
975 if (Context.hasSameUnqualifiedType(FromType, ToType))
976 return false;
977
978 // There are no conversions between extended vector types, only identity.
979 if (ToType->isExtVectorType()) {
980 // There are no conversions between extended vector types other than the
981 // identity conversion.
982 if (FromType->isExtVectorType())
983 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000984
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000985 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +0000986 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000987 ICK = ICK_Vector_Splat;
988 return true;
989 }
990 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000991
992 // We can perform the conversion between vector types in the following cases:
993 // 1)vector types are equivalent AltiVec and GCC vector types
994 // 2)lax vector conversions are permitted and the vector types are of the
995 // same size
996 if (ToType->isVectorType() && FromType->isVectorType()) {
997 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +0000998 (Context.getLangOptions().LaxVectorConversions &&
999 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001000 ICK = ICK_Vector_Conversion;
1001 return true;
1002 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001003 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001004
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001005 return false;
1006}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001007
Douglas Gregor60d62c22008-10-31 16:23:19 +00001008/// IsStandardConversion - Determines whether there is a standard
1009/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1010/// expression From to the type ToType. Standard conversion sequences
1011/// only consider non-class types; for conversions that involve class
1012/// types, use TryImplicitConversion. If a conversion exists, SCS will
1013/// contain the standard conversion sequence required to perform this
1014/// conversion and this routine will return true. Otherwise, this
1015/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001016static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1017 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001018 StandardConversionSequence &SCS,
1019 bool CStyle) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001020 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001021
Douglas Gregor60d62c22008-10-31 16:23:19 +00001022 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001023 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001024 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001025 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001026 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001027 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001028
Douglas Gregorf9201e02009-02-11 23:02:49 +00001029 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001030 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001031 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +00001032 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001033 return false;
1034
Mike Stump1eb44332009-09-09 15:08:12 +00001035 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001036 }
1037
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001038 // The first conversion can be an lvalue-to-rvalue conversion,
1039 // array-to-pointer conversion, or function-to-pointer conversion
1040 // (C++ 4p1).
1041
John McCall120d63c2010-08-24 20:38:10 +00001042 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001043 DeclAccessPair AccessPair;
1044 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001045 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001046 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001047 // We were able to resolve the address of the overloaded function,
1048 // so we can convert to the type of that function.
1049 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001050
1051 // we can sometimes resolve &foo<int> regardless of ToType, so check
1052 // if the type matches (identity) or we are converting to bool
1053 if (!S.Context.hasSameUnqualifiedType(
1054 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1055 QualType resultTy;
1056 // if the function type matches except for [[noreturn]], it's ok
1057 if (!IsNoReturnConversion(S.Context, FromType,
1058 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1059 // otherwise, only a boolean conversion is standard
1060 if (!ToType->isBooleanType())
1061 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001062 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001063
Chandler Carruth90434232011-03-29 08:08:18 +00001064 // Check if the "from" expression is taking the address of an overloaded
1065 // function and recompute the FromType accordingly. Take advantage of the
1066 // fact that non-static member functions *must* have such an address-of
1067 // expression.
1068 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1069 if (Method && !Method->isStatic()) {
1070 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1071 "Non-unary operator on non-static member address");
1072 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1073 == UO_AddrOf &&
1074 "Non-address-of operator on non-static member address");
1075 const Type *ClassType
1076 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1077 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001078 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1079 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1080 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001081 "Non-address-of operator for overloaded function expression");
1082 FromType = S.Context.getPointerType(FromType);
1083 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001084
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001085 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001086 assert(S.Context.hasSameType(
1087 FromType,
1088 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001089 } else {
1090 return false;
1091 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001092 }
Mike Stump1eb44332009-09-09 15:08:12 +00001093 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001094 // An lvalue (3.10) of a non-function, non-array type T can be
1095 // converted to an rvalue.
John McCall7eb0a9e2010-11-24 05:12:34 +00001096 bool argIsLValue = From->isLValue();
1097 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001098 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001099 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001100 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001101
1102 // If T is a non-class type, the type of the rvalue is the
1103 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001104 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1105 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001106 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001107 } else if (FromType->isArrayType()) {
1108 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001109 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001110
1111 // An lvalue or rvalue of type "array of N T" or "array of unknown
1112 // bound of T" can be converted to an rvalue of type "pointer to
1113 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001114 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001115
John McCall120d63c2010-08-24 20:38:10 +00001116 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001117 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001118 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001119
1120 // For the purpose of ranking in overload resolution
1121 // (13.3.3.1.1), this conversion is considered an
1122 // array-to-pointer conversion followed by a qualification
1123 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001124 SCS.Second = ICK_Identity;
1125 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +00001126 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001127 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001128 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001129 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001130 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001131 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001132
1133 // An lvalue of function type T can be converted to an rvalue of
1134 // type "pointer to T." The result is a pointer to the
1135 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001136 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001137 } else {
1138 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001139 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001140 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001141 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001142
1143 // The second conversion can be an integral promotion, floating
1144 // point promotion, integral conversion, floating point conversion,
1145 // floating-integral conversion, pointer conversion,
1146 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001147 // For overloading in C, this can also be a "compatible-type"
1148 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001149 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001150 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001151 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001152 // The unqualified versions of the types are the same: there's no
1153 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001154 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001155 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001156 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001157 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001158 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001159 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001160 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001161 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001162 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001163 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001164 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001165 SCS.Second = ICK_Complex_Promotion;
1166 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001167 } else if (ToType->isBooleanType() &&
1168 (FromType->isArithmeticType() ||
1169 FromType->isAnyPointerType() ||
1170 FromType->isBlockPointerType() ||
1171 FromType->isMemberPointerType() ||
1172 FromType->isNullPtrType())) {
1173 // Boolean conversions (C++ 4.12).
1174 SCS.Second = ICK_Boolean_Conversion;
1175 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001176 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001177 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001178 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001179 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001180 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001181 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001182 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001183 SCS.Second = ICK_Complex_Conversion;
1184 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001185 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1186 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001187 // Complex-real conversions (C99 6.3.1.7)
1188 SCS.Second = ICK_Complex_Real;
1189 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001190 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001191 // Floating point conversions (C++ 4.8).
1192 SCS.Second = ICK_Floating_Conversion;
1193 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001194 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001195 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001196 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001197 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001198 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001199 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001200 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001201 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1202 SCS.Second = ICK_Block_Pointer_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001203 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1204 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001205 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001206 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001207 SCS.IncompatibleObjC = IncompatibleObjC;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001208 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001209 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001210 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001211 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001212 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001213 SCS.Second = SecondICK;
1214 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001215 } else if (!S.getLangOptions().CPlusPlus &&
1216 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001217 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001218 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001219 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001220 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001221 // Treat a conversion that strips "noreturn" as an identity conversion.
1222 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001223 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1224 InOverloadResolution,
1225 SCS, CStyle)) {
1226 SCS.Second = ICK_TransparentUnionConversion;
1227 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001228 } else {
1229 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001230 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001231 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001232 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001233
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001234 QualType CanonFrom;
1235 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001236 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001237 if (S.IsQualificationConversion(FromType, ToType, CStyle)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001238 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001239 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001240 CanonFrom = S.Context.getCanonicalType(FromType);
1241 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001242 } else {
1243 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001244 SCS.Third = ICK_Identity;
1245
Mike Stump1eb44332009-09-09 15:08:12 +00001246 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001247 // [...] Any difference in top-level cv-qualification is
1248 // subsumed by the initialization itself and does not constitute
1249 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001250 CanonFrom = S.Context.getCanonicalType(FromType);
1251 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001252 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001253 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001254 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1255 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001256 FromType = ToType;
1257 CanonFrom = CanonTo;
1258 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001259 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001260 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001261
1262 // If we have not converted the argument type to the parameter type,
1263 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001264 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001265 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001266
Douglas Gregor60d62c22008-10-31 16:23:19 +00001267 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001268}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001269
1270static bool
1271IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1272 QualType &ToType,
1273 bool InOverloadResolution,
1274 StandardConversionSequence &SCS,
1275 bool CStyle) {
1276
1277 const RecordType *UT = ToType->getAsUnionType();
1278 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1279 return false;
1280 // The field to initialize within the transparent union.
1281 RecordDecl *UD = UT->getDecl();
1282 // It's compatible if the expression matches any of the fields.
1283 for (RecordDecl::field_iterator it = UD->field_begin(),
1284 itend = UD->field_end();
1285 it != itend; ++it) {
1286 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, CStyle)) {
1287 ToType = it->getType();
1288 return true;
1289 }
1290 }
1291 return false;
1292}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001293
1294/// IsIntegralPromotion - Determines whether the conversion from the
1295/// expression From (whose potentially-adjusted type is FromType) to
1296/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1297/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001298bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001299 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001300 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001301 if (!To) {
1302 return false;
1303 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001304
1305 // An rvalue of type char, signed char, unsigned char, short int, or
1306 // unsigned short int can be converted to an rvalue of type int if
1307 // int can represent all the values of the source type; otherwise,
1308 // the source rvalue can be converted to an rvalue of type unsigned
1309 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001310 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1311 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001312 if (// We can promote any signed, promotable integer type to an int
1313 (FromType->isSignedIntegerType() ||
1314 // We can promote any unsigned integer type whose size is
1315 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001316 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001317 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001318 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001319 }
1320
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001321 return To->getKind() == BuiltinType::UInt;
1322 }
1323
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001324 // C++0x [conv.prom]p3:
1325 // A prvalue of an unscoped enumeration type whose underlying type is not
1326 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1327 // following types that can represent all the values of the enumeration
1328 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1329 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001330 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001331 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001332 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001333 // with lowest integer conversion rank (4.13) greater than the rank of long
1334 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001335 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001336 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1337 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1338 // provided for a scoped enumeration.
1339 if (FromEnumType->getDecl()->isScoped())
1340 return false;
1341
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001342 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001343 if (ToType->isIntegerType() &&
Douglas Gregor5dde1602010-09-12 03:38:25 +00001344 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001345 return Context.hasSameUnqualifiedType(ToType,
1346 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001347 }
John McCall842aef82009-12-09 09:09:27 +00001348
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001349 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001350 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1351 // to an rvalue a prvalue of the first of the following types that can
1352 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001353 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001354 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001355 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001356 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001357 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001358 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001359 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001360 // Determine whether the type we're converting from is signed or
1361 // unsigned.
1362 bool FromIsSigned;
1363 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001364
John McCall842aef82009-12-09 09:09:27 +00001365 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1366 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001367
1368 // The types we'll try to promote to, in the appropriate
1369 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001370 QualType PromoteTypes[6] = {
1371 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001372 Context.LongTy, Context.UnsignedLongTy ,
1373 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001374 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001375 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001376 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1377 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001378 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001379 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1380 // We found the type that we can promote to. If this is the
1381 // type we wanted, we have a promotion. Otherwise, no
1382 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001383 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001384 }
1385 }
1386 }
1387
1388 // An rvalue for an integral bit-field (9.6) can be converted to an
1389 // rvalue of type int if int can represent all the values of the
1390 // bit-field; otherwise, it can be converted to unsigned int if
1391 // unsigned int can represent all the values of the bit-field. If
1392 // the bit-field is larger yet, no integral promotion applies to
1393 // it. If the bit-field has an enumerated type, it is treated as any
1394 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001395 // FIXME: We should delay checking of bit-fields until we actually perform the
1396 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001397 using llvm::APSInt;
1398 if (From)
1399 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001400 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001401 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001402 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1403 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1404 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Douglas Gregor86f19402008-12-20 23:49:58 +00001406 // Are we promoting to an int from a bitfield that fits in an int?
1407 if (BitWidth < ToSize ||
1408 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1409 return To->getKind() == BuiltinType::Int;
1410 }
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Douglas Gregor86f19402008-12-20 23:49:58 +00001412 // Are we promoting to an unsigned int from an unsigned bitfield
1413 // that fits into an unsigned int?
1414 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1415 return To->getKind() == BuiltinType::UInt;
1416 }
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Douglas Gregor86f19402008-12-20 23:49:58 +00001418 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001419 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001420 }
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001422 // An rvalue of type bool can be converted to an rvalue of type int,
1423 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001424 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001425 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001426 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001427
1428 return false;
1429}
1430
1431/// IsFloatingPointPromotion - Determines whether the conversion from
1432/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1433/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001434bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001435 /// An rvalue of type float can be converted to an rvalue of type
1436 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001437 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1438 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001439 if (FromBuiltin->getKind() == BuiltinType::Float &&
1440 ToBuiltin->getKind() == BuiltinType::Double)
1441 return true;
1442
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001443 // C99 6.3.1.5p1:
1444 // When a float is promoted to double or long double, or a
1445 // double is promoted to long double [...].
1446 if (!getLangOptions().CPlusPlus &&
1447 (FromBuiltin->getKind() == BuiltinType::Float ||
1448 FromBuiltin->getKind() == BuiltinType::Double) &&
1449 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1450 return true;
1451 }
1452
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001453 return false;
1454}
1455
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001456/// \brief Determine if a conversion is a complex promotion.
1457///
1458/// A complex promotion is defined as a complex -> complex conversion
1459/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001460/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001461bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001462 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001463 if (!FromComplex)
1464 return false;
1465
John McCall183700f2009-09-21 23:43:11 +00001466 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001467 if (!ToComplex)
1468 return false;
1469
1470 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001471 ToComplex->getElementType()) ||
1472 IsIntegralPromotion(0, FromComplex->getElementType(),
1473 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001474}
1475
Douglas Gregorcb7de522008-11-26 23:31:11 +00001476/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1477/// the pointer type FromPtr to a pointer to type ToPointee, with the
1478/// same type qualifiers as FromPtr has on its pointee type. ToType,
1479/// if non-empty, will be a pointer to ToType that may or may not have
1480/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001481static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001482BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001483 QualType ToPointee, QualType ToType,
1484 ASTContext &Context) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001485 assert((FromPtr->getTypeClass() == Type::Pointer ||
1486 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1487 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001488
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001489 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1490 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1491 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001492
1493 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001494 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001495 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001496 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001497
1498 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001499 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001500 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001501 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001502 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001503
1504 // Build a pointer to ToPointee. It has the right qualifiers
1505 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001506 if (isa<ObjCObjectPointerType>(ToType))
1507 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001508 return Context.getPointerType(ToPointee);
1509 }
1510
1511 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001512 QualType QualifiedCanonToPointee
1513 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001514
Douglas Gregorda80f742010-12-01 21:43:58 +00001515 if (isa<ObjCObjectPointerType>(ToType))
1516 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1517 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001518}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001519
Mike Stump1eb44332009-09-09 15:08:12 +00001520static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001521 bool InOverloadResolution,
1522 ASTContext &Context) {
1523 // Handle value-dependent integral null pointer constants correctly.
1524 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1525 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001526 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001527 return !InOverloadResolution;
1528
Douglas Gregorce940492009-09-25 04:25:58 +00001529 return Expr->isNullPointerConstant(Context,
1530 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1531 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001532}
Mike Stump1eb44332009-09-09 15:08:12 +00001533
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001534/// IsPointerConversion - Determines whether the conversion of the
1535/// expression From, which has the (possibly adjusted) type FromType,
1536/// can be converted to the type ToType via a pointer conversion (C++
1537/// 4.10). If so, returns true and places the converted type (that
1538/// might differ from ToType in its cv-qualifiers at some level) into
1539/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001540///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001541/// This routine also supports conversions to and from block pointers
1542/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1543/// pointers to interfaces. FIXME: Once we've determined the
1544/// appropriate overloading rules for Objective-C, we may want to
1545/// split the Objective-C checks into a different routine; however,
1546/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001547/// conversions, so for now they live here. IncompatibleObjC will be
1548/// set if the conversion is an allowed Objective-C conversion that
1549/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001550bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001551 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001552 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001553 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001554 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001555 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1556 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001557 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001558
Mike Stump1eb44332009-09-09 15:08:12 +00001559 // Conversion from a null pointer constant to any Objective-C pointer type.
1560 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001561 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001562 ConvertedType = ToType;
1563 return true;
1564 }
1565
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001566 // Blocks: Block pointers can be converted to void*.
1567 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001568 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001569 ConvertedType = ToType;
1570 return true;
1571 }
1572 // Blocks: A null pointer constant can be converted to a block
1573 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001574 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001575 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001576 ConvertedType = ToType;
1577 return true;
1578 }
1579
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001580 // If the left-hand-side is nullptr_t, the right side can be a null
1581 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001582 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001583 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001584 ConvertedType = ToType;
1585 return true;
1586 }
1587
Ted Kremenek6217b802009-07-29 21:53:49 +00001588 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001589 if (!ToTypePtr)
1590 return false;
1591
1592 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001593 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001594 ConvertedType = ToType;
1595 return true;
1596 }
Sebastian Redl07779722008-10-31 14:43:28 +00001597
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001598 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001599 // , including objective-c pointers.
1600 QualType ToPointeeType = ToTypePtr->getPointeeType();
1601 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001602 ConvertedType = BuildSimilarlyQualifiedPointerType(
1603 FromType->getAs<ObjCObjectPointerType>(),
1604 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001605 ToType, Context);
1606 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001607 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001608 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001609 if (!FromTypePtr)
1610 return false;
1611
1612 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001613
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001614 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001615 // pointer conversion, so don't do all of the work below.
1616 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1617 return false;
1618
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001619 // An rvalue of type "pointer to cv T," where T is an object type,
1620 // can be converted to an rvalue of type "pointer to cv void" (C++
1621 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001622 if (FromPointeeType->isIncompleteOrObjectType() &&
1623 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001624 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001625 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001626 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001627 return true;
1628 }
1629
Douglas Gregorf9201e02009-02-11 23:02:49 +00001630 // When we're overloading in C, we allow a special kind of pointer
1631 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001632 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001633 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001634 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001635 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001636 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001637 return true;
1638 }
1639
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001640 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001641 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001642 // An rvalue of type "pointer to cv D," where D is a class type,
1643 // can be converted to an rvalue of type "pointer to cv B," where
1644 // B is a base class (clause 10) of D. If B is an inaccessible
1645 // (clause 11) or ambiguous (10.2) base class of D, a program that
1646 // necessitates this conversion is ill-formed. The result of the
1647 // conversion is a pointer to the base class sub-object of the
1648 // derived class object. The null pointer value is converted to
1649 // the null pointer value of the destination type.
1650 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001651 // Note that we do not check for ambiguity or inaccessibility
1652 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001653 if (getLangOptions().CPlusPlus &&
1654 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001655 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001656 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001657 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001658 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001659 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001660 ToType, Context);
1661 return true;
1662 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001663
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00001664 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1665 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1666 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1667 ToPointeeType,
1668 ToType, Context);
1669 return true;
1670 }
1671
Douglas Gregorc7887512008-12-19 19:13:09 +00001672 return false;
1673}
1674
1675/// isObjCPointerConversion - Determines whether this is an
1676/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1677/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001678bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001679 QualType& ConvertedType,
1680 bool &IncompatibleObjC) {
1681 if (!getLangOptions().ObjC1)
1682 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001683
Steve Naroff14108da2009-07-10 23:34:53 +00001684 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00001685 const ObjCObjectPointerType* ToObjCPtr =
1686 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001687 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001688 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001689
Steve Naroff14108da2009-07-10 23:34:53 +00001690 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001691 // If the pointee types are the same (ignoring qualifications),
1692 // then this is not a pointer conversion.
1693 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1694 FromObjCPtr->getPointeeType()))
1695 return false;
1696
Steve Naroffde2e22d2009-07-15 18:40:39 +00001697 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001698 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001699 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001700 ConvertedType = ToType;
1701 return true;
1702 }
1703 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001704 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001705 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001706 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001707 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001708 ConvertedType = ToType;
1709 return true;
1710 }
1711 // Objective C++: We're able to convert from a pointer to an
1712 // interface to a pointer to a different interface.
1713 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001714 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1715 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1716 if (getLangOptions().CPlusPlus && LHS && RHS &&
1717 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1718 FromObjCPtr->getPointeeType()))
1719 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001720 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00001721 ToObjCPtr->getPointeeType(),
1722 ToType, Context);
Steve Naroff14108da2009-07-10 23:34:53 +00001723 return true;
1724 }
1725
1726 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1727 // Okay: this is some kind of implicit downcast of Objective-C
1728 // interfaces, which is permitted. However, we're going to
1729 // complain about it.
1730 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001731 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00001732 ToObjCPtr->getPointeeType(),
1733 ToType, Context);
Steve Naroff14108da2009-07-10 23:34:53 +00001734 return true;
1735 }
Mike Stump1eb44332009-09-09 15:08:12 +00001736 }
Steve Naroff14108da2009-07-10 23:34:53 +00001737 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001738 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001739 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001740 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001741 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001742 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001743 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001744 // to a block pointer type.
1745 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1746 ConvertedType = ToType;
1747 return true;
1748 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001749 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001750 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001751 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001752 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001753 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001754 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001755 ConvertedType = ToType;
1756 return true;
1757 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001758 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001759 return false;
1760
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001761 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001762 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001763 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00001764 else if (const BlockPointerType *FromBlockPtr =
1765 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001766 FromPointeeType = FromBlockPtr->getPointeeType();
1767 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001768 return false;
1769
Douglas Gregorc7887512008-12-19 19:13:09 +00001770 // If we have pointers to pointers, recursively check whether this
1771 // is an Objective-C conversion.
1772 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1773 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1774 IncompatibleObjC)) {
1775 // We always complain about this conversion.
1776 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00001777 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregorc7887512008-12-19 19:13:09 +00001778 return true;
1779 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001780 // Allow conversion of pointee being objective-c pointer to another one;
1781 // as in I* to id.
1782 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1783 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1784 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1785 IncompatibleObjC)) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001786 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001787 return true;
1788 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001789
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001790 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001791 // differences in the argument and result types are in Objective-C
1792 // pointer conversions. If so, we permit the conversion (but
1793 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001794 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001795 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001796 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001797 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001798 if (FromFunctionType && ToFunctionType) {
1799 // If the function types are exactly the same, this isn't an
1800 // Objective-C pointer conversion.
1801 if (Context.getCanonicalType(FromPointeeType)
1802 == Context.getCanonicalType(ToPointeeType))
1803 return false;
1804
1805 // Perform the quick checks that will tell us whether these
1806 // function types are obviously different.
1807 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1808 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1809 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1810 return false;
1811
1812 bool HasObjCConversion = false;
1813 if (Context.getCanonicalType(FromFunctionType->getResultType())
1814 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1815 // Okay, the types match exactly. Nothing to do.
1816 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1817 ToFunctionType->getResultType(),
1818 ConvertedType, IncompatibleObjC)) {
1819 // Okay, we have an Objective-C pointer conversion.
1820 HasObjCConversion = true;
1821 } else {
1822 // Function types are too different. Abort.
1823 return false;
1824 }
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Douglas Gregorc7887512008-12-19 19:13:09 +00001826 // Check argument types.
1827 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1828 ArgIdx != NumArgs; ++ArgIdx) {
1829 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1830 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1831 if (Context.getCanonicalType(FromArgType)
1832 == Context.getCanonicalType(ToArgType)) {
1833 // Okay, the types match exactly. Nothing to do.
1834 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1835 ConvertedType, IncompatibleObjC)) {
1836 // Okay, we have an Objective-C pointer conversion.
1837 HasObjCConversion = true;
1838 } else {
1839 // Argument types are too different. Abort.
1840 return false;
1841 }
1842 }
1843
1844 if (HasObjCConversion) {
1845 // We had an Objective-C conversion. Allow this pointer
1846 // conversion, but complain about it.
1847 ConvertedType = ToType;
1848 IncompatibleObjC = true;
1849 return true;
1850 }
1851 }
1852
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001853 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001854}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001855
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001856bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1857 QualType& ConvertedType) {
1858 QualType ToPointeeType;
1859 if (const BlockPointerType *ToBlockPtr =
1860 ToType->getAs<BlockPointerType>())
1861 ToPointeeType = ToBlockPtr->getPointeeType();
1862 else
1863 return false;
1864
1865 QualType FromPointeeType;
1866 if (const BlockPointerType *FromBlockPtr =
1867 FromType->getAs<BlockPointerType>())
1868 FromPointeeType = FromBlockPtr->getPointeeType();
1869 else
1870 return false;
1871 // We have pointer to blocks, check whether the only
1872 // differences in the argument and result types are in Objective-C
1873 // pointer conversions. If so, we permit the conversion.
1874
1875 const FunctionProtoType *FromFunctionType
1876 = FromPointeeType->getAs<FunctionProtoType>();
1877 const FunctionProtoType *ToFunctionType
1878 = ToPointeeType->getAs<FunctionProtoType>();
1879
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00001880 if (!FromFunctionType || !ToFunctionType)
1881 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001882
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00001883 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001884 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00001885
1886 // Perform the quick checks that will tell us whether these
1887 // function types are obviously different.
1888 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1889 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
1890 return false;
1891
1892 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
1893 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
1894 if (FromEInfo != ToEInfo)
1895 return false;
1896
1897 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00001898 if (Context.hasSameType(FromFunctionType->getResultType(),
1899 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00001900 // Okay, the types match exactly. Nothing to do.
1901 } else {
1902 QualType RHS = FromFunctionType->getResultType();
1903 QualType LHS = ToFunctionType->getResultType();
1904 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
1905 !RHS.hasQualifiers() && LHS.hasQualifiers())
1906 LHS = LHS.getUnqualifiedType();
1907
1908 if (Context.hasSameType(RHS,LHS)) {
1909 // OK exact match.
1910 } else if (isObjCPointerConversion(RHS, LHS,
1911 ConvertedType, IncompatibleObjC)) {
1912 if (IncompatibleObjC)
1913 return false;
1914 // Okay, we have an Objective-C pointer conversion.
1915 }
1916 else
1917 return false;
1918 }
1919
1920 // Check argument types.
1921 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1922 ArgIdx != NumArgs; ++ArgIdx) {
1923 IncompatibleObjC = false;
1924 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1925 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1926 if (Context.hasSameType(FromArgType, ToArgType)) {
1927 // Okay, the types match exactly. Nothing to do.
1928 } else if (isObjCPointerConversion(ToArgType, FromArgType,
1929 ConvertedType, IncompatibleObjC)) {
1930 if (IncompatibleObjC)
1931 return false;
1932 // Okay, we have an Objective-C pointer conversion.
1933 } else
1934 // Argument types are too different. Abort.
1935 return false;
1936 }
1937 ConvertedType = ToType;
1938 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001939}
1940
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001941/// FunctionArgTypesAreEqual - This routine checks two function proto types
1942/// for equlity of their argument types. Caller has already checked that
1943/// they have same number of arguments. This routine assumes that Objective-C
1944/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001945bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCallf4c73712011-01-19 06:33:43 +00001946 const FunctionProtoType *NewType) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001947 if (!getLangOptions().ObjC1)
1948 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1949 NewType->arg_type_begin());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001950
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001951 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1952 N = NewType->arg_type_begin(),
1953 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1954 QualType ToType = (*O);
1955 QualType FromType = (*N);
1956 if (ToType != FromType) {
1957 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1958 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001959 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1960 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1961 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1962 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001963 continue;
1964 }
John McCallc12c5bb2010-05-15 11:32:37 +00001965 else if (const ObjCObjectPointerType *PTTo =
1966 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001967 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00001968 FromType->getAs<ObjCObjectPointerType>())
1969 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1970 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001971 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001972 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001973 }
1974 }
1975 return true;
1976}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001977
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001978/// CheckPointerConversion - Check the pointer conversion from the
1979/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001980/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001981/// conversions for which IsPointerConversion has already returned
1982/// true. It returns true and produces a diagnostic if there was an
1983/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001984bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001985 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001986 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001987 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001988 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00001989 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001990
John McCalldaa8e4e2010-11-15 09:13:47 +00001991 Kind = CK_BitCast;
1992
Chandler Carruth88f0aed2011-04-09 07:32:05 +00001993 if (!IsCStyleOrFunctionalCast &&
1994 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
1995 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1996 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruthb6006692011-04-09 07:48:17 +00001997 PDiag(diag::warn_impcast_bool_to_null_pointer)
1998 << ToType << From->getSourceRange());
Douglas Gregord7a95972010-06-08 17:35:15 +00001999
Ted Kremenek6217b802009-07-29 21:53:49 +00002000 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
2001 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002002 QualType FromPointeeType = FromPtrType->getPointeeType(),
2003 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002004
Douglas Gregor5fccd362010-03-03 23:55:11 +00002005 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2006 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002007 // We must have a derived-to-base conversion. Check an
2008 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002009 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2010 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002011 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002012 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002013 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002014
Anders Carlsson61faec12009-09-12 04:46:44 +00002015 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002016 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002017 }
2018 }
Mike Stump1eb44332009-09-09 15:08:12 +00002019 if (const ObjCObjectPointerType *FromPtrType =
John McCalldaa8e4e2010-11-15 09:13:47 +00002020 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002021 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00002022 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002023 // Objective-C++ conversions are always okay.
2024 // FIXME: We should have a different class of conversions for the
2025 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002026 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002027 return false;
John McCalldaa8e4e2010-11-15 09:13:47 +00002028 }
Steve Naroff14108da2009-07-10 23:34:53 +00002029 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002030
2031 // We shouldn't fall into this case unless it's valid for other
2032 // reasons.
2033 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2034 Kind = CK_NullToPointer;
2035
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002036 return false;
2037}
2038
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002039/// IsMemberPointerConversion - Determines whether the conversion of the
2040/// expression From, which has the (possibly adjusted) type FromType, can be
2041/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2042/// If so, returns true and places the converted type (that might differ from
2043/// ToType in its cv-qualifiers at some level) into ConvertedType.
2044bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002045 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002046 bool InOverloadResolution,
2047 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002048 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002049 if (!ToTypePtr)
2050 return false;
2051
2052 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002053 if (From->isNullPointerConstant(Context,
2054 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2055 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002056 ConvertedType = ToType;
2057 return true;
2058 }
2059
2060 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002061 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002062 if (!FromTypePtr)
2063 return false;
2064
2065 // A pointer to member of B can be converted to a pointer to member of D,
2066 // where D is derived from B (C++ 4.11p2).
2067 QualType FromClass(FromTypePtr->getClass(), 0);
2068 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002069
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002070 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2071 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2072 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002073 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2074 ToClass.getTypePtr());
2075 return true;
2076 }
2077
2078 return false;
2079}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002080
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002081/// CheckMemberPointerConversion - Check the member pointer conversion from the
2082/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002083/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002084/// for which IsMemberPointerConversion has already returned true. It returns
2085/// true and produces a diagnostic if there was an error, or returns false
2086/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002087bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002088 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002089 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002090 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002091 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002092 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002093 if (!FromPtrType) {
2094 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002095 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002096 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002097 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002098 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002099 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002100 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002101
Ted Kremenek6217b802009-07-29 21:53:49 +00002102 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002103 assert(ToPtrType && "No member pointer cast has a target type "
2104 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002105
Sebastian Redl21593ac2009-01-28 18:33:18 +00002106 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2107 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002108
Sebastian Redl21593ac2009-01-28 18:33:18 +00002109 // FIXME: What about dependent types?
2110 assert(FromClass->isRecordType() && "Pointer into non-class.");
2111 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002112
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002113 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002114 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002115 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2116 assert(DerivationOkay &&
2117 "Should not have been called if derivation isn't OK.");
2118 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002119
Sebastian Redl21593ac2009-01-28 18:33:18 +00002120 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2121 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002122 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2123 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2124 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2125 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002126 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002127
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002128 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002129 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2130 << FromClass << ToClass << QualType(VBase, 0)
2131 << From->getSourceRange();
2132 return true;
2133 }
2134
John McCall6b2accb2010-02-10 09:31:12 +00002135 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002136 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2137 Paths.front(),
2138 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002139
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002140 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002141 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002142 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002143 return false;
2144}
2145
Douglas Gregor98cd5992008-10-21 23:43:52 +00002146/// IsQualificationConversion - Determines whether the conversion from
2147/// an rvalue of type FromType to ToType is a qualification conversion
2148/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00002149bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002150Sema::IsQualificationConversion(QualType FromType, QualType ToType,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002151 bool CStyle) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002152 FromType = Context.getCanonicalType(FromType);
2153 ToType = Context.getCanonicalType(ToType);
2154
2155 // If FromType and ToType are the same type, this is not a
2156 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002157 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002158 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002159
Douglas Gregor98cd5992008-10-21 23:43:52 +00002160 // (C++ 4.4p4):
2161 // A conversion can add cv-qualifiers at levels other than the first
2162 // in multi-level pointers, subject to the following rules: [...]
2163 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002164 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002165 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002166 // Within each iteration of the loop, we check the qualifiers to
2167 // determine if this still looks like a qualification
2168 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002169 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002170 // until there are no more pointers or pointers-to-members left to
2171 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002172 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002173
Douglas Gregor621c92a2011-04-25 18:40:17 +00002174 Qualifiers FromQuals = FromType.getQualifiers();
2175 Qualifiers ToQuals = ToType.getQualifiers();
2176
Douglas Gregor98cd5992008-10-21 23:43:52 +00002177 // -- for every j > 0, if const is in cv 1,j then const is in cv
2178 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002179 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002180 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002181
Douglas Gregor98cd5992008-10-21 23:43:52 +00002182 // -- if the cv 1,j and cv 2,j are different, then const is in
2183 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002184 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002185 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002186 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002187
Douglas Gregor98cd5992008-10-21 23:43:52 +00002188 // Keep track of whether all prior cv-qualifiers in the "to" type
2189 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002190 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002191 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002192 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002193
2194 // We are left with FromType and ToType being the pointee types
2195 // after unwrapping the original FromType and ToType the same number
2196 // of types. If we unwrapped any pointers, and if FromType and
2197 // ToType have the same unqualified type (since we checked
2198 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002199 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002200}
2201
Douglas Gregor734d9862009-01-30 23:27:23 +00002202/// Determines whether there is a user-defined conversion sequence
2203/// (C++ [over.ics.user]) that converts expression From to the type
2204/// ToType. If such a conversion exists, User will contain the
2205/// user-defined conversion sequence that performs such a conversion
2206/// and this routine will return true. Otherwise, this routine returns
2207/// false and User is unspecified.
2208///
Douglas Gregor734d9862009-01-30 23:27:23 +00002209/// \param AllowExplicit true if the conversion should consider C++0x
2210/// "explicit" conversion functions as well as non-explicit conversion
2211/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002212static OverloadingResult
2213IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2214 UserDefinedConversionSequence& User,
2215 OverloadCandidateSet& CandidateSet,
2216 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002217 // Whether we will only visit constructors.
2218 bool ConstructorsOnly = false;
2219
2220 // If the type we are conversion to is a class type, enumerate its
2221 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002222 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002223 // C++ [over.match.ctor]p1:
2224 // When objects of class type are direct-initialized (8.5), or
2225 // copy-initialized from an expression of the same or a
2226 // derived class type (8.5), overload resolution selects the
2227 // constructor. [...] For copy-initialization, the candidate
2228 // functions are all the converting constructors (12.3.1) of
2229 // that class. The argument list is the expression-list within
2230 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002231 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002232 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002233 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002234 ConstructorsOnly = true;
2235
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002236 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2237 // RequireCompleteType may have returned true due to some invalid decl
2238 // during template instantiation, but ToType may be complete enough now
2239 // to try to recover.
2240 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002241 // We're not going to find any constructors.
2242 } else if (CXXRecordDecl *ToRecordDecl
2243 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002244 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002245 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002246 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002247 NamedDecl *D = *Con;
2248 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2249
Douglas Gregordec06662009-08-21 18:42:58 +00002250 // Find the constructor (which may be a template).
2251 CXXConstructorDecl *Constructor = 0;
2252 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002253 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002254 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002255 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002256 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2257 else
John McCall9aa472c2010-03-19 07:35:19 +00002258 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002259
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00002260 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00002261 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00002262 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002263 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2264 /*ExplicitArgs*/ 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002265 &From, 1, CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002266 /*SuppressUserConversions=*/
2267 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002268 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002269 // Allow one user-defined conversion when user specifies a
2270 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002271 S.AddOverloadCandidate(Constructor, FoundDecl,
2272 &From, 1, CandidateSet,
2273 /*SuppressUserConversions=*/
2274 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002275 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002276 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002277 }
2278 }
2279
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002280 // Enumerate conversion functions, if we're allowed to.
2281 if (ConstructorsOnly) {
John McCall120d63c2010-08-24 20:38:10 +00002282 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2283 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002284 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002285 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002286 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002287 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002288 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2289 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002290 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002291 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002292 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002293 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002294 DeclAccessPair FoundDecl = I.getPair();
2295 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002296 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2297 if (isa<UsingShadowDecl>(D))
2298 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2299
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002300 CXXConversionDecl *Conv;
2301 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002302 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2303 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002304 else
John McCall32daa422010-03-31 01:36:47 +00002305 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002306
2307 if (AllowExplicit || !Conv->isExplicit()) {
2308 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002309 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2310 ActingContext, From, ToType,
2311 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002312 else
John McCall120d63c2010-08-24 20:38:10 +00002313 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2314 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002315 }
2316 }
2317 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002318 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002319
2320 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002321 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002322 case OR_Success:
2323 // Record the standard conversion we used and the conversion function.
2324 if (CXXConstructorDecl *Constructor
2325 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth25ca4212011-02-25 19:41:05 +00002326 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2327
John McCall120d63c2010-08-24 20:38:10 +00002328 // C++ [over.ics.user]p1:
2329 // If the user-defined conversion is specified by a
2330 // constructor (12.3.1), the initial standard conversion
2331 // sequence converts the source type to the type required by
2332 // the argument of the constructor.
2333 //
2334 QualType ThisType = Constructor->getThisType(S.Context);
2335 if (Best->Conversions[0].isEllipsis())
2336 User.EllipsisConversion = true;
2337 else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002338 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002339 User.EllipsisConversion = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002340 }
John McCall120d63c2010-08-24 20:38:10 +00002341 User.ConversionFunction = Constructor;
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002342 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall120d63c2010-08-24 20:38:10 +00002343 User.After.setAsIdentityConversion();
2344 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2345 User.After.setAllToTypes(ToType);
2346 return OR_Success;
2347 } else if (CXXConversionDecl *Conversion
2348 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth25ca4212011-02-25 19:41:05 +00002349 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2350
John McCall120d63c2010-08-24 20:38:10 +00002351 // C++ [over.ics.user]p1:
2352 //
2353 // [...] If the user-defined conversion is specified by a
2354 // conversion function (12.3.2), the initial standard
2355 // conversion sequence converts the source type to the
2356 // implicit object parameter of the conversion function.
2357 User.Before = Best->Conversions[0].Standard;
2358 User.ConversionFunction = Conversion;
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002359 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall120d63c2010-08-24 20:38:10 +00002360 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002361
John McCall120d63c2010-08-24 20:38:10 +00002362 // C++ [over.ics.user]p2:
2363 // The second standard conversion sequence converts the
2364 // result of the user-defined conversion to the target type
2365 // for the sequence. Since an implicit conversion sequence
2366 // is an initialization, the special rules for
2367 // initialization by user-defined conversion apply when
2368 // selecting the best user-defined conversion for a
2369 // user-defined conversion sequence (see 13.3.3 and
2370 // 13.3.3.1).
2371 User.After = Best->FinalConversion;
2372 return OR_Success;
2373 } else {
2374 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002375 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002376 }
2377
John McCall120d63c2010-08-24 20:38:10 +00002378 case OR_No_Viable_Function:
2379 return OR_No_Viable_Function;
2380 case OR_Deleted:
2381 // No conversion here! We're done.
2382 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002383
John McCall120d63c2010-08-24 20:38:10 +00002384 case OR_Ambiguous:
2385 return OR_Ambiguous;
2386 }
2387
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002388 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002389}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002390
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002391bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002392Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002393 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002394 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002395 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00002396 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002397 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002398 if (OvResult == OR_Ambiguous)
2399 Diag(From->getSourceRange().getBegin(),
2400 diag::err_typecheck_ambiguous_condition)
2401 << From->getType() << ToType << From->getSourceRange();
2402 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2403 Diag(From->getSourceRange().getBegin(),
2404 diag::err_typecheck_nonviable_condition)
2405 << From->getType() << ToType << From->getSourceRange();
2406 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002407 return false;
John McCall120d63c2010-08-24 20:38:10 +00002408 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002409 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002410}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002411
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002412/// CompareImplicitConversionSequences - Compare two implicit
2413/// conversion sequences to determine whether one is better than the
2414/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00002415static ImplicitConversionSequence::CompareKind
2416CompareImplicitConversionSequences(Sema &S,
2417 const ImplicitConversionSequence& ICS1,
2418 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002419{
2420 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2421 // conversion sequences (as defined in 13.3.3.1)
2422 // -- a standard conversion sequence (13.3.3.1.1) is a better
2423 // conversion sequence than a user-defined conversion sequence or
2424 // an ellipsis conversion sequence, and
2425 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2426 // conversion sequence than an ellipsis conversion sequence
2427 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002428 //
John McCall1d318332010-01-12 00:44:57 +00002429 // C++0x [over.best.ics]p10:
2430 // For the purpose of ranking implicit conversion sequences as
2431 // described in 13.3.3.2, the ambiguous conversion sequence is
2432 // treated as a user-defined sequence that is indistinguishable
2433 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002434 if (ICS1.getKindRank() < ICS2.getKindRank())
2435 return ImplicitConversionSequence::Better;
2436 else if (ICS2.getKindRank() < ICS1.getKindRank())
2437 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002438
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002439 // The following checks require both conversion sequences to be of
2440 // the same kind.
2441 if (ICS1.getKind() != ICS2.getKind())
2442 return ImplicitConversionSequence::Indistinguishable;
2443
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002444 // Two implicit conversion sequences of the same form are
2445 // indistinguishable conversion sequences unless one of the
2446 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002447 if (ICS1.isStandard())
John McCall120d63c2010-08-24 20:38:10 +00002448 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002449 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002450 // User-defined conversion sequence U1 is a better conversion
2451 // sequence than another user-defined conversion sequence U2 if
2452 // they contain the same user-defined conversion function or
2453 // constructor and if the second standard conversion sequence of
2454 // U1 is better than the second standard conversion sequence of
2455 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002456 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002457 ICS2.UserDefined.ConversionFunction)
John McCall120d63c2010-08-24 20:38:10 +00002458 return CompareStandardConversionSequences(S,
2459 ICS1.UserDefined.After,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002460 ICS2.UserDefined.After);
2461 }
2462
2463 return ImplicitConversionSequence::Indistinguishable;
2464}
2465
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002466static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2467 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2468 Qualifiers Quals;
2469 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002470 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002471 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002472
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002473 return Context.hasSameUnqualifiedType(T1, T2);
2474}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002475
Douglas Gregorad323a82010-01-27 03:51:04 +00002476// Per 13.3.3.2p3, compare the given standard conversion sequences to
2477// determine if one is a proper subset of the other.
2478static ImplicitConversionSequence::CompareKind
2479compareStandardConversionSubsets(ASTContext &Context,
2480 const StandardConversionSequence& SCS1,
2481 const StandardConversionSequence& SCS2) {
2482 ImplicitConversionSequence::CompareKind Result
2483 = ImplicitConversionSequence::Indistinguishable;
2484
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002485 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002486 // any non-identity conversion sequence
2487 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2488 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2489 return ImplicitConversionSequence::Better;
2490 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2491 return ImplicitConversionSequence::Worse;
2492 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002493
Douglas Gregorad323a82010-01-27 03:51:04 +00002494 if (SCS1.Second != SCS2.Second) {
2495 if (SCS1.Second == ICK_Identity)
2496 Result = ImplicitConversionSequence::Better;
2497 else if (SCS2.Second == ICK_Identity)
2498 Result = ImplicitConversionSequence::Worse;
2499 else
2500 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002501 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002502 return ImplicitConversionSequence::Indistinguishable;
2503
2504 if (SCS1.Third == SCS2.Third) {
2505 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2506 : ImplicitConversionSequence::Indistinguishable;
2507 }
2508
2509 if (SCS1.Third == ICK_Identity)
2510 return Result == ImplicitConversionSequence::Worse
2511 ? ImplicitConversionSequence::Indistinguishable
2512 : ImplicitConversionSequence::Better;
2513
2514 if (SCS2.Third == ICK_Identity)
2515 return Result == ImplicitConversionSequence::Better
2516 ? ImplicitConversionSequence::Indistinguishable
2517 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002518
Douglas Gregorad323a82010-01-27 03:51:04 +00002519 return ImplicitConversionSequence::Indistinguishable;
2520}
2521
Douglas Gregor440a4832011-01-26 14:52:12 +00002522/// \brief Determine whether one of the given reference bindings is better
2523/// than the other based on what kind of bindings they are.
2524static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2525 const StandardConversionSequence &SCS2) {
2526 // C++0x [over.ics.rank]p3b4:
2527 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2528 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002529 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00002530 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002531 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00002532 // reference*.
2533 //
2534 // FIXME: Rvalue references. We're going rogue with the above edits,
2535 // because the semantics in the current C++0x working paper (N3225 at the
2536 // time of this writing) break the standard definition of std::forward
2537 // and std::reference_wrapper when dealing with references to functions.
2538 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00002539 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2540 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2541 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002542
Douglas Gregor440a4832011-01-26 14:52:12 +00002543 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2544 SCS2.IsLvalueReference) ||
2545 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2546 !SCS2.IsLvalueReference);
2547}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002548
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002549/// CompareStandardConversionSequences - Compare two standard
2550/// conversion sequences to determine whether one is better than the
2551/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00002552static ImplicitConversionSequence::CompareKind
2553CompareStandardConversionSequences(Sema &S,
2554 const StandardConversionSequence& SCS1,
2555 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002556{
2557 // Standard conversion sequence S1 is a better conversion sequence
2558 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2559
2560 // -- S1 is a proper subsequence of S2 (comparing the conversion
2561 // sequences in the canonical form defined by 13.3.3.1.1,
2562 // excluding any Lvalue Transformation; the identity conversion
2563 // sequence is considered to be a subsequence of any
2564 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002565 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00002566 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00002567 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002568
2569 // -- the rank of S1 is better than the rank of S2 (by the rules
2570 // defined below), or, if not that,
2571 ImplicitConversionRank Rank1 = SCS1.getRank();
2572 ImplicitConversionRank Rank2 = SCS2.getRank();
2573 if (Rank1 < Rank2)
2574 return ImplicitConversionSequence::Better;
2575 else if (Rank2 < Rank1)
2576 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002577
Douglas Gregor57373262008-10-22 14:17:15 +00002578 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2579 // are indistinguishable unless one of the following rules
2580 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002581
Douglas Gregor57373262008-10-22 14:17:15 +00002582 // A conversion that is not a conversion of a pointer, or
2583 // pointer to member, to bool is better than another conversion
2584 // that is such a conversion.
2585 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2586 return SCS2.isPointerConversionToBool()
2587 ? ImplicitConversionSequence::Better
2588 : ImplicitConversionSequence::Worse;
2589
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002590 // C++ [over.ics.rank]p4b2:
2591 //
2592 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002593 // conversion of B* to A* is better than conversion of B* to
2594 // void*, and conversion of A* to void* is better than conversion
2595 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002596 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002597 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002598 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002599 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002600 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2601 // Exactly one of the conversion sequences is a conversion to
2602 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002603 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2604 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002605 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2606 // Neither conversion sequence converts to a void pointer; compare
2607 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002608 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00002609 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002610 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002611 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2612 // Both conversion sequences are conversions to void
2613 // pointers. Compare the source types to determine if there's an
2614 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002615 QualType FromType1 = SCS1.getFromType();
2616 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002617
2618 // Adjust the types we're converting from via the array-to-pointer
2619 // conversion, if we need to.
2620 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002621 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002622 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002623 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002624
Douglas Gregor01919692009-12-13 21:37:05 +00002625 QualType FromPointee1
2626 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2627 QualType FromPointee2
2628 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002629
John McCall120d63c2010-08-24 20:38:10 +00002630 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00002631 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002632 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00002633 return ImplicitConversionSequence::Worse;
2634
2635 // Objective-C++: If one interface is more specific than the
2636 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002637 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2638 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002639 if (FromIface1 && FromIface1) {
John McCall120d63c2010-08-24 20:38:10 +00002640 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor01919692009-12-13 21:37:05 +00002641 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002642 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor01919692009-12-13 21:37:05 +00002643 return ImplicitConversionSequence::Worse;
2644 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002645 }
Douglas Gregor57373262008-10-22 14:17:15 +00002646
2647 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2648 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002649 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00002650 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002651 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002652
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002653 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00002654 // Check for a better reference binding based on the kind of bindings.
2655 if (isBetterReferenceBindingKind(SCS1, SCS2))
2656 return ImplicitConversionSequence::Better;
2657 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2658 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002659
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002660 // C++ [over.ics.rank]p3b4:
2661 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2662 // which the references refer are the same type except for
2663 // top-level cv-qualifiers, and the type to which the reference
2664 // initialized by S2 refers is more cv-qualified than the type
2665 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002666 QualType T1 = SCS1.getToType(2);
2667 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002668 T1 = S.Context.getCanonicalType(T1);
2669 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002670 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002671 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2672 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002673 if (UnqualT1 == UnqualT2) {
Chandler Carruth6df868e2010-12-12 08:17:55 +00002674 // If the type is an array type, promote the element qualifiers to the
2675 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002676 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002677 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002678 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002679 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002680 if (T2.isMoreQualifiedThan(T1))
2681 return ImplicitConversionSequence::Better;
2682 else if (T1.isMoreQualifiedThan(T2))
2683 return ImplicitConversionSequence::Worse;
2684 }
2685 }
Douglas Gregor57373262008-10-22 14:17:15 +00002686
2687 return ImplicitConversionSequence::Indistinguishable;
2688}
2689
2690/// CompareQualificationConversions - Compares two standard conversion
2691/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002692/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2693ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002694CompareQualificationConversions(Sema &S,
2695 const StandardConversionSequence& SCS1,
2696 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002697 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002698 // -- S1 and S2 differ only in their qualification conversion and
2699 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2700 // cv-qualification signature of type T1 is a proper subset of
2701 // the cv-qualification signature of type T2, and S1 is not the
2702 // deprecated string literal array-to-pointer conversion (4.2).
2703 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2704 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2705 return ImplicitConversionSequence::Indistinguishable;
2706
2707 // FIXME: the example in the standard doesn't use a qualification
2708 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002709 QualType T1 = SCS1.getToType(2);
2710 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002711 T1 = S.Context.getCanonicalType(T1);
2712 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002713 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002714 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2715 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002716
2717 // If the types are the same, we won't learn anything by unwrapped
2718 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002719 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002720 return ImplicitConversionSequence::Indistinguishable;
2721
Chandler Carruth28e318c2009-12-29 07:16:59 +00002722 // If the type is an array type, promote the element qualifiers to the type
2723 // for comparison.
2724 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002725 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002726 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002727 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002728
Mike Stump1eb44332009-09-09 15:08:12 +00002729 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002730 = ImplicitConversionSequence::Indistinguishable;
John McCall120d63c2010-08-24 20:38:10 +00002731 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002732 // Within each iteration of the loop, we check the qualifiers to
2733 // determine if this still looks like a qualification
2734 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002735 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002736 // until there are no more pointers or pointers-to-members left
2737 // to unwrap. This essentially mimics what
2738 // IsQualificationConversion does, but here we're checking for a
2739 // strict subset of qualifiers.
2740 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2741 // The qualifiers are the same, so this doesn't tell us anything
2742 // about how the sequences rank.
2743 ;
2744 else if (T2.isMoreQualifiedThan(T1)) {
2745 // T1 has fewer qualifiers, so it could be the better sequence.
2746 if (Result == ImplicitConversionSequence::Worse)
2747 // Neither has qualifiers that are a subset of the other's
2748 // qualifiers.
2749 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002750
Douglas Gregor57373262008-10-22 14:17:15 +00002751 Result = ImplicitConversionSequence::Better;
2752 } else if (T1.isMoreQualifiedThan(T2)) {
2753 // T2 has fewer qualifiers, so it could be the better sequence.
2754 if (Result == ImplicitConversionSequence::Better)
2755 // Neither has qualifiers that are a subset of the other's
2756 // qualifiers.
2757 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002758
Douglas Gregor57373262008-10-22 14:17:15 +00002759 Result = ImplicitConversionSequence::Worse;
2760 } else {
2761 // Qualifiers are disjoint.
2762 return ImplicitConversionSequence::Indistinguishable;
2763 }
2764
2765 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00002766 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002767 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002768 }
2769
Douglas Gregor57373262008-10-22 14:17:15 +00002770 // Check that the winning standard conversion sequence isn't using
2771 // the deprecated string literal array to pointer conversion.
2772 switch (Result) {
2773 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002774 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002775 Result = ImplicitConversionSequence::Indistinguishable;
2776 break;
2777
2778 case ImplicitConversionSequence::Indistinguishable:
2779 break;
2780
2781 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002782 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002783 Result = ImplicitConversionSequence::Indistinguishable;
2784 break;
2785 }
2786
2787 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002788}
2789
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002790/// CompareDerivedToBaseConversions - Compares two standard conversion
2791/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002792/// various kinds of derived-to-base conversions (C++
2793/// [over.ics.rank]p4b3). As part of these checks, we also look at
2794/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002795ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002796CompareDerivedToBaseConversions(Sema &S,
2797 const StandardConversionSequence& SCS1,
2798 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002799 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002800 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002801 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002802 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002803
2804 // Adjust the types we're converting from via the array-to-pointer
2805 // conversion, if we need to.
2806 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002807 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002808 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002809 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002810
2811 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00002812 FromType1 = S.Context.getCanonicalType(FromType1);
2813 ToType1 = S.Context.getCanonicalType(ToType1);
2814 FromType2 = S.Context.getCanonicalType(FromType2);
2815 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002816
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002817 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002818 //
2819 // If class B is derived directly or indirectly from class A and
2820 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002821 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002822 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002823 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002824 SCS2.Second == ICK_Pointer_Conversion &&
2825 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2826 FromType1->isPointerType() && FromType2->isPointerType() &&
2827 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002828 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002829 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002830 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002831 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002832 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002833 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002834 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002835 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002836
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002837 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002838 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002839 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002840 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002841 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002842 return ImplicitConversionSequence::Worse;
2843 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002844
2845 // -- conversion of B* to A* is better than conversion of C* to A*,
2846 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002847 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002848 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002849 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002850 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00002851 }
2852 } else if (SCS1.Second == ICK_Pointer_Conversion &&
2853 SCS2.Second == ICK_Pointer_Conversion) {
2854 const ObjCObjectPointerType *FromPtr1
2855 = FromType1->getAs<ObjCObjectPointerType>();
2856 const ObjCObjectPointerType *FromPtr2
2857 = FromType2->getAs<ObjCObjectPointerType>();
2858 const ObjCObjectPointerType *ToPtr1
2859 = ToType1->getAs<ObjCObjectPointerType>();
2860 const ObjCObjectPointerType *ToPtr2
2861 = ToType2->getAs<ObjCObjectPointerType>();
2862
2863 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
2864 // Apply the same conversion ranking rules for Objective-C pointer types
2865 // that we do for C++ pointers to class types. However, we employ the
2866 // Objective-C pseudo-subtyping relationship used for assignment of
2867 // Objective-C pointer types.
2868 bool FromAssignLeft
2869 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
2870 bool FromAssignRight
2871 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
2872 bool ToAssignLeft
2873 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
2874 bool ToAssignRight
2875 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
2876
2877 // A conversion to an a non-id object pointer type or qualified 'id'
2878 // type is better than a conversion to 'id'.
2879 if (ToPtr1->isObjCIdType() &&
2880 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
2881 return ImplicitConversionSequence::Worse;
2882 if (ToPtr2->isObjCIdType() &&
2883 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
2884 return ImplicitConversionSequence::Better;
2885
2886 // A conversion to a non-id object pointer type is better than a
2887 // conversion to a qualified 'id' type
2888 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
2889 return ImplicitConversionSequence::Worse;
2890 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
2891 return ImplicitConversionSequence::Better;
2892
2893 // A conversion to an a non-Class object pointer type or qualified 'Class'
2894 // type is better than a conversion to 'Class'.
2895 if (ToPtr1->isObjCClassType() &&
2896 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
2897 return ImplicitConversionSequence::Worse;
2898 if (ToPtr2->isObjCClassType() &&
2899 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
2900 return ImplicitConversionSequence::Better;
2901
2902 // A conversion to a non-Class object pointer type is better than a
2903 // conversion to a qualified 'Class' type.
2904 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
2905 return ImplicitConversionSequence::Worse;
2906 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
2907 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00002908
Douglas Gregor395cc372011-01-31 18:51:41 +00002909 // -- "conversion of C* to B* is better than conversion of C* to A*,"
2910 if (S.Context.hasSameType(FromType1, FromType2) &&
2911 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
2912 (ToAssignLeft != ToAssignRight))
2913 return ToAssignLeft? ImplicitConversionSequence::Worse
2914 : ImplicitConversionSequence::Better;
2915
2916 // -- "conversion of B* to A* is better than conversion of C* to A*,"
2917 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
2918 (FromAssignLeft != FromAssignRight))
2919 return FromAssignLeft? ImplicitConversionSequence::Better
2920 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002921 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002922 }
Douglas Gregor395cc372011-01-31 18:51:41 +00002923
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002924 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002925 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2926 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2927 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002928 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002929 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002930 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002931 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002932 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002933 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002934 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002935 ToType2->getAs<MemberPointerType>();
2936 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2937 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2938 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2939 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2940 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2941 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2942 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2943 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002944 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002945 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002946 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002947 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00002948 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002949 return ImplicitConversionSequence::Better;
2950 }
2951 // conversion of B::* to C::* is better than conversion of A::* to C::*
2952 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002953 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002954 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002955 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002956 return ImplicitConversionSequence::Worse;
2957 }
2958 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002959
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002960 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002961 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002962 // -- binding of an expression of type C to a reference of type
2963 // B& is better than binding an expression of type C to a
2964 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002965 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2966 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2967 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002968 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002969 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002970 return ImplicitConversionSequence::Worse;
2971 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002972
Douglas Gregor225c41e2008-11-03 19:09:14 +00002973 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002974 // -- binding of an expression of type B to a reference of type
2975 // A& is better than binding an expression of type C to a
2976 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002977 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2978 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2979 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002980 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002981 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002982 return ImplicitConversionSequence::Worse;
2983 }
2984 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002985
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002986 return ImplicitConversionSequence::Indistinguishable;
2987}
2988
Douglas Gregorabe183d2010-04-13 16:31:36 +00002989/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2990/// determine whether they are reference-related,
2991/// reference-compatible, reference-compatible with added
2992/// qualification, or incompatible, for use in C++ initialization by
2993/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2994/// type, and the first type (T1) is the pointee type of the reference
2995/// type being initialized.
2996Sema::ReferenceCompareResult
2997Sema::CompareReferenceRelationship(SourceLocation Loc,
2998 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00002999 bool &DerivedToBase,
3000 bool &ObjCConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003001 assert(!OrigT1->isReferenceType() &&
3002 "T1 must be the pointee type of the reference type");
3003 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3004
3005 QualType T1 = Context.getCanonicalType(OrigT1);
3006 QualType T2 = Context.getCanonicalType(OrigT2);
3007 Qualifiers T1Quals, T2Quals;
3008 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3009 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3010
3011 // C++ [dcl.init.ref]p4:
3012 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3013 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3014 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003015 DerivedToBase = false;
3016 ObjCConversion = false;
3017 if (UnqualT1 == UnqualT2) {
3018 // Nothing to do.
3019 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003020 IsDerivedFrom(UnqualT2, UnqualT1))
3021 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003022 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3023 UnqualT2->isObjCObjectOrInterfaceType() &&
3024 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3025 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003026 else
3027 return Ref_Incompatible;
3028
3029 // At this point, we know that T1 and T2 are reference-related (at
3030 // least).
3031
3032 // If the type is an array type, promote the element qualifiers to the type
3033 // for comparison.
3034 if (isa<ArrayType>(T1) && T1Quals)
3035 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3036 if (isa<ArrayType>(T2) && T2Quals)
3037 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3038
3039 // C++ [dcl.init.ref]p4:
3040 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3041 // reference-related to T2 and cv1 is the same cv-qualification
3042 // as, or greater cv-qualification than, cv2. For purposes of
3043 // overload resolution, cases for which cv1 is greater
3044 // cv-qualification than cv2 are identified as
3045 // reference-compatible with added qualification (see 13.3.3.2).
3046 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
3047 return Ref_Compatible;
3048 else if (T1.isMoreQualifiedThan(T2))
3049 return Ref_Compatible_With_Added_Qualification;
3050 else
3051 return Ref_Related;
3052}
3053
Douglas Gregor604eb652010-08-11 02:15:33 +00003054/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003055/// with DeclType. Return true if something definite is found.
3056static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003057FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3058 QualType DeclType, SourceLocation DeclLoc,
3059 Expr *Init, QualType T2, bool AllowRvalues,
3060 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003061 assert(T2->isRecordType() && "Can only find conversions of record types.");
3062 CXXRecordDecl *T2RecordDecl
3063 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3064
3065 OverloadCandidateSet CandidateSet(DeclLoc);
3066 const UnresolvedSetImpl *Conversions
3067 = T2RecordDecl->getVisibleConversionFunctions();
3068 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3069 E = Conversions->end(); I != E; ++I) {
3070 NamedDecl *D = *I;
3071 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3072 if (isa<UsingShadowDecl>(D))
3073 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3074
3075 FunctionTemplateDecl *ConvTemplate
3076 = dyn_cast<FunctionTemplateDecl>(D);
3077 CXXConversionDecl *Conv;
3078 if (ConvTemplate)
3079 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3080 else
3081 Conv = cast<CXXConversionDecl>(D);
3082
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003083 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003084 // explicit conversions, skip it.
3085 if (!AllowExplicit && Conv->isExplicit())
3086 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003087
Douglas Gregor604eb652010-08-11 02:15:33 +00003088 if (AllowRvalues) {
3089 bool DerivedToBase = false;
3090 bool ObjCConversion = false;
3091 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00003092 S.CompareReferenceRelationship(
3093 DeclLoc,
3094 Conv->getConversionType().getNonReferenceType()
3095 .getUnqualifiedType(),
3096 DeclType.getNonReferenceType().getUnqualifiedType(),
3097 DerivedToBase, ObjCConversion) ==
3098 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00003099 continue;
3100 } else {
3101 // If the conversion function doesn't return a reference type,
3102 // it can't be considered for this conversion. An rvalue reference
3103 // is only acceptable if its referencee is a function type.
3104
3105 const ReferenceType *RefType =
3106 Conv->getConversionType()->getAs<ReferenceType>();
3107 if (!RefType ||
3108 (!RefType->isLValueReferenceType() &&
3109 !RefType->getPointeeType()->isFunctionType()))
3110 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003111 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003112
Douglas Gregor604eb652010-08-11 02:15:33 +00003113 if (ConvTemplate)
3114 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003115 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00003116 else
3117 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003118 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003119 }
3120
3121 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003122 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003123 case OR_Success:
3124 // C++ [over.ics.ref]p1:
3125 //
3126 // [...] If the parameter binds directly to the result of
3127 // applying a conversion function to the argument
3128 // expression, the implicit conversion sequence is a
3129 // user-defined conversion sequence (13.3.3.1.2), with the
3130 // second standard conversion sequence either an identity
3131 // conversion or, if the conversion function returns an
3132 // entity of a type that is a derived class of the parameter
3133 // type, a derived-to-base Conversion.
3134 if (!Best->FinalConversion.DirectBinding)
3135 return false;
3136
Chandler Carruth25ca4212011-02-25 19:41:05 +00003137 if (Best->Function)
3138 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003139 ICS.setUserDefined();
3140 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3141 ICS.UserDefined.After = Best->FinalConversion;
3142 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor83eecbe2011-01-20 01:32:05 +00003143 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redl4680bf22010-06-30 18:13:39 +00003144 ICS.UserDefined.EllipsisConversion = false;
3145 assert(ICS.UserDefined.After.ReferenceBinding &&
3146 ICS.UserDefined.After.DirectBinding &&
3147 "Expected a direct reference binding!");
3148 return true;
3149
3150 case OR_Ambiguous:
3151 ICS.setAmbiguous();
3152 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3153 Cand != CandidateSet.end(); ++Cand)
3154 if (Cand->Viable)
3155 ICS.Ambiguous.addConversion(Cand->Function);
3156 return true;
3157
3158 case OR_No_Viable_Function:
3159 case OR_Deleted:
3160 // There was no suitable conversion, or we found a deleted
3161 // conversion; continue with other checks.
3162 return false;
3163 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003164
Eric Christopher1c3d5022010-06-30 18:36:32 +00003165 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003166}
3167
Douglas Gregorabe183d2010-04-13 16:31:36 +00003168/// \brief Compute an implicit conversion sequence for reference
3169/// initialization.
3170static ImplicitConversionSequence
3171TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3172 SourceLocation DeclLoc,
3173 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003174 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003175 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3176
3177 // Most paths end in a failed conversion.
3178 ImplicitConversionSequence ICS;
3179 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3180
3181 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3182 QualType T2 = Init->getType();
3183
3184 // If the initializer is the address of an overloaded function, try
3185 // to resolve the overloaded function. If all goes well, T2 is the
3186 // type of the resulting function.
3187 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3188 DeclAccessPair Found;
3189 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3190 false, Found))
3191 T2 = Fn->getType();
3192 }
3193
3194 // Compute some basic properties of the types and the initializer.
3195 bool isRValRef = DeclType->isRValueReferenceType();
3196 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003197 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003198 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003199 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003200 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
3201 ObjCConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003202
Douglas Gregorabe183d2010-04-13 16:31:36 +00003203
Sebastian Redl4680bf22010-06-30 18:13:39 +00003204 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00003205 // A reference to type "cv1 T1" is initialized by an expression
3206 // of type "cv2 T2" as follows:
3207
Sebastian Redl4680bf22010-06-30 18:13:39 +00003208 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003209 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003210 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3211 // reference-compatible with "cv2 T2," or
3212 //
3213 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3214 if (InitCategory.isLValue() &&
3215 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003216 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00003217 // When a parameter of reference type binds directly (8.5.3)
3218 // to an argument expression, the implicit conversion sequence
3219 // is the identity conversion, unless the argument expression
3220 // has a type that is a derived class of the parameter type,
3221 // in which case the implicit conversion sequence is a
3222 // derived-to-base Conversion (13.3.3.1).
3223 ICS.setStandard();
3224 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00003225 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3226 : ObjCConversion? ICK_Compatible_Conversion
3227 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003228 ICS.Standard.Third = ICK_Identity;
3229 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3230 ICS.Standard.setToType(0, T2);
3231 ICS.Standard.setToType(1, T1);
3232 ICS.Standard.setToType(2, T1);
3233 ICS.Standard.ReferenceBinding = true;
3234 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003235 ICS.Standard.IsLvalueReference = !isRValRef;
3236 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3237 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003238 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003239 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003240
Sebastian Redl4680bf22010-06-30 18:13:39 +00003241 // Nothing more to do: the inaccessibility/ambiguity check for
3242 // derived-to-base conversions is suppressed when we're
3243 // computing the implicit conversion sequence (C++
3244 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00003245 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003246 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00003247
Sebastian Redl4680bf22010-06-30 18:13:39 +00003248 // -- has a class type (i.e., T2 is a class type), where T1 is
3249 // not reference-related to T2, and can be implicitly
3250 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3251 // is reference-compatible with "cv3 T3" 92) (this
3252 // conversion is selected by enumerating the applicable
3253 // conversion functions (13.3.1.6) and choosing the best
3254 // one through overload resolution (13.3)),
3255 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003256 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00003257 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00003258 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3259 Init, T2, /*AllowRvalues=*/false,
3260 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00003261 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003262 }
3263 }
3264
Sebastian Redl4680bf22010-06-30 18:13:39 +00003265 // -- Otherwise, the reference shall be an lvalue reference to a
3266 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003267 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003268 //
Douglas Gregor66821b52010-04-18 09:22:00 +00003269 // We actually handle one oddity of C++ [over.ics.ref] at this
3270 // point, which is that, due to p2 (which short-circuits reference
3271 // binding by only attempting a simple conversion for non-direct
3272 // bindings) and p3's strange wording, we allow a const volatile
3273 // reference to bind to an rvalue. Hence the check for the presence
3274 // of "const" rather than checking for "const" being the only
3275 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00003276 // This is also the point where rvalue references and lvalue inits no longer
3277 // go together.
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003278 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00003279 return ICS;
3280
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003281 // -- If the initializer expression
3282 //
3283 // -- is an xvalue, class prvalue, array prvalue or function
3284 // lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3285 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3286 (InitCategory.isXValue() ||
3287 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3288 (InitCategory.isLValue() && T2->isFunctionType()))) {
3289 ICS.setStandard();
3290 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003291 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003292 : ObjCConversion? ICK_Compatible_Conversion
3293 : ICK_Identity;
3294 ICS.Standard.Third = ICK_Identity;
3295 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3296 ICS.Standard.setToType(0, T2);
3297 ICS.Standard.setToType(1, T1);
3298 ICS.Standard.setToType(2, T1);
3299 ICS.Standard.ReferenceBinding = true;
3300 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3301 // binding unless we're binding to a class prvalue.
3302 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3303 // allow the use of rvalue references in C++98/03 for the benefit of
3304 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003305 ICS.Standard.DirectBinding =
3306 S.getLangOptions().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003307 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00003308 ICS.Standard.IsLvalueReference = !isRValRef;
3309 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003310 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003311 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003312 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003313 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003314 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003315
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003316 // -- has a class type (i.e., T2 is a class type), where T1 is not
3317 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003318 // an xvalue, class prvalue, or function lvalue of type
3319 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003320 // "cv3 T3",
3321 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003322 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003323 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003324 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003325 // class subobject).
3326 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003327 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003328 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3329 Init, T2, /*AllowRvalues=*/true,
3330 AllowExplicit)) {
3331 // In the second case, if the reference is an rvalue reference
3332 // and the second standard conversion sequence of the
3333 // user-defined conversion sequence includes an lvalue-to-rvalue
3334 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003335 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003336 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3337 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3338
Douglas Gregor68ed68b2011-01-21 16:36:05 +00003339 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00003340 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003341
Douglas Gregorabe183d2010-04-13 16:31:36 +00003342 // -- Otherwise, a temporary of type "cv1 T1" is created and
3343 // initialized from the initializer expression using the
3344 // rules for a non-reference copy initialization (8.5). The
3345 // reference is then bound to the temporary. If T1 is
3346 // reference-related to T2, cv1 must be the same
3347 // cv-qualification as, or greater cv-qualification than,
3348 // cv2; otherwise, the program is ill-formed.
3349 if (RefRelationship == Sema::Ref_Related) {
3350 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3351 // we would be reference-compatible or reference-compatible with
3352 // added qualification. But that wasn't the case, so the reference
3353 // initialization fails.
3354 return ICS;
3355 }
3356
3357 // If at least one of the types is a class type, the types are not
3358 // related, and we aren't allowed any user conversions, the
3359 // reference binding fails. This case is important for breaking
3360 // recursion, since TryImplicitConversion below will attempt to
3361 // create a temporary through the use of a copy constructor.
3362 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3363 (T1->isRecordType() || T2->isRecordType()))
3364 return ICS;
3365
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003366 // If T1 is reference-related to T2 and the reference is an rvalue
3367 // reference, the initializer expression shall not be an lvalue.
3368 if (RefRelationship >= Sema::Ref_Related &&
3369 isRValRef && Init->Classify(S.Context).isLValue())
3370 return ICS;
3371
Douglas Gregorabe183d2010-04-13 16:31:36 +00003372 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00003373 // When a parameter of reference type is not bound directly to
3374 // an argument expression, the conversion sequence is the one
3375 // required to convert the argument expression to the
3376 // underlying type of the reference according to
3377 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3378 // to copy-initializing a temporary of the underlying type with
3379 // the argument expression. Any difference in top-level
3380 // cv-qualification is subsumed by the initialization itself
3381 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00003382 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3383 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003384 /*InOverloadResolution=*/false,
3385 /*CStyle=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003386
3387 // Of course, that's still a reference binding.
3388 if (ICS.isStandard()) {
3389 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003390 ICS.Standard.IsLvalueReference = !isRValRef;
3391 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3392 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003393 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003394 } else if (ICS.isUserDefined()) {
3395 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003396 ICS.Standard.IsLvalueReference = !isRValRef;
3397 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3398 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003399 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003400 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003401
Douglas Gregorabe183d2010-04-13 16:31:36 +00003402 return ICS;
3403}
3404
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003405/// TryCopyInitialization - Try to copy-initialize a value of type
3406/// ToType from the expression From. Return the implicit conversion
3407/// sequence required to pass this argument, which may be a bad
3408/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00003409/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00003410/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00003411static ImplicitConversionSequence
3412TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003413 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00003414 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003415 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00003416 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003417 /*FIXME:*/From->getLocStart(),
3418 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003419 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003420
John McCall120d63c2010-08-24 20:38:10 +00003421 return TryImplicitConversion(S, From, ToType,
3422 SuppressUserConversions,
3423 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003424 InOverloadResolution,
3425 /*CStyle=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003426}
3427
Douglas Gregor96176b32008-11-18 23:14:02 +00003428/// TryObjectArgumentInitialization - Try to initialize the object
3429/// parameter of the given member function (@c Method) from the
3430/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00003431static ImplicitConversionSequence
3432TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003433 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00003434 CXXMethodDecl *Method,
3435 CXXRecordDecl *ActingContext) {
3436 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003437 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3438 // const volatile object.
3439 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3440 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00003441 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00003442
3443 // Set up the conversion sequence as a "bad" conversion, to allow us
3444 // to exit early.
3445 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00003446
3447 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00003448 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003449 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003450 FromType = PT->getPointeeType();
3451
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003452 // When we had a pointer, it's implicitly dereferenced, so we
3453 // better have an lvalue.
3454 assert(FromClassification.isLValue());
3455 }
3456
Anders Carlssona552f7c2009-05-01 18:34:30 +00003457 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00003458
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003459 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003460 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003461 // parameter is
3462 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003463 // - "lvalue reference to cv X" for functions declared without a
3464 // ref-qualifier or with the & ref-qualifier
3465 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003466 // ref-qualifier
3467 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003468 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003469 // cv-qualification on the member function declaration.
3470 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003471 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003472 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00003473 // (C++ [over.match.funcs]p5). We perform a simplified version of
3474 // reference binding here, that allows class rvalues to bind to
3475 // non-constant references.
3476
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003477 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00003478 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003479 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00003480 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00003481 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00003482 ICS.setBad(BadConversionSequence::bad_qualifiers,
3483 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003484 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003485 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003486
3487 // Check that we have either the same type or a derived type. It
3488 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00003489 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00003490 ImplicitConversionKind SecondKind;
3491 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3492 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00003493 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00003494 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00003495 else {
John McCallb1bdc622010-02-25 01:37:24 +00003496 ICS.setBad(BadConversionSequence::unrelated_class,
3497 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003498 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003499 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003500
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003501 // Check the ref-qualifier.
3502 switch (Method->getRefQualifier()) {
3503 case RQ_None:
3504 // Do nothing; we don't care about lvalueness or rvalueness.
3505 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003506
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003507 case RQ_LValue:
3508 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3509 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003510 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003511 ImplicitParamType);
3512 return ICS;
3513 }
3514 break;
3515
3516 case RQ_RValue:
3517 if (!FromClassification.isRValue()) {
3518 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003519 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003520 ImplicitParamType);
3521 return ICS;
3522 }
3523 break;
3524 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003525
Douglas Gregor96176b32008-11-18 23:14:02 +00003526 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00003527 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003528 ICS.Standard.setAsIdentityConversion();
3529 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003530 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003531 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003532 ICS.Standard.ReferenceBinding = true;
3533 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003534 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00003535 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003536 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3537 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3538 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00003539 return ICS;
3540}
3541
3542/// PerformObjectArgumentInitialization - Perform initialization of
3543/// the implicit object parameter for the given Method with the given
3544/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00003545ExprResult
3546Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003547 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003548 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003549 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003550 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003551 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003552 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003553
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003554 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00003555 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003556 FromRecordType = PT->getPointeeType();
3557 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003558 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00003559 } else {
3560 FromRecordType = From->getType();
3561 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003562 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00003563 }
3564
John McCall701c89e2009-12-03 04:06:58 +00003565 // Note that we always use the true parent context when performing
3566 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003567 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003568 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3569 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003570 if (ICS.isBad()) {
3571 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3572 Qualifiers FromQs = FromRecordType.getQualifiers();
3573 Qualifiers ToQs = DestType.getQualifiers();
3574 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3575 if (CVR) {
3576 Diag(From->getSourceRange().getBegin(),
3577 diag::err_member_function_call_bad_cvr)
3578 << Method->getDeclName() << FromRecordType << (CVR - 1)
3579 << From->getSourceRange();
3580 Diag(Method->getLocation(), diag::note_previous_decl)
3581 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00003582 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003583 }
3584 }
3585
Douglas Gregor96176b32008-11-18 23:14:02 +00003586 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003587 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003588 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003589 }
Mike Stump1eb44332009-09-09 15:08:12 +00003590
John Wiegley429bb272011-04-08 18:41:53 +00003591 if (ICS.Standard.Second == ICK_Derived_To_Base) {
3592 ExprResult FromRes =
3593 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3594 if (FromRes.isInvalid())
3595 return ExprError();
3596 From = FromRes.take();
3597 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003598
Douglas Gregor5fccd362010-03-03 23:55:11 +00003599 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00003600 From = ImpCastExprToType(From, DestType, CK_NoOp,
3601 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3602 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00003603}
3604
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003605/// TryContextuallyConvertToBool - Attempt to contextually convert the
3606/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00003607static ImplicitConversionSequence
3608TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003609 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00003610 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003611 // FIXME: Are these flags correct?
3612 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003613 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003614 /*InOverloadResolution=*/false,
3615 /*CStyle=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003616}
3617
3618/// PerformContextuallyConvertToBool - Perform a contextual conversion
3619/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00003620ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall120d63c2010-08-24 20:38:10 +00003621 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00003622 if (!ICS.isBad())
3623 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003624
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003625 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003626 return Diag(From->getSourceRange().getBegin(),
3627 diag::err_typecheck_bool_condition)
3628 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003629 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003630}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003631
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003632/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3633/// expression From to 'id'.
John McCall120d63c2010-08-24 20:38:10 +00003634static ImplicitConversionSequence
3635TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3636 QualType Ty = S.Context.getObjCIdType();
3637 return TryImplicitConversion(S, From, Ty,
3638 // FIXME: Are these flags correct?
3639 /*SuppressUserConversions=*/false,
3640 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003641 /*InOverloadResolution=*/false,
3642 /*CStyle=*/false);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003643}
John McCall120d63c2010-08-24 20:38:10 +00003644
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003645/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3646/// of the expression From to 'id'.
John Wiegley429bb272011-04-08 18:41:53 +00003647ExprResult Sema::PerformContextuallyConvertToObjCId(Expr *From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003648 QualType Ty = Context.getObjCIdType();
John McCall120d63c2010-08-24 20:38:10 +00003649 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003650 if (!ICS.isBad())
3651 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00003652 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003653}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003654
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003655/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00003656/// enumeration type.
3657///
3658/// This routine will attempt to convert an expression of class type to an
3659/// integral or enumeration type, if that class type only has a single
3660/// conversion to an integral or enumeration type.
3661///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003662/// \param Loc The source location of the construct that requires the
3663/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003664///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003665/// \param FromE The expression we're converting from.
3666///
3667/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3668/// have integral or enumeration type.
3669///
3670/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3671/// incomplete class type.
3672///
3673/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3674/// explicit conversion function (because no implicit conversion functions
3675/// were available). This is a recovery mode.
3676///
3677/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3678/// showing which conversion was picked.
3679///
3680/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3681/// conversion function that could convert to integral or enumeration type.
3682///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003683/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003684/// usable conversion function.
3685///
3686/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3687/// function, which may be an extension in this case.
3688///
3689/// \returns The expression, converted to an integral or enumeration type if
3690/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003691ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003692Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003693 const PartialDiagnostic &NotIntDiag,
3694 const PartialDiagnostic &IncompleteDiag,
3695 const PartialDiagnostic &ExplicitConvDiag,
3696 const PartialDiagnostic &ExplicitConvNote,
3697 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003698 const PartialDiagnostic &AmbigNote,
3699 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00003700 // We can't perform any more checking for type-dependent expressions.
3701 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00003702 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003703
Douglas Gregorc30614b2010-06-29 23:17:37 +00003704 // If the expression already has integral or enumeration type, we're golden.
3705 QualType T = From->getType();
3706 if (T->isIntegralOrEnumerationType())
John McCall9ae2f072010-08-23 23:25:46 +00003707 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003708
3709 // FIXME: Check for missing '()' if T is a function type?
3710
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003711 // If we don't have a class type in C++, there's no way we can get an
Douglas Gregorc30614b2010-06-29 23:17:37 +00003712 // expression of integral or enumeration type.
3713 const RecordType *RecordTy = T->getAs<RecordType>();
3714 if (!RecordTy || !getLangOptions().CPlusPlus) {
3715 Diag(Loc, NotIntDiag)
3716 << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00003717 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003718 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003719
Douglas Gregorc30614b2010-06-29 23:17:37 +00003720 // We must have a complete class type.
3721 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00003722 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003723
Douglas Gregorc30614b2010-06-29 23:17:37 +00003724 // Look for a conversion to an integral or enumeration type.
3725 UnresolvedSet<4> ViableConversions;
3726 UnresolvedSet<4> ExplicitConversions;
3727 const UnresolvedSetImpl *Conversions
3728 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003729
Douglas Gregorc30614b2010-06-29 23:17:37 +00003730 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003731 E = Conversions->end();
3732 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00003733 ++I) {
3734 if (CXXConversionDecl *Conversion
3735 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3736 if (Conversion->getConversionType().getNonReferenceType()
3737 ->isIntegralOrEnumerationType()) {
3738 if (Conversion->isExplicit())
3739 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3740 else
3741 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3742 }
3743 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003744
Douglas Gregorc30614b2010-06-29 23:17:37 +00003745 switch (ViableConversions.size()) {
3746 case 0:
3747 if (ExplicitConversions.size() == 1) {
3748 DeclAccessPair Found = ExplicitConversions[0];
3749 CXXConversionDecl *Conversion
3750 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003751
Douglas Gregorc30614b2010-06-29 23:17:37 +00003752 // The user probably meant to invoke the given explicit
3753 // conversion; use it.
3754 QualType ConvTy
3755 = Conversion->getConversionType().getNonReferenceType();
3756 std::string TypeStr;
3757 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003758
Douglas Gregorc30614b2010-06-29 23:17:37 +00003759 Diag(Loc, ExplicitConvDiag)
3760 << T << ConvTy
3761 << FixItHint::CreateInsertion(From->getLocStart(),
3762 "static_cast<" + TypeStr + ">(")
3763 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3764 ")");
3765 Diag(Conversion->getLocation(), ExplicitConvNote)
3766 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003767
3768 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00003769 // explicit conversion function.
3770 if (isSFINAEContext())
3771 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003772
Douglas Gregorc30614b2010-06-29 23:17:37 +00003773 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003774 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3775 if (Result.isInvalid())
3776 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003777
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003778 From = Result.get();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003779 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003780
Douglas Gregorc30614b2010-06-29 23:17:37 +00003781 // We'll complain below about a non-integral condition type.
3782 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003783
Douglas Gregorc30614b2010-06-29 23:17:37 +00003784 case 1: {
3785 // Apply this conversion.
3786 DeclAccessPair Found = ViableConversions[0];
3787 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003788
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003789 CXXConversionDecl *Conversion
3790 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3791 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003792 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003793 if (ConvDiag.getDiagID()) {
3794 if (isSFINAEContext())
3795 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003796
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003797 Diag(Loc, ConvDiag)
3798 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3799 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003800
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003801 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003802 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003803 if (Result.isInvalid())
3804 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003805
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003806 From = Result.get();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003807 break;
3808 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003809
Douglas Gregorc30614b2010-06-29 23:17:37 +00003810 default:
3811 Diag(Loc, AmbigDiag)
3812 << T << From->getSourceRange();
3813 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3814 CXXConversionDecl *Conv
3815 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3816 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3817 Diag(Conv->getLocation(), AmbigNote)
3818 << ConvTy->isEnumeralType() << ConvTy;
3819 }
John McCall9ae2f072010-08-23 23:25:46 +00003820 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003821 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003822
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003823 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00003824 Diag(Loc, NotIntDiag)
3825 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003826
John McCall9ae2f072010-08-23 23:25:46 +00003827 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003828}
3829
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003830/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003831/// candidate functions, using the given function call arguments. If
3832/// @p SuppressUserConversions, then don't allow user-defined
3833/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003834///
3835/// \para PartialOverloading true if we are performing "partial" overloading
3836/// based on an incomplete set of function arguments. This feature is used by
3837/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003838void
3839Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003840 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003841 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003842 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003843 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003844 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003845 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003846 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003847 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003848 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003849 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003850
Douglas Gregor88a35142008-12-22 05:46:06 +00003851 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003852 if (!isa<CXXConstructorDecl>(Method)) {
3853 // If we get here, it's because we're calling a member function
3854 // that is named without a member access expression (e.g.,
3855 // "this->f") that was either written explicitly or created
3856 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003857 // function, e.g., X::f(). We use an empty type for the implied
3858 // object argument (C++ [over.call.func]p3), and the acting context
3859 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003860 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003861 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003862 Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003863 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003864 return;
3865 }
3866 // We treat a constructor like a non-member function, since its object
3867 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003868 }
3869
Douglas Gregorfd476482009-11-13 23:59:09 +00003870 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003871 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003872
Douglas Gregor7edfb692009-11-23 12:27:39 +00003873 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003874 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003875
Douglas Gregor66724ea2009-11-14 01:20:54 +00003876 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3877 // C++ [class.copy]p3:
3878 // A member function template is never instantiated to perform the copy
3879 // of a class object to an object of its class type.
3880 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003881 if (NumArgs == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00003882 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003883 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3884 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003885 return;
3886 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003887
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003888 // Add this candidate
3889 CandidateSet.push_back(OverloadCandidate());
3890 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003891 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003892 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003893 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003894 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003895 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00003896 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003897
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003898 unsigned NumArgsInProto = Proto->getNumArgs();
3899
3900 // (C++ 13.3.2p2): A candidate function having fewer than m
3901 // parameters is viable only if it has an ellipsis in its parameter
3902 // list (8.3.5).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003903 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003904 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003905 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003906 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003907 return;
3908 }
3909
3910 // (C++ 13.3.2p2): A candidate function having more than m parameters
3911 // is viable only if the (m+1)st parameter has a default argument
3912 // (8.3.6). For the purposes of overload resolution, the
3913 // parameter list is truncated on the right, so that there are
3914 // exactly m parameters.
3915 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003916 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003917 // Not enough arguments.
3918 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003919 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003920 return;
3921 }
3922
3923 // Determine the implicit conversion sequences for each of the
3924 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003925 Candidate.Conversions.resize(NumArgs);
3926 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3927 if (ArgIdx < NumArgsInProto) {
3928 // (C++ 13.3.2p3): for F to be a viable function, there shall
3929 // exist for each argument an implicit conversion sequence
3930 // (13.3.3.1) that converts that argument to the corresponding
3931 // parameter of F.
3932 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003933 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003934 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003935 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003936 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003937 if (Candidate.Conversions[ArgIdx].isBad()) {
3938 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003939 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003940 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003941 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003942 } else {
3943 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3944 // argument for which there is no corresponding parameter is
3945 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003946 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003947 }
3948 }
3949}
3950
Douglas Gregor063daf62009-03-13 18:40:31 +00003951/// \brief Add all of the function declarations in the given function set to
3952/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003953void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003954 Expr **Args, unsigned NumArgs,
3955 OverloadCandidateSet& CandidateSet,
3956 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003957 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003958 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3959 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003960 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003961 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003962 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003963 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003964 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003965 CandidateSet, SuppressUserConversions);
3966 else
John McCall9aa472c2010-03-19 07:35:19 +00003967 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003968 SuppressUserConversions);
3969 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003970 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003971 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3972 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003973 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003974 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003975 /*FIXME: explicit args */ 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003976 Args[0]->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003977 Args[0]->Classify(Context),
3978 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003979 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003980 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003981 else
John McCall9aa472c2010-03-19 07:35:19 +00003982 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003983 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003984 Args, NumArgs, CandidateSet,
3985 SuppressUserConversions);
3986 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003987 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003988}
3989
John McCall314be4e2009-11-17 07:50:12 +00003990/// AddMethodCandidate - Adds a named decl (which is some kind of
3991/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003992void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003993 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003994 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00003995 Expr **Args, unsigned NumArgs,
3996 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003997 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003998 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003999 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00004000
4001 if (isa<UsingShadowDecl>(Decl))
4002 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004003
John McCall314be4e2009-11-17 07:50:12 +00004004 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4005 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4006 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00004007 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4008 /*ExplicitArgs*/ 0,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004009 ObjectType, ObjectClassification, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00004010 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004011 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00004012 } else {
John McCall9aa472c2010-03-19 07:35:19 +00004013 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004014 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004015 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00004016 }
4017}
4018
Douglas Gregor96176b32008-11-18 23:14:02 +00004019/// AddMethodCandidate - Adds the given C++ member function to the set
4020/// of candidate functions, using the given function call arguments
4021/// and the object argument (@c Object). For example, in a call
4022/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4023/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4024/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00004025/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00004026void
John McCall9aa472c2010-03-19 07:35:19 +00004027Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00004028 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004029 Expr::Classification ObjectClassification,
John McCall86820f52010-01-26 01:37:31 +00004030 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00004031 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004032 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00004033 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00004034 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00004035 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004036 assert(!isa<CXXConstructorDecl>(Method) &&
4037 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00004038
Douglas Gregor3f396022009-09-28 04:47:19 +00004039 if (!CandidateSet.isNewCandidate(Method))
4040 return;
4041
Douglas Gregor7edfb692009-11-23 12:27:39 +00004042 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004043 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004044
Douglas Gregor96176b32008-11-18 23:14:02 +00004045 // Add this candidate
4046 CandidateSet.push_back(OverloadCandidate());
4047 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004048 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00004049 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004050 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004051 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004052 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor96176b32008-11-18 23:14:02 +00004053
4054 unsigned NumArgsInProto = Proto->getNumArgs();
4055
4056 // (C++ 13.3.2p2): A candidate function having fewer than m
4057 // parameters is viable only if it has an ellipsis in its parameter
4058 // list (8.3.5).
4059 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4060 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004061 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00004062 return;
4063 }
4064
4065 // (C++ 13.3.2p2): A candidate function having more than m parameters
4066 // is viable only if the (m+1)st parameter has a default argument
4067 // (8.3.6). For the purposes of overload resolution, the
4068 // parameter list is truncated on the right, so that there are
4069 // exactly m parameters.
4070 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4071 if (NumArgs < MinRequiredArgs) {
4072 // Not enough arguments.
4073 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004074 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00004075 return;
4076 }
4077
4078 Candidate.Viable = true;
4079 Candidate.Conversions.resize(NumArgs + 1);
4080
John McCall701c89e2009-12-03 04:06:58 +00004081 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00004082 // The implicit object argument is ignored.
4083 Candidate.IgnoreObjectArgument = true;
4084 else {
4085 // Determine the implicit conversion sequence for the object
4086 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00004087 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004088 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4089 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00004090 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004091 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004092 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00004093 return;
4094 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004095 }
4096
4097 // Determine the implicit conversion sequences for each of the
4098 // arguments.
4099 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4100 if (ArgIdx < NumArgsInProto) {
4101 // (C++ 13.3.2p3): for F to be a viable function, there shall
4102 // exist for each argument an implicit conversion sequence
4103 // (13.3.3.1) that converts that argument to the corresponding
4104 // parameter of F.
4105 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004106 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004107 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004108 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00004109 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00004110 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004111 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004112 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004113 break;
4114 }
4115 } else {
4116 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4117 // argument for which there is no corresponding parameter is
4118 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004119 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00004120 }
4121 }
4122}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004123
Douglas Gregor6b906862009-08-21 00:16:32 +00004124/// \brief Add a C++ member function template as a candidate to the candidate
4125/// set, using template argument deduction to produce an appropriate member
4126/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004127void
Douglas Gregor6b906862009-08-21 00:16:32 +00004128Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00004129 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004130 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00004131 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00004132 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004133 Expr::Classification ObjectClassification,
John McCall701c89e2009-12-03 04:06:58 +00004134 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00004135 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004136 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004137 if (!CandidateSet.isNewCandidate(MethodTmpl))
4138 return;
4139
Douglas Gregor6b906862009-08-21 00:16:32 +00004140 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00004141 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00004142 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00004143 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00004144 // candidate functions in the usual way.113) A given name can refer to one
4145 // or more function templates and also to a set of overloaded non-template
4146 // functions. In such a case, the candidate functions generated from each
4147 // function template are combined with the set of non-template candidate
4148 // functions.
John McCall5769d612010-02-08 23:07:23 +00004149 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00004150 FunctionDecl *Specialization = 0;
4151 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004152 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00004153 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00004154 CandidateSet.push_back(OverloadCandidate());
4155 OverloadCandidate &Candidate = CandidateSet.back();
4156 Candidate.FoundDecl = FoundDecl;
4157 Candidate.Function = MethodTmpl->getTemplatedDecl();
4158 Candidate.Viable = false;
4159 Candidate.FailureKind = ovl_fail_bad_deduction;
4160 Candidate.IsSurrogate = false;
4161 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004162 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004163 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004164 Info);
4165 return;
4166 }
Mike Stump1eb44332009-09-09 15:08:12 +00004167
Douglas Gregor6b906862009-08-21 00:16:32 +00004168 // Add the function template specialization produced by template argument
4169 // deduction as a candidate.
4170 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00004171 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00004172 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00004173 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004174 ActingContext, ObjectType, ObjectClassification,
4175 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00004176}
4177
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004178/// \brief Add a C++ function template specialization as a candidate
4179/// in the candidate set, using template argument deduction to produce
4180/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004181void
Douglas Gregore53060f2009-06-25 22:08:12 +00004182Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00004183 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00004184 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00004185 Expr **Args, unsigned NumArgs,
4186 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004187 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004188 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4189 return;
4190
Douglas Gregore53060f2009-06-25 22:08:12 +00004191 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00004192 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00004193 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00004194 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00004195 // candidate functions in the usual way.113) A given name can refer to one
4196 // or more function templates and also to a set of overloaded non-template
4197 // functions. In such a case, the candidate functions generated from each
4198 // function template are combined with the set of non-template candidate
4199 // functions.
John McCall5769d612010-02-08 23:07:23 +00004200 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00004201 FunctionDecl *Specialization = 0;
4202 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004203 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004204 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00004205 CandidateSet.push_back(OverloadCandidate());
4206 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004207 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00004208 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4209 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004210 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00004211 Candidate.IsSurrogate = false;
4212 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004213 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004214 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004215 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00004216 return;
4217 }
Mike Stump1eb44332009-09-09 15:08:12 +00004218
Douglas Gregore53060f2009-06-25 22:08:12 +00004219 // Add the function template specialization produced by template argument
4220 // deduction as a candidate.
4221 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00004222 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004223 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00004224}
Mike Stump1eb44332009-09-09 15:08:12 +00004225
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004226/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00004227/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004228/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00004229/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004230/// (which may or may not be the same type as the type that the
4231/// conversion function produces).
4232void
4233Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00004234 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004235 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004236 Expr *From, QualType ToType,
4237 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004238 assert(!Conversion->getDescribedFunctionTemplate() &&
4239 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004240 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00004241 if (!CandidateSet.isNewCandidate(Conversion))
4242 return;
4243
Douglas Gregor7edfb692009-11-23 12:27:39 +00004244 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004245 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004246
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004247 // Add this candidate
4248 CandidateSet.push_back(OverloadCandidate());
4249 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004250 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004251 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004252 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004253 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004254 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004255 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004256 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004257 Candidate.Viable = true;
4258 Candidate.Conversions.resize(1);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004259 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004260
Douglas Gregorbca39322010-08-19 15:37:02 +00004261 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004262 // For conversion functions, the function is considered to be a member of
4263 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00004264 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004265 //
4266 // Determine the implicit conversion sequence for the implicit
4267 // object parameter.
4268 QualType ImplicitParamType = From->getType();
4269 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4270 ImplicitParamType = FromPtrType->getPointeeType();
4271 CXXRecordDecl *ConversionContext
4272 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004273
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004274 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004275 = TryObjectArgumentInitialization(*this, From->getType(),
4276 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004277 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004278
John McCall1d318332010-01-12 00:44:57 +00004279 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004280 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004281 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004282 return;
4283 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004284
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004285 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00004286 // derived to base as such conversions are given Conversion Rank. They only
4287 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4288 QualType FromCanon
4289 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4290 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4291 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4292 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00004293 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00004294 return;
4295 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004296
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004297 // To determine what the conversion from the result of calling the
4298 // conversion function to the type we're eventually trying to
4299 // convert to (ToType), we need to synthesize a call to the
4300 // conversion function and attempt copy initialization from it. This
4301 // makes sure that we get the right semantics with respect to
4302 // lvalues/rvalues and the type. Fortunately, we can allocate this
4303 // call on the stack and we don't need its arguments to be
4304 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00004305 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004306 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00004307 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4308 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00004309 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00004310 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00004311
Douglas Gregor7d14d382010-11-13 19:36:57 +00004312 QualType CallResultType
4313 = Conversion->getConversionType().getNonLValueExprType(Context);
4314 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4315 Candidate.Viable = false;
4316 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4317 return;
4318 }
4319
John McCallf89e55a2010-11-18 06:31:45 +00004320 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4321
Mike Stump1eb44332009-09-09 15:08:12 +00004322 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00004323 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4324 // allocator).
John McCallf89e55a2010-11-18 06:31:45 +00004325 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00004326 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00004327 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00004328 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004329 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004330 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004331
John McCall1d318332010-01-12 00:44:57 +00004332 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004333 case ImplicitConversionSequence::StandardConversion:
4334 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004335
Douglas Gregorc520c842010-04-12 23:42:09 +00004336 // C++ [over.ics.user]p3:
4337 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004338 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00004339 // shall have exact match rank.
4340 if (Conversion->getPrimaryTemplate() &&
4341 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4342 Candidate.Viable = false;
4343 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4344 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004345
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004346 // C++0x [dcl.init.ref]p5:
4347 // In the second case, if the reference is an rvalue reference and
4348 // the second standard conversion sequence of the user-defined
4349 // conversion sequence includes an lvalue-to-rvalue conversion, the
4350 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004351 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004352 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4353 Candidate.Viable = false;
4354 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4355 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004356 break;
4357
4358 case ImplicitConversionSequence::BadConversion:
4359 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00004360 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004361 break;
4362
4363 default:
Mike Stump1eb44332009-09-09 15:08:12 +00004364 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004365 "Can only end up with a standard conversion sequence or failure");
4366 }
4367}
4368
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004369/// \brief Adds a conversion function template specialization
4370/// candidate to the overload set, using template argument deduction
4371/// to deduce the template arguments of the conversion function
4372/// template from the type that we are converting to (C++
4373/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00004374void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004375Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00004376 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004377 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004378 Expr *From, QualType ToType,
4379 OverloadCandidateSet &CandidateSet) {
4380 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4381 "Only conversion function templates permitted here");
4382
Douglas Gregor3f396022009-09-28 04:47:19 +00004383 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4384 return;
4385
John McCall5769d612010-02-08 23:07:23 +00004386 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004387 CXXConversionDecl *Specialization = 0;
4388 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00004389 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004390 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00004391 CandidateSet.push_back(OverloadCandidate());
4392 OverloadCandidate &Candidate = CandidateSet.back();
4393 Candidate.FoundDecl = FoundDecl;
4394 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4395 Candidate.Viable = false;
4396 Candidate.FailureKind = ovl_fail_bad_deduction;
4397 Candidate.IsSurrogate = false;
4398 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004399 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004400 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004401 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004402 return;
4403 }
Mike Stump1eb44332009-09-09 15:08:12 +00004404
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004405 // Add the conversion function template specialization produced by
4406 // template argument deduction as a candidate.
4407 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00004408 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00004409 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004410}
4411
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004412/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4413/// converts the given @c Object to a function pointer via the
4414/// conversion function @c Conversion, and then attempts to call it
4415/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4416/// the type of function that we'll eventually be calling.
4417void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00004418 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004419 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00004420 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004421 Expr *Object,
John McCall701c89e2009-12-03 04:06:58 +00004422 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004423 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004424 if (!CandidateSet.isNewCandidate(Conversion))
4425 return;
4426
Douglas Gregor7edfb692009-11-23 12:27:39 +00004427 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004428 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004429
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004430 CandidateSet.push_back(OverloadCandidate());
4431 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004432 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004433 Candidate.Function = 0;
4434 Candidate.Surrogate = Conversion;
4435 Candidate.Viable = true;
4436 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004437 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004438 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004439 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004440
4441 // Determine the implicit conversion sequence for the implicit
4442 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004443 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004444 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004445 Object->Classify(Context),
4446 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00004447 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004448 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004449 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00004450 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004451 return;
4452 }
4453
4454 // The first conversion is actually a user-defined conversion whose
4455 // first conversion is ObjectInit's standard conversion (which is
4456 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00004457 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004458 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004459 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004460 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004461 Candidate.Conversions[0].UserDefined.FoundConversionFunction
Douglas Gregor83eecbe2011-01-20 01:32:05 +00004462 = FoundDecl.getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004463 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004464 = Candidate.Conversions[0].UserDefined.Before;
4465 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4466
Mike Stump1eb44332009-09-09 15:08:12 +00004467 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004468 unsigned NumArgsInProto = Proto->getNumArgs();
4469
4470 // (C++ 13.3.2p2): A candidate function having fewer than m
4471 // parameters is viable only if it has an ellipsis in its parameter
4472 // list (8.3.5).
4473 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4474 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004475 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004476 return;
4477 }
4478
4479 // Function types don't have any default arguments, so just check if
4480 // we have enough arguments.
4481 if (NumArgs < NumArgsInProto) {
4482 // Not enough arguments.
4483 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004484 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004485 return;
4486 }
4487
4488 // Determine the implicit conversion sequences for each of the
4489 // arguments.
4490 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4491 if (ArgIdx < NumArgsInProto) {
4492 // (C++ 13.3.2p3): for F to be a viable function, there shall
4493 // exist for each argument an implicit conversion sequence
4494 // (13.3.3.1) that converts that argument to the corresponding
4495 // parameter of F.
4496 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004497 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004498 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004499 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004500 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00004501 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004502 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004503 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004504 break;
4505 }
4506 } else {
4507 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4508 // argument for which there is no corresponding parameter is
4509 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004510 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004511 }
4512 }
4513}
4514
Douglas Gregor063daf62009-03-13 18:40:31 +00004515/// \brief Add overload candidates for overloaded operators that are
4516/// member functions.
4517///
4518/// Add the overloaded operator candidates that are member functions
4519/// for the operator Op that was used in an operator expression such
4520/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4521/// CandidateSet will store the added overload candidates. (C++
4522/// [over.match.oper]).
4523void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4524 SourceLocation OpLoc,
4525 Expr **Args, unsigned NumArgs,
4526 OverloadCandidateSet& CandidateSet,
4527 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004528 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4529
4530 // C++ [over.match.oper]p3:
4531 // For a unary operator @ with an operand of a type whose
4532 // cv-unqualified version is T1, and for a binary operator @ with
4533 // a left operand of a type whose cv-unqualified version is T1 and
4534 // a right operand of a type whose cv-unqualified version is T2,
4535 // three sets of candidate functions, designated member
4536 // candidates, non-member candidates and built-in candidates, are
4537 // constructed as follows:
4538 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00004539
4540 // -- If T1 is a class type, the set of member candidates is the
4541 // result of the qualified lookup of T1::operator@
4542 // (13.3.1.1.1); otherwise, the set of member candidates is
4543 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00004544 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004545 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004546 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004547 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004548
John McCalla24dc2e2009-11-17 02:14:36 +00004549 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4550 LookupQualifiedName(Operators, T1Rec->getDecl());
4551 Operators.suppressDiagnostics();
4552
Mike Stump1eb44332009-09-09 15:08:12 +00004553 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004554 OperEnd = Operators.end();
4555 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00004556 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00004557 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004558 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004559 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00004560 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00004561 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004562}
4563
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004564/// AddBuiltinCandidate - Add a candidate for a built-in
4565/// operator. ResultTy and ParamTys are the result and parameter types
4566/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004567/// arguments being passed to the candidate. IsAssignmentOperator
4568/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004569/// operator. NumContextualBoolArguments is the number of arguments
4570/// (at the beginning of the argument list) that will be contextually
4571/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00004572void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004573 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004574 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004575 bool IsAssignmentOperator,
4576 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00004577 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004578 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004579
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004580 // Add this candidate
4581 CandidateSet.push_back(OverloadCandidate());
4582 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004583 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004584 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004585 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004586 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004587 Candidate.BuiltinTypes.ResultTy = ResultTy;
4588 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4589 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4590
4591 // Determine the implicit conversion sequences for each of the
4592 // arguments.
4593 Candidate.Viable = true;
4594 Candidate.Conversions.resize(NumArgs);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004595 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004596 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004597 // C++ [over.match.oper]p4:
4598 // For the built-in assignment operators, conversions of the
4599 // left operand are restricted as follows:
4600 // -- no temporaries are introduced to hold the left operand, and
4601 // -- no user-defined conversions are applied to the left
4602 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00004603 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004604 //
4605 // We block these conversions by turning off user-defined
4606 // conversions, since that is the only way that initialization of
4607 // a reference to a non-class type can occur from something that
4608 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004609 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004610 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004611 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00004612 Candidate.Conversions[ArgIdx]
4613 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004614 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004615 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004616 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004617 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004618 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004619 }
John McCall1d318332010-01-12 00:44:57 +00004620 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004621 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004622 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004623 break;
4624 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004625 }
4626}
4627
4628/// BuiltinCandidateTypeSet - A set of types that will be used for the
4629/// candidate operator functions for built-in operators (C++
4630/// [over.built]). The types are separated into pointer types and
4631/// enumeration types.
4632class BuiltinCandidateTypeSet {
4633 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004634 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004635
4636 /// PointerTypes - The set of pointer types that will be used in the
4637 /// built-in candidates.
4638 TypeSet PointerTypes;
4639
Sebastian Redl78eb8742009-04-19 21:53:20 +00004640 /// MemberPointerTypes - The set of member pointer types that will be
4641 /// used in the built-in candidates.
4642 TypeSet MemberPointerTypes;
4643
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004644 /// EnumerationTypes - The set of enumeration types that will be
4645 /// used in the built-in candidates.
4646 TypeSet EnumerationTypes;
4647
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004648 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00004649 /// candidates.
4650 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00004651
4652 /// \brief A flag indicating non-record types are viable candidates
4653 bool HasNonRecordTypes;
4654
4655 /// \brief A flag indicating whether either arithmetic or enumeration types
4656 /// were present in the candidate set.
4657 bool HasArithmeticOrEnumeralTypes;
4658
Douglas Gregor5842ba92009-08-24 15:23:48 +00004659 /// Sema - The semantic analysis instance where we are building the
4660 /// candidate type set.
4661 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004662
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004663 /// Context - The AST context in which we will build the type sets.
4664 ASTContext &Context;
4665
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004666 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4667 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00004668 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004669
4670public:
4671 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004672 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004673
Mike Stump1eb44332009-09-09 15:08:12 +00004674 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00004675 : HasNonRecordTypes(false),
4676 HasArithmeticOrEnumeralTypes(false),
4677 SemaRef(SemaRef),
4678 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004679
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004680 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004681 SourceLocation Loc,
4682 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004683 bool AllowExplicitConversions,
4684 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004685
4686 /// pointer_begin - First pointer type found;
4687 iterator pointer_begin() { return PointerTypes.begin(); }
4688
Sebastian Redl78eb8742009-04-19 21:53:20 +00004689 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004690 iterator pointer_end() { return PointerTypes.end(); }
4691
Sebastian Redl78eb8742009-04-19 21:53:20 +00004692 /// member_pointer_begin - First member pointer type found;
4693 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4694
4695 /// member_pointer_end - Past the last member pointer type found;
4696 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4697
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004698 /// enumeration_begin - First enumeration type found;
4699 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4700
Sebastian Redl78eb8742009-04-19 21:53:20 +00004701 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004702 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004703
Douglas Gregor26bcf672010-05-19 03:21:00 +00004704 iterator vector_begin() { return VectorTypes.begin(); }
4705 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00004706
4707 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4708 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004709};
4710
Sebastian Redl78eb8742009-04-19 21:53:20 +00004711/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004712/// the set of pointer types along with any more-qualified variants of
4713/// that type. For example, if @p Ty is "int const *", this routine
4714/// will add "int const *", "int const volatile *", "int const
4715/// restrict *", and "int const volatile restrict *" to the set of
4716/// pointer types. Returns true if the add of @p Ty itself succeeded,
4717/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004718///
4719/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004720bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00004721BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4722 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00004723
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004724 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004725 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004726 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004727
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004728 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00004729 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004730 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004731 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004732 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004733 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004734 buildObjCPtr = true;
4735 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004736 else
4737 assert(false && "type was not a pointer type!");
4738 }
4739 else
4740 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004741
Sebastian Redla9efada2009-11-18 20:39:26 +00004742 // Don't add qualified variants of arrays. For one, they're not allowed
4743 // (the qualifier would sink to the element type), and for another, the
4744 // only overload situation where it matters is subscript or pointer +- int,
4745 // and those shouldn't have qualifier variants anyway.
4746 if (PointeeTy->isArrayType())
4747 return true;
John McCall0953e762009-09-24 19:53:00 +00004748 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00004749 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00004750 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004751 bool hasVolatile = VisibleQuals.hasVolatile();
4752 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004753
John McCall0953e762009-09-24 19:53:00 +00004754 // Iterate through all strict supersets of BaseCVR.
4755 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4756 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004757 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4758 // in the types.
4759 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4760 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00004761 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004762 if (!buildObjCPtr)
4763 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4764 else
4765 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004766 }
4767
4768 return true;
4769}
4770
Sebastian Redl78eb8742009-04-19 21:53:20 +00004771/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4772/// to the set of pointer types along with any more-qualified variants of
4773/// that type. For example, if @p Ty is "int const *", this routine
4774/// will add "int const *", "int const volatile *", "int const
4775/// restrict *", and "int const volatile restrict *" to the set of
4776/// pointer types. Returns true if the add of @p Ty itself succeeded,
4777/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004778///
4779/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004780bool
4781BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4782 QualType Ty) {
4783 // Insert this type.
4784 if (!MemberPointerTypes.insert(Ty))
4785 return false;
4786
John McCall0953e762009-09-24 19:53:00 +00004787 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4788 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00004789
John McCall0953e762009-09-24 19:53:00 +00004790 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004791 // Don't add qualified variants of arrays. For one, they're not allowed
4792 // (the qualifier would sink to the element type), and for another, the
4793 // only overload situation where it matters is subscript or pointer +- int,
4794 // and those shouldn't have qualifier variants anyway.
4795 if (PointeeTy->isArrayType())
4796 return true;
John McCall0953e762009-09-24 19:53:00 +00004797 const Type *ClassTy = PointerTy->getClass();
4798
4799 // Iterate through all strict supersets of the pointee type's CVR
4800 // qualifiers.
4801 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4802 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4803 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004804
John McCall0953e762009-09-24 19:53:00 +00004805 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00004806 MemberPointerTypes.insert(
4807 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00004808 }
4809
4810 return true;
4811}
4812
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004813/// AddTypesConvertedFrom - Add each of the types to which the type @p
4814/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00004815/// primarily interested in pointer types and enumeration types. We also
4816/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004817/// AllowUserConversions is true if we should look at the conversion
4818/// functions of a class type, and AllowExplicitConversions if we
4819/// should also include the explicit conversion functions of a class
4820/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004821void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004822BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004823 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004824 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004825 bool AllowExplicitConversions,
4826 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004827 // Only deal with canonical types.
4828 Ty = Context.getCanonicalType(Ty);
4829
4830 // Look through reference types; they aren't part of the type of an
4831 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004832 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004833 Ty = RefTy->getPointeeType();
4834
John McCall3b657512011-01-19 10:06:00 +00004835 // If we're dealing with an array type, decay to the pointer.
4836 if (Ty->isArrayType())
4837 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4838
4839 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004840 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004841
Chandler Carruth6a577462010-12-13 01:44:01 +00004842 // Flag if we ever add a non-record type.
4843 const RecordType *TyRec = Ty->getAs<RecordType>();
4844 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4845
Chandler Carruth6a577462010-12-13 01:44:01 +00004846 // Flag if we encounter an arithmetic type.
4847 HasArithmeticOrEnumeralTypes =
4848 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4849
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004850 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4851 PointerTypes.insert(Ty);
4852 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004853 // Insert our type, and its more-qualified variants, into the set
4854 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004855 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004856 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00004857 } else if (Ty->isMemberPointerType()) {
4858 // Member pointers are far easier, since the pointee can't be converted.
4859 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4860 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004861 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00004862 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00004863 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004864 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00004865 // We treat vector types as arithmetic types in many contexts as an
4866 // extension.
4867 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00004868 VectorTypes.insert(Ty);
Chandler Carruth6a577462010-12-13 01:44:01 +00004869 } else if (AllowUserConversions && TyRec) {
4870 // No conversion functions in incomplete types.
4871 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4872 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004873
Chandler Carruth6a577462010-12-13 01:44:01 +00004874 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4875 const UnresolvedSetImpl *Conversions
4876 = ClassDecl->getVisibleConversionFunctions();
4877 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4878 E = Conversions->end(); I != E; ++I) {
4879 NamedDecl *D = I.getDecl();
4880 if (isa<UsingShadowDecl>(D))
4881 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004882
Chandler Carruth6a577462010-12-13 01:44:01 +00004883 // Skip conversion function templates; they don't tell us anything
4884 // about which builtin types we can convert to.
4885 if (isa<FunctionTemplateDecl>(D))
4886 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004887
Chandler Carruth6a577462010-12-13 01:44:01 +00004888 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4889 if (AllowExplicitConversions || !Conv->isExplicit()) {
4890 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4891 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004892 }
4893 }
4894 }
4895}
4896
Douglas Gregor19b7b152009-08-24 13:43:27 +00004897/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4898/// the volatile- and non-volatile-qualified assignment operators for the
4899/// given type to the candidate set.
4900static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4901 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004902 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004903 unsigned NumArgs,
4904 OverloadCandidateSet &CandidateSet) {
4905 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004906
Douglas Gregor19b7b152009-08-24 13:43:27 +00004907 // T& operator=(T&, T)
4908 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4909 ParamTypes[1] = T;
4910 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4911 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004912
Douglas Gregor19b7b152009-08-24 13:43:27 +00004913 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4914 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004915 ParamTypes[0]
4916 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004917 ParamTypes[1] = T;
4918 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004919 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004920 }
4921}
Mike Stump1eb44332009-09-09 15:08:12 +00004922
Sebastian Redl9994a342009-10-25 17:03:50 +00004923/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4924/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004925static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4926 Qualifiers VRQuals;
4927 const RecordType *TyRec;
4928 if (const MemberPointerType *RHSMPType =
4929 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004930 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004931 else
4932 TyRec = ArgExpr->getType()->getAs<RecordType>();
4933 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004934 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004935 VRQuals.addVolatile();
4936 VRQuals.addRestrict();
4937 return VRQuals;
4938 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004939
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004940 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004941 if (!ClassDecl->hasDefinition())
4942 return VRQuals;
4943
John McCalleec51cf2010-01-20 00:46:10 +00004944 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004945 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004946
John McCalleec51cf2010-01-20 00:46:10 +00004947 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004948 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004949 NamedDecl *D = I.getDecl();
4950 if (isa<UsingShadowDecl>(D))
4951 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4952 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004953 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4954 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4955 CanTy = ResTypeRef->getPointeeType();
4956 // Need to go down the pointer/mempointer chain and add qualifiers
4957 // as see them.
4958 bool done = false;
4959 while (!done) {
4960 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4961 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004962 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004963 CanTy->getAs<MemberPointerType>())
4964 CanTy = ResTypeMPtr->getPointeeType();
4965 else
4966 done = true;
4967 if (CanTy.isVolatileQualified())
4968 VRQuals.addVolatile();
4969 if (CanTy.isRestrictQualified())
4970 VRQuals.addRestrict();
4971 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4972 return VRQuals;
4973 }
4974 }
4975 }
4976 return VRQuals;
4977}
John McCall00071ec2010-11-13 05:51:15 +00004978
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004979namespace {
John McCall00071ec2010-11-13 05:51:15 +00004980
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004981/// \brief Helper class to manage the addition of builtin operator overload
4982/// candidates. It provides shared state and utility methods used throughout
4983/// the process, as well as a helper method to add each group of builtin
4984/// operator overloads from the standard to a candidate set.
4985class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00004986 // Common instance state available to all overload candidate addition methods.
4987 Sema &S;
4988 Expr **Args;
4989 unsigned NumArgs;
4990 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00004991 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruth6d695582010-12-12 10:35:00 +00004992 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4993 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004994
Chandler Carruth6d695582010-12-12 10:35:00 +00004995 // Define some constants used to index and iterate over the arithemetic types
4996 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00004997 // The "promoted arithmetic types" are the arithmetic
4998 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00004999 static const unsigned FirstIntegralType = 3;
5000 static const unsigned LastIntegralType = 18;
5001 static const unsigned FirstPromotedIntegralType = 3,
5002 LastPromotedIntegralType = 9;
5003 static const unsigned FirstPromotedArithmeticType = 0,
5004 LastPromotedArithmeticType = 9;
5005 static const unsigned NumArithmeticTypes = 18;
5006
Chandler Carruth6d695582010-12-12 10:35:00 +00005007 /// \brief Get the canonical type for a given arithmetic type index.
5008 CanQualType getArithmeticType(unsigned index) {
5009 assert(index < NumArithmeticTypes);
5010 static CanQualType ASTContext::* const
5011 ArithmeticTypes[NumArithmeticTypes] = {
5012 // Start of promoted types.
5013 &ASTContext::FloatTy,
5014 &ASTContext::DoubleTy,
5015 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00005016
Chandler Carruth6d695582010-12-12 10:35:00 +00005017 // Start of integral types.
5018 &ASTContext::IntTy,
5019 &ASTContext::LongTy,
5020 &ASTContext::LongLongTy,
5021 &ASTContext::UnsignedIntTy,
5022 &ASTContext::UnsignedLongTy,
5023 &ASTContext::UnsignedLongLongTy,
5024 // End of promoted types.
5025
5026 &ASTContext::BoolTy,
5027 &ASTContext::CharTy,
5028 &ASTContext::WCharTy,
5029 &ASTContext::Char16Ty,
5030 &ASTContext::Char32Ty,
5031 &ASTContext::SignedCharTy,
5032 &ASTContext::ShortTy,
5033 &ASTContext::UnsignedCharTy,
5034 &ASTContext::UnsignedShortTy,
5035 // End of integral types.
5036 // FIXME: What about complex?
5037 };
5038 return S.Context.*ArithmeticTypes[index];
5039 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005040
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005041 /// \brief Gets the canonical type resulting from the usual arithemetic
5042 /// converions for the given arithmetic types.
5043 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5044 // Accelerator table for performing the usual arithmetic conversions.
5045 // The rules are basically:
5046 // - if either is floating-point, use the wider floating-point
5047 // - if same signedness, use the higher rank
5048 // - if same size, use unsigned of the higher rank
5049 // - use the larger type
5050 // These rules, together with the axiom that higher ranks are
5051 // never smaller, are sufficient to precompute all of these results
5052 // *except* when dealing with signed types of higher rank.
5053 // (we could precompute SLL x UI for all known platforms, but it's
5054 // better not to make any assumptions).
5055 enum PromotedType {
5056 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5057 };
5058 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5059 [LastPromotedArithmeticType] = {
5060 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5061 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5062 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5063 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5064 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5065 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5066 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5067 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5068 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5069 };
5070
5071 assert(L < LastPromotedArithmeticType);
5072 assert(R < LastPromotedArithmeticType);
5073 int Idx = ConversionsTable[L][R];
5074
5075 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00005076 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005077
5078 // Slow path: we need to compare widths.
5079 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00005080 CanQualType LT = getArithmeticType(L),
5081 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005082 unsigned LW = S.Context.getIntWidth(LT),
5083 RW = S.Context.getIntWidth(RT);
5084
5085 // If they're different widths, use the signed type.
5086 if (LW > RW) return LT;
5087 else if (LW < RW) return RT;
5088
5089 // Otherwise, use the unsigned type of the signed type's rank.
5090 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5091 assert(L == SLL || R == SLL);
5092 return S.Context.UnsignedLongLongTy;
5093 }
5094
Chandler Carruth3c69dc42010-12-12 09:22:45 +00005095 /// \brief Helper method to factor out the common pattern of adding overloads
5096 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005097 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5098 bool HasVolatile) {
5099 QualType ParamTypes[2] = {
5100 S.Context.getLValueReferenceType(CandidateTy),
5101 S.Context.IntTy
5102 };
5103
5104 // Non-volatile version.
5105 if (NumArgs == 1)
5106 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5107 else
5108 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5109
5110 // Use a heuristic to reduce number of builtin candidates in the set:
5111 // add volatile version only if there are conversions to a volatile type.
5112 if (HasVolatile) {
5113 ParamTypes[0] =
5114 S.Context.getLValueReferenceType(
5115 S.Context.getVolatileType(CandidateTy));
5116 if (NumArgs == 1)
5117 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5118 else
5119 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5120 }
5121 }
5122
5123public:
5124 BuiltinOperatorOverloadBuilder(
5125 Sema &S, Expr **Args, unsigned NumArgs,
5126 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00005127 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005128 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
5129 OverloadCandidateSet &CandidateSet)
5130 : S(S), Args(Args), NumArgs(NumArgs),
5131 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00005132 HasArithmeticOrEnumeralCandidateType(
5133 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005134 CandidateTypes(CandidateTypes),
5135 CandidateSet(CandidateSet) {
5136 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00005137 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005138 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005139 assert(getArithmeticType(LastPromotedIntegralType - 1)
5140 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005141 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005142 assert(getArithmeticType(FirstPromotedArithmeticType)
5143 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005144 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005145 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5146 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005147 "Invalid last promoted arithmetic type");
5148 }
5149
5150 // C++ [over.built]p3:
5151 //
5152 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5153 // is either volatile or empty, there exist candidate operator
5154 // functions of the form
5155 //
5156 // VQ T& operator++(VQ T&);
5157 // T operator++(VQ T&, int);
5158 //
5159 // C++ [over.built]p4:
5160 //
5161 // For every pair (T, VQ), where T is an arithmetic type other
5162 // than bool, and VQ is either volatile or empty, there exist
5163 // candidate operator functions of the form
5164 //
5165 // VQ T& operator--(VQ T&);
5166 // T operator--(VQ T&, int);
5167 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005168 if (!HasArithmeticOrEnumeralCandidateType)
5169 return;
5170
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005171 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5172 Arith < NumArithmeticTypes; ++Arith) {
5173 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00005174 getArithmeticType(Arith),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005175 VisibleTypeConversionsQuals.hasVolatile());
5176 }
5177 }
5178
5179 // C++ [over.built]p5:
5180 //
5181 // For every pair (T, VQ), where T is a cv-qualified or
5182 // cv-unqualified object type, and VQ is either volatile or
5183 // empty, there exist candidate operator functions of the form
5184 //
5185 // T*VQ& operator++(T*VQ&);
5186 // T*VQ& operator--(T*VQ&);
5187 // T* operator++(T*VQ&, int);
5188 // T* operator--(T*VQ&, int);
5189 void addPlusPlusMinusMinusPointerOverloads() {
5190 for (BuiltinCandidateTypeSet::iterator
5191 Ptr = CandidateTypes[0].pointer_begin(),
5192 PtrEnd = CandidateTypes[0].pointer_end();
5193 Ptr != PtrEnd; ++Ptr) {
5194 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005195 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005196 continue;
5197
5198 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5199 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5200 VisibleTypeConversionsQuals.hasVolatile()));
5201 }
5202 }
5203
5204 // C++ [over.built]p6:
5205 // For every cv-qualified or cv-unqualified object type T, there
5206 // exist candidate operator functions of the form
5207 //
5208 // T& operator*(T*);
5209 //
5210 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005211 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005212 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005213 // T& operator*(T*);
5214 void addUnaryStarPointerOverloads() {
5215 for (BuiltinCandidateTypeSet::iterator
5216 Ptr = CandidateTypes[0].pointer_begin(),
5217 PtrEnd = CandidateTypes[0].pointer_end();
5218 Ptr != PtrEnd; ++Ptr) {
5219 QualType ParamTy = *Ptr;
5220 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005221 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5222 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005223
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005224 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5225 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5226 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005227
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005228 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5229 &ParamTy, Args, 1, CandidateSet);
5230 }
5231 }
5232
5233 // C++ [over.built]p9:
5234 // For every promoted arithmetic type T, there exist candidate
5235 // operator functions of the form
5236 //
5237 // T operator+(T);
5238 // T operator-(T);
5239 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00005240 if (!HasArithmeticOrEnumeralCandidateType)
5241 return;
5242
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005243 for (unsigned Arith = FirstPromotedArithmeticType;
5244 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005245 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005246 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5247 }
5248
5249 // Extension: We also add these operators for vector types.
5250 for (BuiltinCandidateTypeSet::iterator
5251 Vec = CandidateTypes[0].vector_begin(),
5252 VecEnd = CandidateTypes[0].vector_end();
5253 Vec != VecEnd; ++Vec) {
5254 QualType VecTy = *Vec;
5255 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5256 }
5257 }
5258
5259 // C++ [over.built]p8:
5260 // For every type T, there exist candidate operator functions of
5261 // the form
5262 //
5263 // T* operator+(T*);
5264 void addUnaryPlusPointerOverloads() {
5265 for (BuiltinCandidateTypeSet::iterator
5266 Ptr = CandidateTypes[0].pointer_begin(),
5267 PtrEnd = CandidateTypes[0].pointer_end();
5268 Ptr != PtrEnd; ++Ptr) {
5269 QualType ParamTy = *Ptr;
5270 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5271 }
5272 }
5273
5274 // C++ [over.built]p10:
5275 // For every promoted integral type T, there exist candidate
5276 // operator functions of the form
5277 //
5278 // T operator~(T);
5279 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00005280 if (!HasArithmeticOrEnumeralCandidateType)
5281 return;
5282
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005283 for (unsigned Int = FirstPromotedIntegralType;
5284 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005285 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005286 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5287 }
5288
5289 // Extension: We also add this operator for vector types.
5290 for (BuiltinCandidateTypeSet::iterator
5291 Vec = CandidateTypes[0].vector_begin(),
5292 VecEnd = CandidateTypes[0].vector_end();
5293 Vec != VecEnd; ++Vec) {
5294 QualType VecTy = *Vec;
5295 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5296 }
5297 }
5298
5299 // C++ [over.match.oper]p16:
5300 // For every pointer to member type T, there exist candidate operator
5301 // functions of the form
5302 //
5303 // bool operator==(T,T);
5304 // bool operator!=(T,T);
5305 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5306 /// Set of (canonical) types that we've already handled.
5307 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5308
5309 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5310 for (BuiltinCandidateTypeSet::iterator
5311 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5312 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5313 MemPtr != MemPtrEnd;
5314 ++MemPtr) {
5315 // Don't add the same builtin candidate twice.
5316 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5317 continue;
5318
5319 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5320 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5321 CandidateSet);
5322 }
5323 }
5324 }
5325
5326 // C++ [over.built]p15:
5327 //
5328 // For every pointer or enumeration type T, there exist
5329 // candidate operator functions of the form
5330 //
5331 // bool operator<(T, T);
5332 // bool operator>(T, T);
5333 // bool operator<=(T, T);
5334 // bool operator>=(T, T);
5335 // bool operator==(T, T);
5336 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005337 void addRelationalPointerOrEnumeralOverloads() {
5338 // C++ [over.built]p1:
5339 // If there is a user-written candidate with the same name and parameter
5340 // types as a built-in candidate operator function, the built-in operator
5341 // function is hidden and is not included in the set of candidate
5342 // functions.
5343 //
5344 // The text is actually in a note, but if we don't implement it then we end
5345 // up with ambiguities when the user provides an overloaded operator for
5346 // an enumeration type. Note that only enumeration types have this problem,
5347 // so we track which enumeration types we've seen operators for. Also, the
5348 // only other overloaded operator with enumeration argumenst, operator=,
5349 // cannot be overloaded for enumeration types, so this is the only place
5350 // where we must suppress candidates like this.
5351 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5352 UserDefinedBinaryOperators;
5353
5354 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5355 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5356 CandidateTypes[ArgIdx].enumeration_end()) {
5357 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5358 CEnd = CandidateSet.end();
5359 C != CEnd; ++C) {
5360 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5361 continue;
5362
5363 QualType FirstParamType =
5364 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5365 QualType SecondParamType =
5366 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5367
5368 // Skip if either parameter isn't of enumeral type.
5369 if (!FirstParamType->isEnumeralType() ||
5370 !SecondParamType->isEnumeralType())
5371 continue;
5372
5373 // Add this operator to the set of known user-defined operators.
5374 UserDefinedBinaryOperators.insert(
5375 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5376 S.Context.getCanonicalType(SecondParamType)));
5377 }
5378 }
5379 }
5380
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005381 /// Set of (canonical) types that we've already handled.
5382 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5383
5384 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5385 for (BuiltinCandidateTypeSet::iterator
5386 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5387 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5388 Ptr != PtrEnd; ++Ptr) {
5389 // Don't add the same builtin candidate twice.
5390 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5391 continue;
5392
5393 QualType ParamTypes[2] = { *Ptr, *Ptr };
5394 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5395 CandidateSet);
5396 }
5397 for (BuiltinCandidateTypeSet::iterator
5398 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5399 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5400 Enum != EnumEnd; ++Enum) {
5401 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5402
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005403 // Don't add the same builtin candidate twice, or if a user defined
5404 // candidate exists.
5405 if (!AddedTypes.insert(CanonType) ||
5406 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5407 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005408 continue;
5409
5410 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005411 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5412 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005413 }
5414 }
5415 }
5416
5417 // C++ [over.built]p13:
5418 //
5419 // For every cv-qualified or cv-unqualified object type T
5420 // there exist candidate operator functions of the form
5421 //
5422 // T* operator+(T*, ptrdiff_t);
5423 // T& operator[](T*, ptrdiff_t); [BELOW]
5424 // T* operator-(T*, ptrdiff_t);
5425 // T* operator+(ptrdiff_t, T*);
5426 // T& operator[](ptrdiff_t, T*); [BELOW]
5427 //
5428 // C++ [over.built]p14:
5429 //
5430 // For every T, where T is a pointer to object type, there
5431 // exist candidate operator functions of the form
5432 //
5433 // ptrdiff_t operator-(T, T);
5434 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5435 /// Set of (canonical) types that we've already handled.
5436 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5437
5438 for (int Arg = 0; Arg < 2; ++Arg) {
5439 QualType AsymetricParamTypes[2] = {
5440 S.Context.getPointerDiffType(),
5441 S.Context.getPointerDiffType(),
5442 };
5443 for (BuiltinCandidateTypeSet::iterator
5444 Ptr = CandidateTypes[Arg].pointer_begin(),
5445 PtrEnd = CandidateTypes[Arg].pointer_end();
5446 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005447 QualType PointeeTy = (*Ptr)->getPointeeType();
5448 if (!PointeeTy->isObjectType())
5449 continue;
5450
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005451 AsymetricParamTypes[Arg] = *Ptr;
5452 if (Arg == 0 || Op == OO_Plus) {
5453 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5454 // T* operator+(ptrdiff_t, T*);
5455 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5456 CandidateSet);
5457 }
5458 if (Op == OO_Minus) {
5459 // ptrdiff_t operator-(T, T);
5460 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5461 continue;
5462
5463 QualType ParamTypes[2] = { *Ptr, *Ptr };
5464 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5465 Args, 2, CandidateSet);
5466 }
5467 }
5468 }
5469 }
5470
5471 // C++ [over.built]p12:
5472 //
5473 // For every pair of promoted arithmetic types L and R, there
5474 // exist candidate operator functions of the form
5475 //
5476 // LR operator*(L, R);
5477 // LR operator/(L, R);
5478 // LR operator+(L, R);
5479 // LR operator-(L, R);
5480 // bool operator<(L, R);
5481 // bool operator>(L, R);
5482 // bool operator<=(L, R);
5483 // bool operator>=(L, R);
5484 // bool operator==(L, R);
5485 // bool operator!=(L, R);
5486 //
5487 // where LR is the result of the usual arithmetic conversions
5488 // between types L and R.
5489 //
5490 // C++ [over.built]p24:
5491 //
5492 // For every pair of promoted arithmetic types L and R, there exist
5493 // candidate operator functions of the form
5494 //
5495 // LR operator?(bool, L, R);
5496 //
5497 // where LR is the result of the usual arithmetic conversions
5498 // between types L and R.
5499 // Our candidates ignore the first parameter.
5500 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005501 if (!HasArithmeticOrEnumeralCandidateType)
5502 return;
5503
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005504 for (unsigned Left = FirstPromotedArithmeticType;
5505 Left < LastPromotedArithmeticType; ++Left) {
5506 for (unsigned Right = FirstPromotedArithmeticType;
5507 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005508 QualType LandR[2] = { getArithmeticType(Left),
5509 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005510 QualType Result =
5511 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005512 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005513 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5514 }
5515 }
5516
5517 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5518 // conditional operator for vector types.
5519 for (BuiltinCandidateTypeSet::iterator
5520 Vec1 = CandidateTypes[0].vector_begin(),
5521 Vec1End = CandidateTypes[0].vector_end();
5522 Vec1 != Vec1End; ++Vec1) {
5523 for (BuiltinCandidateTypeSet::iterator
5524 Vec2 = CandidateTypes[1].vector_begin(),
5525 Vec2End = CandidateTypes[1].vector_end();
5526 Vec2 != Vec2End; ++Vec2) {
5527 QualType LandR[2] = { *Vec1, *Vec2 };
5528 QualType Result = S.Context.BoolTy;
5529 if (!isComparison) {
5530 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5531 Result = *Vec1;
5532 else
5533 Result = *Vec2;
5534 }
5535
5536 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5537 }
5538 }
5539 }
5540
5541 // C++ [over.built]p17:
5542 //
5543 // For every pair of promoted integral types L and R, there
5544 // exist candidate operator functions of the form
5545 //
5546 // LR operator%(L, R);
5547 // LR operator&(L, R);
5548 // LR operator^(L, R);
5549 // LR operator|(L, R);
5550 // L operator<<(L, R);
5551 // L operator>>(L, R);
5552 //
5553 // where LR is the result of the usual arithmetic conversions
5554 // between types L and R.
5555 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005556 if (!HasArithmeticOrEnumeralCandidateType)
5557 return;
5558
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005559 for (unsigned Left = FirstPromotedIntegralType;
5560 Left < LastPromotedIntegralType; ++Left) {
5561 for (unsigned Right = FirstPromotedIntegralType;
5562 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005563 QualType LandR[2] = { getArithmeticType(Left),
5564 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005565 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5566 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005567 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005568 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5569 }
5570 }
5571 }
5572
5573 // C++ [over.built]p20:
5574 //
5575 // For every pair (T, VQ), where T is an enumeration or
5576 // pointer to member type and VQ is either volatile or
5577 // empty, there exist candidate operator functions of the form
5578 //
5579 // VQ T& operator=(VQ T&, T);
5580 void addAssignmentMemberPointerOrEnumeralOverloads() {
5581 /// Set of (canonical) types that we've already handled.
5582 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5583
5584 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5585 for (BuiltinCandidateTypeSet::iterator
5586 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5587 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5588 Enum != EnumEnd; ++Enum) {
5589 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5590 continue;
5591
5592 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5593 CandidateSet);
5594 }
5595
5596 for (BuiltinCandidateTypeSet::iterator
5597 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5598 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5599 MemPtr != MemPtrEnd; ++MemPtr) {
5600 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5601 continue;
5602
5603 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5604 CandidateSet);
5605 }
5606 }
5607 }
5608
5609 // C++ [over.built]p19:
5610 //
5611 // For every pair (T, VQ), where T is any type and VQ is either
5612 // volatile or empty, there exist candidate operator functions
5613 // of the form
5614 //
5615 // T*VQ& operator=(T*VQ&, T*);
5616 //
5617 // C++ [over.built]p21:
5618 //
5619 // For every pair (T, VQ), where T is a cv-qualified or
5620 // cv-unqualified object type and VQ is either volatile or
5621 // empty, there exist candidate operator functions of the form
5622 //
5623 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5624 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5625 void addAssignmentPointerOverloads(bool isEqualOp) {
5626 /// Set of (canonical) types that we've already handled.
5627 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5628
5629 for (BuiltinCandidateTypeSet::iterator
5630 Ptr = CandidateTypes[0].pointer_begin(),
5631 PtrEnd = CandidateTypes[0].pointer_end();
5632 Ptr != PtrEnd; ++Ptr) {
5633 // If this is operator=, keep track of the builtin candidates we added.
5634 if (isEqualOp)
5635 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005636 else if (!(*Ptr)->getPointeeType()->isObjectType())
5637 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005638
5639 // non-volatile version
5640 QualType ParamTypes[2] = {
5641 S.Context.getLValueReferenceType(*Ptr),
5642 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5643 };
5644 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5645 /*IsAssigmentOperator=*/ isEqualOp);
5646
5647 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5648 VisibleTypeConversionsQuals.hasVolatile()) {
5649 // volatile version
5650 ParamTypes[0] =
5651 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5652 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5653 /*IsAssigmentOperator=*/isEqualOp);
5654 }
5655 }
5656
5657 if (isEqualOp) {
5658 for (BuiltinCandidateTypeSet::iterator
5659 Ptr = CandidateTypes[1].pointer_begin(),
5660 PtrEnd = CandidateTypes[1].pointer_end();
5661 Ptr != PtrEnd; ++Ptr) {
5662 // Make sure we don't add the same candidate twice.
5663 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5664 continue;
5665
Chandler Carruth6df868e2010-12-12 08:17:55 +00005666 QualType ParamTypes[2] = {
5667 S.Context.getLValueReferenceType(*Ptr),
5668 *Ptr,
5669 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005670
5671 // non-volatile version
5672 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5673 /*IsAssigmentOperator=*/true);
5674
5675 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5676 VisibleTypeConversionsQuals.hasVolatile()) {
5677 // volatile version
5678 ParamTypes[0] =
5679 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00005680 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5681 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005682 }
5683 }
5684 }
5685 }
5686
5687 // C++ [over.built]p18:
5688 //
5689 // For every triple (L, VQ, R), where L is an arithmetic type,
5690 // VQ is either volatile or empty, and R is a promoted
5691 // arithmetic type, there exist candidate operator functions of
5692 // the form
5693 //
5694 // VQ L& operator=(VQ L&, R);
5695 // VQ L& operator*=(VQ L&, R);
5696 // VQ L& operator/=(VQ L&, R);
5697 // VQ L& operator+=(VQ L&, R);
5698 // VQ L& operator-=(VQ L&, R);
5699 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005700 if (!HasArithmeticOrEnumeralCandidateType)
5701 return;
5702
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005703 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5704 for (unsigned Right = FirstPromotedArithmeticType;
5705 Right < LastPromotedArithmeticType; ++Right) {
5706 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00005707 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005708
5709 // Add this built-in operator as a candidate (VQ is empty).
5710 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00005711 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005712 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5713 /*IsAssigmentOperator=*/isEqualOp);
5714
5715 // Add this built-in operator as a candidate (VQ is 'volatile').
5716 if (VisibleTypeConversionsQuals.hasVolatile()) {
5717 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00005718 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005719 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00005720 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5721 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005722 /*IsAssigmentOperator=*/isEqualOp);
5723 }
5724 }
5725 }
5726
5727 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5728 for (BuiltinCandidateTypeSet::iterator
5729 Vec1 = CandidateTypes[0].vector_begin(),
5730 Vec1End = CandidateTypes[0].vector_end();
5731 Vec1 != Vec1End; ++Vec1) {
5732 for (BuiltinCandidateTypeSet::iterator
5733 Vec2 = CandidateTypes[1].vector_begin(),
5734 Vec2End = CandidateTypes[1].vector_end();
5735 Vec2 != Vec2End; ++Vec2) {
5736 QualType ParamTypes[2];
5737 ParamTypes[1] = *Vec2;
5738 // Add this built-in operator as a candidate (VQ is empty).
5739 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5740 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5741 /*IsAssigmentOperator=*/isEqualOp);
5742
5743 // Add this built-in operator as a candidate (VQ is 'volatile').
5744 if (VisibleTypeConversionsQuals.hasVolatile()) {
5745 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5746 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00005747 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5748 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005749 /*IsAssigmentOperator=*/isEqualOp);
5750 }
5751 }
5752 }
5753 }
5754
5755 // C++ [over.built]p22:
5756 //
5757 // For every triple (L, VQ, R), where L is an integral type, VQ
5758 // is either volatile or empty, and R is a promoted integral
5759 // type, there exist candidate operator functions of the form
5760 //
5761 // VQ L& operator%=(VQ L&, R);
5762 // VQ L& operator<<=(VQ L&, R);
5763 // VQ L& operator>>=(VQ L&, R);
5764 // VQ L& operator&=(VQ L&, R);
5765 // VQ L& operator^=(VQ L&, R);
5766 // VQ L& operator|=(VQ L&, R);
5767 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00005768 if (!HasArithmeticOrEnumeralCandidateType)
5769 return;
5770
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005771 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5772 for (unsigned Right = FirstPromotedIntegralType;
5773 Right < LastPromotedIntegralType; ++Right) {
5774 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00005775 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005776
5777 // Add this built-in operator as a candidate (VQ is empty).
5778 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00005779 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005780 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5781 if (VisibleTypeConversionsQuals.hasVolatile()) {
5782 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00005783 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005784 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5785 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5786 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5787 CandidateSet);
5788 }
5789 }
5790 }
5791 }
5792
5793 // C++ [over.operator]p23:
5794 //
5795 // There also exist candidate operator functions of the form
5796 //
5797 // bool operator!(bool);
5798 // bool operator&&(bool, bool);
5799 // bool operator||(bool, bool);
5800 void addExclaimOverload() {
5801 QualType ParamTy = S.Context.BoolTy;
5802 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5803 /*IsAssignmentOperator=*/false,
5804 /*NumContextualBoolArguments=*/1);
5805 }
5806 void addAmpAmpOrPipePipeOverload() {
5807 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5808 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5809 /*IsAssignmentOperator=*/false,
5810 /*NumContextualBoolArguments=*/2);
5811 }
5812
5813 // C++ [over.built]p13:
5814 //
5815 // For every cv-qualified or cv-unqualified object type T there
5816 // exist candidate operator functions of the form
5817 //
5818 // T* operator+(T*, ptrdiff_t); [ABOVE]
5819 // T& operator[](T*, ptrdiff_t);
5820 // T* operator-(T*, ptrdiff_t); [ABOVE]
5821 // T* operator+(ptrdiff_t, T*); [ABOVE]
5822 // T& operator[](ptrdiff_t, T*);
5823 void addSubscriptOverloads() {
5824 for (BuiltinCandidateTypeSet::iterator
5825 Ptr = CandidateTypes[0].pointer_begin(),
5826 PtrEnd = CandidateTypes[0].pointer_end();
5827 Ptr != PtrEnd; ++Ptr) {
5828 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5829 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005830 if (!PointeeType->isObjectType())
5831 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005832
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005833 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5834
5835 // T& operator[](T*, ptrdiff_t)
5836 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5837 }
5838
5839 for (BuiltinCandidateTypeSet::iterator
5840 Ptr = CandidateTypes[1].pointer_begin(),
5841 PtrEnd = CandidateTypes[1].pointer_end();
5842 Ptr != PtrEnd; ++Ptr) {
5843 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5844 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005845 if (!PointeeType->isObjectType())
5846 continue;
5847
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005848 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5849
5850 // T& operator[](ptrdiff_t, T*)
5851 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5852 }
5853 }
5854
5855 // C++ [over.built]p11:
5856 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5857 // C1 is the same type as C2 or is a derived class of C2, T is an object
5858 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5859 // there exist candidate operator functions of the form
5860 //
5861 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5862 //
5863 // where CV12 is the union of CV1 and CV2.
5864 void addArrowStarOverloads() {
5865 for (BuiltinCandidateTypeSet::iterator
5866 Ptr = CandidateTypes[0].pointer_begin(),
5867 PtrEnd = CandidateTypes[0].pointer_end();
5868 Ptr != PtrEnd; ++Ptr) {
5869 QualType C1Ty = (*Ptr);
5870 QualType C1;
5871 QualifierCollector Q1;
5872 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5873 if (!isa<RecordType>(C1))
5874 continue;
5875 // heuristic to reduce number of builtin candidates in the set.
5876 // Add volatile/restrict version only if there are conversions to a
5877 // volatile/restrict type.
5878 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5879 continue;
5880 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5881 continue;
5882 for (BuiltinCandidateTypeSet::iterator
5883 MemPtr = CandidateTypes[1].member_pointer_begin(),
5884 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5885 MemPtr != MemPtrEnd; ++MemPtr) {
5886 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5887 QualType C2 = QualType(mptr->getClass(), 0);
5888 C2 = C2.getUnqualifiedType();
5889 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5890 break;
5891 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5892 // build CV12 T&
5893 QualType T = mptr->getPointeeType();
5894 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5895 T.isVolatileQualified())
5896 continue;
5897 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5898 T.isRestrictQualified())
5899 continue;
5900 T = Q1.apply(S.Context, T);
5901 QualType ResultTy = S.Context.getLValueReferenceType(T);
5902 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5903 }
5904 }
5905 }
5906
5907 // Note that we don't consider the first argument, since it has been
5908 // contextually converted to bool long ago. The candidates below are
5909 // therefore added as binary.
5910 //
5911 // C++ [over.built]p25:
5912 // For every type T, where T is a pointer, pointer-to-member, or scoped
5913 // enumeration type, there exist candidate operator functions of the form
5914 //
5915 // T operator?(bool, T, T);
5916 //
5917 void addConditionalOperatorOverloads() {
5918 /// Set of (canonical) types that we've already handled.
5919 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5920
5921 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5922 for (BuiltinCandidateTypeSet::iterator
5923 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5924 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5925 Ptr != PtrEnd; ++Ptr) {
5926 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5927 continue;
5928
5929 QualType ParamTypes[2] = { *Ptr, *Ptr };
5930 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5931 }
5932
5933 for (BuiltinCandidateTypeSet::iterator
5934 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5935 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5936 MemPtr != MemPtrEnd; ++MemPtr) {
5937 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5938 continue;
5939
5940 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5941 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5942 }
5943
5944 if (S.getLangOptions().CPlusPlus0x) {
5945 for (BuiltinCandidateTypeSet::iterator
5946 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5947 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5948 Enum != EnumEnd; ++Enum) {
5949 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5950 continue;
5951
5952 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5953 continue;
5954
5955 QualType ParamTypes[2] = { *Enum, *Enum };
5956 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5957 }
5958 }
5959 }
5960 }
5961};
5962
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005963} // end anonymous namespace
5964
5965/// AddBuiltinOperatorCandidates - Add the appropriate built-in
5966/// operator overloads to the candidate set (C++ [over.built]), based
5967/// on the operator @p Op and the arguments given. For example, if the
5968/// operator is a binary '+', this routine might add "int
5969/// operator+(int, int)" to cover integer addition.
5970void
5971Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5972 SourceLocation OpLoc,
5973 Expr **Args, unsigned NumArgs,
5974 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005975 // Find all of the types that the arguments can convert to, but only
5976 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00005977 // that make use of these types. Also record whether we encounter non-record
5978 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005979 Qualifiers VisibleTypeConversionsQuals;
5980 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005981 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5982 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00005983
5984 bool HasNonRecordCandidateType = false;
5985 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorfec56e72010-11-03 17:00:07 +00005986 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5987 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5988 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5989 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5990 OpLoc,
5991 true,
5992 (Op == OO_Exclaim ||
5993 Op == OO_AmpAmp ||
5994 Op == OO_PipePipe),
5995 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00005996 HasNonRecordCandidateType = HasNonRecordCandidateType ||
5997 CandidateTypes[ArgIdx].hasNonRecordTypes();
5998 HasArithmeticOrEnumeralCandidateType =
5999 HasArithmeticOrEnumeralCandidateType ||
6000 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00006001 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006002
Chandler Carruth6a577462010-12-13 01:44:01 +00006003 // Exit early when no non-record types have been added to the candidate set
6004 // for any of the arguments to the operator.
6005 if (!HasNonRecordCandidateType)
6006 return;
6007
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006008 // Setup an object to manage the common state for building overloads.
6009 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6010 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006011 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006012 CandidateTypes, CandidateSet);
6013
6014 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006015 switch (Op) {
6016 case OO_None:
6017 case NUM_OVERLOADED_OPERATORS:
6018 assert(false && "Expected an overloaded operator");
6019 break;
6020
Chandler Carruthabb71842010-12-12 08:51:33 +00006021 case OO_New:
6022 case OO_Delete:
6023 case OO_Array_New:
6024 case OO_Array_Delete:
6025 case OO_Call:
6026 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
6027 break;
6028
6029 case OO_Comma:
6030 case OO_Arrow:
6031 // C++ [over.match.oper]p3:
6032 // -- For the operator ',', the unary operator '&', or the
6033 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00006034 break;
6035
6036 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00006037 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006038 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00006039 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00006040
6041 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00006042 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006043 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00006044 } else {
6045 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6046 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6047 }
Douglas Gregor74253732008-11-19 15:42:04 +00006048 break;
6049
Chandler Carruthabb71842010-12-12 08:51:33 +00006050 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00006051 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00006052 OpBuilder.addUnaryStarPointerOverloads();
6053 else
6054 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6055 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006056
Chandler Carruthabb71842010-12-12 08:51:33 +00006057 case OO_Slash:
6058 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00006059 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006060
6061 case OO_PlusPlus:
6062 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006063 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6064 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00006065 break;
6066
Douglas Gregor19b7b152009-08-24 13:43:27 +00006067 case OO_EqualEqual:
6068 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006069 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00006070 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00006071
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006072 case OO_Less:
6073 case OO_Greater:
6074 case OO_LessEqual:
6075 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006076 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00006077 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6078 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006079
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006080 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006081 case OO_Caret:
6082 case OO_Pipe:
6083 case OO_LessLess:
6084 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006085 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006086 break;
6087
Chandler Carruthabb71842010-12-12 08:51:33 +00006088 case OO_Amp: // '&' is either unary or binary
6089 if (NumArgs == 1)
6090 // C++ [over.match.oper]p3:
6091 // -- For the operator ',', the unary operator '&', or the
6092 // operator '->', the built-in candidates set is empty.
6093 break;
6094
6095 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6096 break;
6097
6098 case OO_Tilde:
6099 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6100 break;
6101
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006102 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006103 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00006104 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006105
6106 case OO_PlusEqual:
6107 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006108 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006109 // Fall through.
6110
6111 case OO_StarEqual:
6112 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006113 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006114 break;
6115
6116 case OO_PercentEqual:
6117 case OO_LessLessEqual:
6118 case OO_GreaterGreaterEqual:
6119 case OO_AmpEqual:
6120 case OO_CaretEqual:
6121 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006122 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006123 break;
6124
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006125 case OO_Exclaim:
6126 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00006127 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006128
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006129 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006130 case OO_PipePipe:
6131 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006132 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006133
6134 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006135 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006136 break;
6137
6138 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006139 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006140 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006141
6142 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006143 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00006144 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6145 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006146 }
6147}
6148
Douglas Gregorfa047642009-02-04 00:32:51 +00006149/// \brief Add function candidates found via argument-dependent lookup
6150/// to the set of overloading candidates.
6151///
6152/// This routine performs argument-dependent name lookup based on the
6153/// given function name (which may also be an operator name) and adds
6154/// all of the overload candidates found by ADL to the overload
6155/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00006156void
Douglas Gregorfa047642009-02-04 00:32:51 +00006157Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00006158 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00006159 Expr **Args, unsigned NumArgs,
Douglas Gregor67714232011-03-03 02:41:12 +00006160 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006161 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00006162 bool PartialOverloading,
6163 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00006164 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00006165
John McCalla113e722010-01-26 06:04:06 +00006166 // FIXME: This approach for uniquing ADL results (and removing
6167 // redundant candidates from the set) relies on pointer-equality,
6168 // which means we need to key off the canonical decl. However,
6169 // always going back to the canonical decl might not get us the
6170 // right set of default arguments. What default arguments are
6171 // we supposed to consider on ADL candidates, anyway?
6172
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006173 // FIXME: Pass in the explicit template arguments?
Richard Smithad762fc2011-04-14 22:09:26 +00006174 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6175 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00006176
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006177 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006178 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6179 CandEnd = CandidateSet.end();
6180 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00006181 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00006182 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00006183 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00006184 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00006185 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006186
6187 // For each of the ADL candidates we found, add it to the overload
6188 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00006189 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00006190 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00006191 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00006192 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006193 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006194
John McCall9aa472c2010-03-19 07:35:19 +00006195 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006196 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006197 } else
John McCall6e266892010-01-26 03:27:55 +00006198 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00006199 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00006200 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00006201 }
Douglas Gregorfa047642009-02-04 00:32:51 +00006202}
6203
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006204/// isBetterOverloadCandidate - Determines whether the first overload
6205/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00006206bool
John McCall120d63c2010-08-24 20:38:10 +00006207isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00006208 const OverloadCandidate &Cand1,
6209 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006210 SourceLocation Loc,
6211 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006212 // Define viable functions to be better candidates than non-viable
6213 // functions.
6214 if (!Cand2.Viable)
6215 return Cand1.Viable;
6216 else if (!Cand1.Viable)
6217 return false;
6218
Douglas Gregor88a35142008-12-22 05:46:06 +00006219 // C++ [over.match.best]p1:
6220 //
6221 // -- if F is a static member function, ICS1(F) is defined such
6222 // that ICS1(F) is neither better nor worse than ICS1(G) for
6223 // any function G, and, symmetrically, ICS1(G) is neither
6224 // better nor worse than ICS1(F).
6225 unsigned StartArg = 0;
6226 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6227 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006228
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006229 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00006230 // A viable function F1 is defined to be a better function than another
6231 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006232 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006233 unsigned NumArgs = Cand1.Conversions.size();
6234 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6235 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006236 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00006237 switch (CompareImplicitConversionSequences(S,
6238 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006239 Cand2.Conversions[ArgIdx])) {
6240 case ImplicitConversionSequence::Better:
6241 // Cand1 has a better conversion sequence.
6242 HasBetterConversion = true;
6243 break;
6244
6245 case ImplicitConversionSequence::Worse:
6246 // Cand1 can't be better than Cand2.
6247 return false;
6248
6249 case ImplicitConversionSequence::Indistinguishable:
6250 // Do nothing.
6251 break;
6252 }
6253 }
6254
Mike Stump1eb44332009-09-09 15:08:12 +00006255 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006256 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006257 if (HasBetterConversion)
6258 return true;
6259
Mike Stump1eb44332009-09-09 15:08:12 +00006260 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006261 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00006262 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006263 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6264 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006265
6266 // -- F1 and F2 are function template specializations, and the function
6267 // template for F1 is more specialized than the template for F2
6268 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006269 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00006270 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00006271 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006272 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00006273 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6274 Cand2.Function->getPrimaryTemplate(),
6275 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006276 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00006277 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00006278 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006279 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00006280 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006281
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006282 // -- the context is an initialization by user-defined conversion
6283 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6284 // from the return type of F1 to the destination type (i.e.,
6285 // the type of the entity being initialized) is a better
6286 // conversion sequence than the standard conversion sequence
6287 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006288 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00006289 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006290 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00006291 switch (CompareStandardConversionSequences(S,
6292 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006293 Cand2.FinalConversion)) {
6294 case ImplicitConversionSequence::Better:
6295 // Cand1 has a better conversion sequence.
6296 return true;
6297
6298 case ImplicitConversionSequence::Worse:
6299 // Cand1 can't be better than Cand2.
6300 return false;
6301
6302 case ImplicitConversionSequence::Indistinguishable:
6303 // Do nothing
6304 break;
6305 }
6306 }
6307
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006308 return false;
6309}
6310
Mike Stump1eb44332009-09-09 15:08:12 +00006311/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00006312/// within an overload candidate set.
6313///
6314/// \param CandidateSet the set of candidate functions.
6315///
6316/// \param Loc the location of the function name (or operator symbol) for
6317/// which overload resolution occurs.
6318///
Mike Stump1eb44332009-09-09 15:08:12 +00006319/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00006320/// function, Best points to the candidate function found.
6321///
6322/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00006323OverloadingResult
6324OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00006325 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00006326 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006327 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00006328 Best = end();
6329 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6330 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006331 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006332 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006333 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006334 }
6335
6336 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00006337 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006338 return OR_No_Viable_Function;
6339
6340 // Make sure that this function is better than every other viable
6341 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00006342 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00006343 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006344 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006345 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006346 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00006347 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006348 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006349 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006350 }
Mike Stump1eb44332009-09-09 15:08:12 +00006351
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006352 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006353 if (Best->Function &&
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00006354 (Best->Function->isDeleted() || Best->Function->isUnavailable()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006355 return OR_Deleted;
6356
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006357 return OR_Success;
6358}
6359
John McCall3c80f572010-01-12 02:15:36 +00006360namespace {
6361
6362enum OverloadCandidateKind {
6363 oc_function,
6364 oc_method,
6365 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00006366 oc_function_template,
6367 oc_method_template,
6368 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00006369 oc_implicit_default_constructor,
6370 oc_implicit_copy_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006371 oc_implicit_copy_assignment,
6372 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00006373};
6374
John McCall220ccbf2010-01-13 00:25:19 +00006375OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6376 FunctionDecl *Fn,
6377 std::string &Description) {
6378 bool isTemplate = false;
6379
6380 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6381 isTemplate = true;
6382 Description = S.getTemplateArgumentBindingsText(
6383 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6384 }
John McCallb1622a12010-01-06 09:43:14 +00006385
6386 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00006387 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00006388 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00006389
Sebastian Redlf677ea32011-02-05 19:23:19 +00006390 if (Ctor->getInheritedConstructor())
6391 return oc_implicit_inherited_constructor;
6392
John McCall3c80f572010-01-12 02:15:36 +00006393 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6394 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00006395 }
6396
6397 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6398 // This actually gets spelled 'candidate function' for now, but
6399 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00006400 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00006401 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00006402
Douglas Gregor3e9438b2010-09-27 22:37:28 +00006403 assert(Meth->isCopyAssignmentOperator()
John McCallb1622a12010-01-06 09:43:14 +00006404 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00006405 return oc_implicit_copy_assignment;
6406 }
6407
John McCall220ccbf2010-01-13 00:25:19 +00006408 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00006409}
6410
Sebastian Redlf677ea32011-02-05 19:23:19 +00006411void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6412 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6413 if (!Ctor) return;
6414
6415 Ctor = Ctor->getInheritedConstructor();
6416 if (!Ctor) return;
6417
6418 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6419}
6420
John McCall3c80f572010-01-12 02:15:36 +00006421} // end anonymous namespace
6422
6423// Notes the location of an overload candidate.
6424void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00006425 std::string FnDesc;
6426 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6427 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6428 << (unsigned) K << FnDesc;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006429 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00006430}
6431
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006432//Notes the location of all overload candidates designated through
6433// OverloadedExpr
6434void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6435 assert(OverloadedExpr->getType() == Context.OverloadTy);
6436
6437 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6438 OverloadExpr *OvlExpr = Ovl.Expression;
6439
6440 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6441 IEnd = OvlExpr->decls_end();
6442 I != IEnd; ++I) {
6443 if (FunctionTemplateDecl *FunTmpl =
6444 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6445 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6446 } else if (FunctionDecl *Fun
6447 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6448 NoteOverloadCandidate(Fun);
6449 }
6450 }
6451}
6452
John McCall1d318332010-01-12 00:44:57 +00006453/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6454/// "lead" diagnostic; it will be given two arguments, the source and
6455/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00006456void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6457 Sema &S,
6458 SourceLocation CaretLoc,
6459 const PartialDiagnostic &PDiag) const {
6460 S.Diag(CaretLoc, PDiag)
6461 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00006462 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00006463 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6464 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00006465 }
John McCall81201622010-01-08 04:41:39 +00006466}
6467
John McCall1d318332010-01-12 00:44:57 +00006468namespace {
6469
John McCalladbb8f82010-01-13 09:16:55 +00006470void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6471 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6472 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00006473 assert(Cand->Function && "for now, candidate must be a function");
6474 FunctionDecl *Fn = Cand->Function;
6475
6476 // There's a conversion slot for the object argument if this is a
6477 // non-constructor method. Note that 'I' corresponds the
6478 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00006479 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00006480 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00006481 if (I == 0)
6482 isObjectArgument = true;
6483 else
6484 I--;
John McCall220ccbf2010-01-13 00:25:19 +00006485 }
6486
John McCall220ccbf2010-01-13 00:25:19 +00006487 std::string FnDesc;
6488 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6489
John McCalladbb8f82010-01-13 09:16:55 +00006490 Expr *FromExpr = Conv.Bad.FromExpr;
6491 QualType FromTy = Conv.Bad.getFromType();
6492 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00006493
John McCall5920dbb2010-02-02 02:42:52 +00006494 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00006495 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00006496 Expr *E = FromExpr->IgnoreParens();
6497 if (isa<UnaryOperator>(E))
6498 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00006499 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00006500
6501 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6502 << (unsigned) FnKind << FnDesc
6503 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6504 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006505 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00006506 return;
6507 }
6508
John McCall258b2032010-01-23 08:10:49 +00006509 // Do some hand-waving analysis to see if the non-viability is due
6510 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00006511 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6512 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6513 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6514 CToTy = RT->getPointeeType();
6515 else {
6516 // TODO: detect and diagnose the full richness of const mismatches.
6517 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6518 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6519 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6520 }
6521
6522 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6523 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6524 // It is dumb that we have to do this here.
6525 while (isa<ArrayType>(CFromTy))
6526 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6527 while (isa<ArrayType>(CToTy))
6528 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6529
6530 Qualifiers FromQs = CFromTy.getQualifiers();
6531 Qualifiers ToQs = CToTy.getQualifiers();
6532
6533 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6534 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6535 << (unsigned) FnKind << FnDesc
6536 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6537 << FromTy
6538 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6539 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006540 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00006541 return;
6542 }
6543
6544 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6545 assert(CVR && "unexpected qualifiers mismatch");
6546
6547 if (isObjectArgument) {
6548 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6549 << (unsigned) FnKind << FnDesc
6550 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6551 << FromTy << (CVR - 1);
6552 } else {
6553 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6554 << (unsigned) FnKind << FnDesc
6555 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6556 << FromTy << (CVR - 1) << I+1;
6557 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00006558 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00006559 return;
6560 }
6561
John McCall258b2032010-01-23 08:10:49 +00006562 // Diagnose references or pointers to incomplete types differently,
6563 // since it's far from impossible that the incompleteness triggered
6564 // the failure.
6565 QualType TempFromTy = FromTy.getNonReferenceType();
6566 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6567 TempFromTy = PTy->getPointeeType();
6568 if (TempFromTy->isIncompleteType()) {
6569 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6570 << (unsigned) FnKind << FnDesc
6571 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6572 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006573 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00006574 return;
6575 }
6576
Douglas Gregor85789812010-06-30 23:01:39 +00006577 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006578 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00006579 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6580 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6581 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6582 FromPtrTy->getPointeeType()) &&
6583 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6584 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006585 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00006586 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006587 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00006588 }
6589 } else if (const ObjCObjectPointerType *FromPtrTy
6590 = FromTy->getAs<ObjCObjectPointerType>()) {
6591 if (const ObjCObjectPointerType *ToPtrTy
6592 = ToTy->getAs<ObjCObjectPointerType>())
6593 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6594 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6595 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6596 FromPtrTy->getPointeeType()) &&
6597 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006598 BaseToDerivedConversion = 2;
6599 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6600 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6601 !FromTy->isIncompleteType() &&
6602 !ToRefTy->getPointeeType()->isIncompleteType() &&
6603 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6604 BaseToDerivedConversion = 3;
6605 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006606
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006607 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006608 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006609 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00006610 << (unsigned) FnKind << FnDesc
6611 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006612 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006613 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006614 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00006615 return;
6616 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006617
John McCall651f3ee2010-01-14 03:28:57 +00006618 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00006619 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6620 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00006621 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00006622 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006623 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00006624}
6625
6626void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6627 unsigned NumFormalArgs) {
6628 // TODO: treat calls to a missing default constructor as a special case
6629
6630 FunctionDecl *Fn = Cand->Function;
6631 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6632
6633 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006634
John McCalladbb8f82010-01-13 09:16:55 +00006635 // at least / at most / exactly
6636 unsigned mode, modeCount;
6637 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00006638 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6639 (Cand->FailureKind == ovl_fail_bad_deduction &&
6640 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006641 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00006642 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00006643 mode = 0; // "at least"
6644 else
6645 mode = 2; // "exactly"
6646 modeCount = MinParams;
6647 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00006648 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6649 (Cand->FailureKind == ovl_fail_bad_deduction &&
6650 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00006651 if (MinParams != FnTy->getNumArgs())
6652 mode = 1; // "at most"
6653 else
6654 mode = 2; // "exactly"
6655 modeCount = FnTy->getNumArgs();
6656 }
6657
6658 std::string Description;
6659 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6660
6661 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006662 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregora18592e2010-05-08 18:13:28 +00006663 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006664 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006665}
6666
John McCall342fec42010-02-01 18:53:26 +00006667/// Diagnose a failed template-argument deduction.
6668void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6669 Expr **Args, unsigned NumArgs) {
6670 FunctionDecl *Fn = Cand->Function; // pattern
6671
Douglas Gregora9333192010-05-08 17:41:32 +00006672 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00006673 NamedDecl *ParamD;
6674 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6675 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6676 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00006677 switch (Cand->DeductionFailure.Result) {
6678 case Sema::TDK_Success:
6679 llvm_unreachable("TDK_success while diagnosing bad deduction");
6680
6681 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00006682 assert(ParamD && "no parameter found for incomplete deduction result");
6683 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6684 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006685 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00006686 return;
6687 }
6688
John McCall57e97782010-08-05 09:05:08 +00006689 case Sema::TDK_Underqualified: {
6690 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6691 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6692
6693 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6694
6695 // Param will have been canonicalized, but it should just be a
6696 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00006697 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00006698 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00006699 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00006700 assert(S.Context.hasSameType(Param, NonCanonParam));
6701
6702 // Arg has also been canonicalized, but there's nothing we can do
6703 // about that. It also doesn't matter as much, because it won't
6704 // have any template parameters in it (because deduction isn't
6705 // done on dependent types).
6706 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6707
6708 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6709 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006710 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00006711 return;
6712 }
6713
6714 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00006715 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00006716 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00006717 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00006718 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00006719 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00006720 which = 1;
6721 else {
Douglas Gregora9333192010-05-08 17:41:32 +00006722 which = 2;
6723 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006724
Douglas Gregora9333192010-05-08 17:41:32 +00006725 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006726 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00006727 << *Cand->DeductionFailure.getFirstArg()
6728 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006729 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00006730 return;
6731 }
Douglas Gregora18592e2010-05-08 18:13:28 +00006732
Douglas Gregorf1a84452010-05-08 19:15:54 +00006733 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006734 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00006735 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006736 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00006737 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6738 << ParamD->getDeclName();
6739 else {
6740 int index = 0;
6741 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6742 index = TTP->getIndex();
6743 else if (NonTypeTemplateParmDecl *NTTP
6744 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6745 index = NTTP->getIndex();
6746 else
6747 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006748 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00006749 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6750 << (index + 1);
6751 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00006752 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00006753 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006754
Douglas Gregora18592e2010-05-08 18:13:28 +00006755 case Sema::TDK_TooManyArguments:
6756 case Sema::TDK_TooFewArguments:
6757 DiagnoseArityMismatch(S, Cand, NumArgs);
6758 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00006759
6760 case Sema::TDK_InstantiationDepth:
6761 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006762 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00006763 return;
6764
6765 case Sema::TDK_SubstitutionFailure: {
6766 std::string ArgString;
6767 if (TemplateArgumentList *Args
6768 = Cand->DeductionFailure.getTemplateArgumentList())
6769 ArgString = S.getTemplateArgumentBindingsText(
6770 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6771 *Args);
6772 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6773 << ArgString;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006774 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00006775 return;
6776 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006777
John McCall342fec42010-02-01 18:53:26 +00006778 // TODO: diagnose these individually, then kill off
6779 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00006780 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00006781 case Sema::TDK_FailedOverloadResolution:
6782 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006783 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00006784 return;
6785 }
6786}
6787
6788/// Generates a 'note' diagnostic for an overload candidate. We've
6789/// already generated a primary error at the call site.
6790///
6791/// It really does need to be a single diagnostic with its caret
6792/// pointed at the candidate declaration. Yes, this creates some
6793/// major challenges of technical writing. Yes, this makes pointing
6794/// out problems with specific arguments quite awkward. It's still
6795/// better than generating twenty screens of text for every failed
6796/// overload.
6797///
6798/// It would be great to be able to express per-candidate problems
6799/// more richly for those diagnostic clients that cared, but we'd
6800/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00006801void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6802 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00006803 FunctionDecl *Fn = Cand->Function;
6804
John McCall81201622010-01-08 04:41:39 +00006805 // Note deleted candidates, but only if they're viable.
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00006806 if (Cand->Viable && (Fn->isDeleted() || Fn->isUnavailable())) {
John McCall220ccbf2010-01-13 00:25:19 +00006807 std::string FnDesc;
6808 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00006809
6810 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00006811 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006812 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00006813 return;
John McCall81201622010-01-08 04:41:39 +00006814 }
6815
John McCall220ccbf2010-01-13 00:25:19 +00006816 // We don't really have anything else to say about viable candidates.
6817 if (Cand->Viable) {
6818 S.NoteOverloadCandidate(Fn);
6819 return;
6820 }
John McCall1d318332010-01-12 00:44:57 +00006821
John McCalladbb8f82010-01-13 09:16:55 +00006822 switch (Cand->FailureKind) {
6823 case ovl_fail_too_many_arguments:
6824 case ovl_fail_too_few_arguments:
6825 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00006826
John McCalladbb8f82010-01-13 09:16:55 +00006827 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00006828 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6829
John McCall717e8912010-01-23 05:17:32 +00006830 case ovl_fail_trivial_conversion:
6831 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00006832 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00006833 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006834
John McCallb1bdc622010-02-25 01:37:24 +00006835 case ovl_fail_bad_conversion: {
6836 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6837 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00006838 if (Cand->Conversions[I].isBad())
6839 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006840
John McCalladbb8f82010-01-13 09:16:55 +00006841 // FIXME: this currently happens when we're called from SemaInit
6842 // when user-conversion overload fails. Figure out how to handle
6843 // those conditions and diagnose them well.
6844 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006845 }
John McCallb1bdc622010-02-25 01:37:24 +00006846 }
John McCalla1d7d622010-01-08 00:58:21 +00006847}
6848
6849void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6850 // Desugar the type of the surrogate down to a function type,
6851 // retaining as many typedefs as possible while still showing
6852 // the function type (and, therefore, its parameter types).
6853 QualType FnType = Cand->Surrogate->getConversionType();
6854 bool isLValueReference = false;
6855 bool isRValueReference = false;
6856 bool isPointer = false;
6857 if (const LValueReferenceType *FnTypeRef =
6858 FnType->getAs<LValueReferenceType>()) {
6859 FnType = FnTypeRef->getPointeeType();
6860 isLValueReference = true;
6861 } else if (const RValueReferenceType *FnTypeRef =
6862 FnType->getAs<RValueReferenceType>()) {
6863 FnType = FnTypeRef->getPointeeType();
6864 isRValueReference = true;
6865 }
6866 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6867 FnType = FnTypePtr->getPointeeType();
6868 isPointer = true;
6869 }
6870 // Desugar down to a function type.
6871 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6872 // Reconstruct the pointer/reference as appropriate.
6873 if (isPointer) FnType = S.Context.getPointerType(FnType);
6874 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6875 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6876
6877 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6878 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006879 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00006880}
6881
6882void NoteBuiltinOperatorCandidate(Sema &S,
6883 const char *Opc,
6884 SourceLocation OpLoc,
6885 OverloadCandidate *Cand) {
6886 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6887 std::string TypeStr("operator");
6888 TypeStr += Opc;
6889 TypeStr += "(";
6890 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6891 if (Cand->Conversions.size() == 1) {
6892 TypeStr += ")";
6893 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6894 } else {
6895 TypeStr += ", ";
6896 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6897 TypeStr += ")";
6898 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6899 }
6900}
6901
6902void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6903 OverloadCandidate *Cand) {
6904 unsigned NoOperands = Cand->Conversions.size();
6905 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6906 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00006907 if (ICS.isBad()) break; // all meaningless after first invalid
6908 if (!ICS.isAmbiguous()) continue;
6909
John McCall120d63c2010-08-24 20:38:10 +00006910 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006911 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00006912 }
6913}
6914
John McCall1b77e732010-01-15 23:32:50 +00006915SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6916 if (Cand->Function)
6917 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00006918 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00006919 return Cand->Surrogate->getLocation();
6920 return SourceLocation();
6921}
6922
John McCallbf65c0b2010-01-12 00:48:53 +00006923struct CompareOverloadCandidatesForDisplay {
6924 Sema &S;
6925 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00006926
6927 bool operator()(const OverloadCandidate *L,
6928 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00006929 // Fast-path this check.
6930 if (L == R) return false;
6931
John McCall81201622010-01-08 04:41:39 +00006932 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00006933 if (L->Viable) {
6934 if (!R->Viable) return true;
6935
6936 // TODO: introduce a tri-valued comparison for overload
6937 // candidates. Would be more worthwhile if we had a sort
6938 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00006939 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6940 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00006941 } else if (R->Viable)
6942 return false;
John McCall81201622010-01-08 04:41:39 +00006943
John McCall1b77e732010-01-15 23:32:50 +00006944 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00006945
John McCall1b77e732010-01-15 23:32:50 +00006946 // Criteria by which we can sort non-viable candidates:
6947 if (!L->Viable) {
6948 // 1. Arity mismatches come after other candidates.
6949 if (L->FailureKind == ovl_fail_too_many_arguments ||
6950 L->FailureKind == ovl_fail_too_few_arguments)
6951 return false;
6952 if (R->FailureKind == ovl_fail_too_many_arguments ||
6953 R->FailureKind == ovl_fail_too_few_arguments)
6954 return true;
John McCall81201622010-01-08 04:41:39 +00006955
John McCall717e8912010-01-23 05:17:32 +00006956 // 2. Bad conversions come first and are ordered by the number
6957 // of bad conversions and quality of good conversions.
6958 if (L->FailureKind == ovl_fail_bad_conversion) {
6959 if (R->FailureKind != ovl_fail_bad_conversion)
6960 return true;
6961
6962 // If there's any ordering between the defined conversions...
6963 // FIXME: this might not be transitive.
6964 assert(L->Conversions.size() == R->Conversions.size());
6965
6966 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00006967 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6968 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00006969 switch (CompareImplicitConversionSequences(S,
6970 L->Conversions[I],
6971 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00006972 case ImplicitConversionSequence::Better:
6973 leftBetter++;
6974 break;
6975
6976 case ImplicitConversionSequence::Worse:
6977 leftBetter--;
6978 break;
6979
6980 case ImplicitConversionSequence::Indistinguishable:
6981 break;
6982 }
6983 }
6984 if (leftBetter > 0) return true;
6985 if (leftBetter < 0) return false;
6986
6987 } else if (R->FailureKind == ovl_fail_bad_conversion)
6988 return false;
6989
John McCall1b77e732010-01-15 23:32:50 +00006990 // TODO: others?
6991 }
6992
6993 // Sort everything else by location.
6994 SourceLocation LLoc = GetLocationForCandidate(L);
6995 SourceLocation RLoc = GetLocationForCandidate(R);
6996
6997 // Put candidates without locations (e.g. builtins) at the end.
6998 if (LLoc.isInvalid()) return false;
6999 if (RLoc.isInvalid()) return true;
7000
7001 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00007002 }
7003};
7004
John McCall717e8912010-01-23 05:17:32 +00007005/// CompleteNonViableCandidate - Normally, overload resolution only
7006/// computes up to the first
7007void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7008 Expr **Args, unsigned NumArgs) {
7009 assert(!Cand->Viable);
7010
7011 // Don't do anything on failures other than bad conversion.
7012 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7013
7014 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00007015 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00007016 unsigned ConvCount = Cand->Conversions.size();
7017 while (true) {
7018 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7019 ConvIdx++;
7020 if (Cand->Conversions[ConvIdx - 1].isBad())
7021 break;
7022 }
7023
7024 if (ConvIdx == ConvCount)
7025 return;
7026
John McCallb1bdc622010-02-25 01:37:24 +00007027 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7028 "remaining conversion is initialized?");
7029
Douglas Gregor23ef6c02010-04-16 17:45:54 +00007030 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00007031 // operation somehow.
7032 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00007033
7034 const FunctionProtoType* Proto;
7035 unsigned ArgIdx = ConvIdx;
7036
7037 if (Cand->IsSurrogate) {
7038 QualType ConvType
7039 = Cand->Surrogate->getConversionType().getNonReferenceType();
7040 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7041 ConvType = ConvPtrType->getPointeeType();
7042 Proto = ConvType->getAs<FunctionProtoType>();
7043 ArgIdx--;
7044 } else if (Cand->Function) {
7045 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7046 if (isa<CXXMethodDecl>(Cand->Function) &&
7047 !isa<CXXConstructorDecl>(Cand->Function))
7048 ArgIdx--;
7049 } else {
7050 // Builtin binary operator with a bad first conversion.
7051 assert(ConvCount <= 3);
7052 for (; ConvIdx != ConvCount; ++ConvIdx)
7053 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00007054 = TryCopyInitialization(S, Args[ConvIdx],
7055 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007056 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00007057 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00007058 return;
7059 }
7060
7061 // Fill in the rest of the conversions.
7062 unsigned NumArgsInProto = Proto->getNumArgs();
7063 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
7064 if (ArgIdx < NumArgsInProto)
7065 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00007066 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007067 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00007068 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00007069 else
7070 Cand->Conversions[ConvIdx].setEllipsis();
7071 }
7072}
7073
John McCalla1d7d622010-01-08 00:58:21 +00007074} // end anonymous namespace
7075
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007076/// PrintOverloadCandidates - When overload resolution fails, prints
7077/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00007078/// set.
John McCall120d63c2010-08-24 20:38:10 +00007079void OverloadCandidateSet::NoteCandidates(Sema &S,
7080 OverloadCandidateDisplayKind OCD,
7081 Expr **Args, unsigned NumArgs,
7082 const char *Opc,
7083 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00007084 // Sort the candidates by viability and position. Sorting directly would
7085 // be prohibitive, so we make a set of pointers and sort those.
7086 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00007087 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7088 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00007089 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00007090 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00007091 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00007092 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007093 if (Cand->Function || Cand->IsSurrogate)
7094 Cands.push_back(Cand);
7095 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7096 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00007097 }
7098 }
7099
John McCallbf65c0b2010-01-12 00:48:53 +00007100 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00007101 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007102
John McCall1d318332010-01-12 00:44:57 +00007103 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00007104
John McCall81201622010-01-08 04:41:39 +00007105 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall120d63c2010-08-24 20:38:10 +00007106 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007107 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00007108 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7109 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00007110
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007111 // Set an arbitrary limit on the number of candidate functions we'll spam
7112 // the user with. FIXME: This limit should depend on details of the
7113 // candidate list.
7114 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
7115 break;
7116 }
7117 ++CandsShown;
7118
John McCalla1d7d622010-01-08 00:58:21 +00007119 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00007120 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00007121 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00007122 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007123 else {
7124 assert(Cand->Viable &&
7125 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00007126 // Generally we only see ambiguities including viable builtin
7127 // operators if overload resolution got screwed up by an
7128 // ambiguous user-defined conversion.
7129 //
7130 // FIXME: It's quite possible for different conversions to see
7131 // different ambiguities, though.
7132 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00007133 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00007134 ReportedAmbiguousConversions = true;
7135 }
John McCalla1d7d622010-01-08 00:58:21 +00007136
John McCall1d318332010-01-12 00:44:57 +00007137 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00007138 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007139 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007140 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007141
7142 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00007143 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007144}
7145
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007146// [PossiblyAFunctionType] --> [Return]
7147// NonFunctionType --> NonFunctionType
7148// R (A) --> R(A)
7149// R (*)(A) --> R (A)
7150// R (&)(A) --> R (A)
7151// R (S::*)(A) --> R (A)
7152QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7153 QualType Ret = PossiblyAFunctionType;
7154 if (const PointerType *ToTypePtr =
7155 PossiblyAFunctionType->getAs<PointerType>())
7156 Ret = ToTypePtr->getPointeeType();
7157 else if (const ReferenceType *ToTypeRef =
7158 PossiblyAFunctionType->getAs<ReferenceType>())
7159 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00007160 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007161 PossiblyAFunctionType->getAs<MemberPointerType>())
7162 Ret = MemTypePtr->getPointeeType();
7163 Ret =
7164 Context.getCanonicalType(Ret).getUnqualifiedType();
7165 return Ret;
7166}
Douglas Gregor904eed32008-11-10 20:40:00 +00007167
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007168// A helper class to help with address of function resolution
7169// - allows us to avoid passing around all those ugly parameters
7170class AddressOfFunctionResolver
7171{
7172 Sema& S;
7173 Expr* SourceExpr;
7174 const QualType& TargetType;
7175 QualType TargetFunctionType; // Extracted function type from target type
7176
7177 bool Complain;
7178 //DeclAccessPair& ResultFunctionAccessPair;
7179 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007180
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007181 bool TargetTypeIsNonStaticMemberFunction;
7182 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007183
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007184 OverloadExpr::FindResult OvlExprInfo;
7185 OverloadExpr *OvlExpr;
7186 TemplateArgumentListInfo OvlExplicitTemplateArgs;
John McCall9aa472c2010-03-19 07:35:19 +00007187 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007188
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007189public:
7190 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7191 const QualType& TargetType, bool Complain)
7192 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7193 Complain(Complain), Context(S.getASTContext()),
7194 TargetTypeIsNonStaticMemberFunction(
7195 !!TargetType->getAs<MemberPointerType>()),
7196 FoundNonTemplateFunction(false),
7197 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7198 OvlExpr(OvlExprInfo.Expression)
7199 {
7200 ExtractUnqualifiedFunctionTypeFromTargetType();
7201
7202 if (!TargetFunctionType->isFunctionType()) {
7203 if (OvlExpr->hasExplicitTemplateArgs()) {
7204 DeclAccessPair dap;
7205 if( FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
7206 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00007207
7208 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7209 if (!Method->isStatic()) {
7210 // If the target type is a non-function type and the function
7211 // found is a non-static member function, pretend as if that was
7212 // the target, it's the only possible type to end up with.
7213 TargetTypeIsNonStaticMemberFunction = true;
7214
7215 // And skip adding the function if its not in the proper form.
7216 // We'll diagnose this due to an empty set of functions.
7217 if (!OvlExprInfo.HasFormOfMemberPointer)
7218 return;
7219 }
7220 }
7221
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007222 Matches.push_back(std::make_pair(dap,Fn));
7223 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00007224 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007225 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00007226 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007227
7228 if (OvlExpr->hasExplicitTemplateArgs())
7229 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00007230
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007231 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7232 // C++ [over.over]p4:
7233 // If more than one function is selected, [...]
7234 if (Matches.size() > 1) {
7235 if (FoundNonTemplateFunction)
7236 EliminateAllTemplateMatches();
7237 else
7238 EliminateAllExceptMostSpecializedTemplate();
7239 }
7240 }
7241 }
7242
7243private:
7244 bool isTargetTypeAFunction() const {
7245 return TargetFunctionType->isFunctionType();
7246 }
7247
7248 // [ToType] [Return]
7249
7250 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7251 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7252 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7253 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7254 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7255 }
7256
7257 // return true if any matching specializations were found
7258 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7259 const DeclAccessPair& CurAccessFunPair) {
7260 if (CXXMethodDecl *Method
7261 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7262 // Skip non-static function templates when converting to pointer, and
7263 // static when converting to member pointer.
7264 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7265 return false;
7266 }
7267 else if (TargetTypeIsNonStaticMemberFunction)
7268 return false;
7269
7270 // C++ [over.over]p2:
7271 // If the name is a function template, template argument deduction is
7272 // done (14.8.2.2), and if the argument deduction succeeds, the
7273 // resulting template argument list is used to generate a single
7274 // function template specialization, which is added to the set of
7275 // overloaded functions considered.
7276 FunctionDecl *Specialization = 0;
7277 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7278 if (Sema::TemplateDeductionResult Result
7279 = S.DeduceTemplateArguments(FunctionTemplate,
7280 &OvlExplicitTemplateArgs,
7281 TargetFunctionType, Specialization,
7282 Info)) {
7283 // FIXME: make a note of the failed deduction for diagnostics.
7284 (void)Result;
7285 return false;
7286 }
7287
7288 // Template argument deduction ensures that we have an exact match.
7289 // This function template specicalization works.
7290 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7291 assert(TargetFunctionType
7292 == Context.getCanonicalType(Specialization->getType()));
7293 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7294 return true;
7295 }
7296
7297 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7298 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00007299 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00007300 // Skip non-static functions when converting to pointer, and static
7301 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007302 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7303 return false;
7304 }
7305 else if (TargetTypeIsNonStaticMemberFunction)
7306 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00007307
Chandler Carruthbd647292009-12-29 06:17:27 +00007308 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00007309 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007310 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7311 FunDecl->getType()) ||
7312 IsNoReturnConversion(Context, FunDecl->getType(), TargetFunctionType,
Douglas Gregor43c79c22009-12-09 00:47:37 +00007313 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007314 Matches.push_back(std::make_pair(CurAccessFunPair,
7315 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00007316 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007317 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00007318 }
Mike Stump1eb44332009-09-09 15:08:12 +00007319 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007320
7321 return false;
7322 }
7323
7324 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7325 bool Ret = false;
7326
7327 // If the overload expression doesn't have the form of a pointer to
7328 // member, don't try to convert it to a pointer-to-member type.
7329 if (IsInvalidFormOfPointerToMemberFunction())
7330 return false;
7331
7332 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7333 E = OvlExpr->decls_end();
7334 I != E; ++I) {
7335 // Look through any using declarations to find the underlying function.
7336 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7337
7338 // C++ [over.over]p3:
7339 // Non-member functions and static member functions match
7340 // targets of type "pointer-to-function" or "reference-to-function."
7341 // Nonstatic member functions match targets of
7342 // type "pointer-to-member-function."
7343 // Note that according to DR 247, the containing class does not matter.
7344 if (FunctionTemplateDecl *FunctionTemplate
7345 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7346 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7347 Ret = true;
7348 }
7349 // If we have explicit template arguments supplied, skip non-templates.
7350 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7351 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7352 Ret = true;
7353 }
7354 assert(Ret || Matches.empty());
7355 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00007356 }
7357
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007358 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007359 // [...] and any given function template specialization F1 is
7360 // eliminated if the set contains a second function template
7361 // specialization whose function template is more specialized
7362 // than the function template of F1 according to the partial
7363 // ordering rules of 14.5.5.2.
7364
7365 // The algorithm specified above is quadratic. We instead use a
7366 // two-pass algorithm (similar to the one used to identify the
7367 // best viable function in an overload set) that identifies the
7368 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00007369
7370 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7371 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7372 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007373
John McCallc373d482010-01-27 01:50:18 +00007374 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007375 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7376 TPOC_Other, 0, SourceExpr->getLocStart(),
7377 S.PDiag(),
7378 S.PDiag(diag::err_addr_ovl_ambiguous)
7379 << Matches[0].second->getDeclName(),
7380 S.PDiag(diag::note_ovl_candidate)
7381 << (unsigned) oc_function_template,
7382 Complain);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007383
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007384 if (Result != MatchesCopy.end()) {
7385 // Make it the first and only element
7386 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7387 Matches[0].second = cast<FunctionDecl>(*Result);
7388 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00007389 }
7390 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007391
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007392 void EliminateAllTemplateMatches() {
7393 // [...] any function template specializations in the set are
7394 // eliminated if the set also contains a non-template function, [...]
7395 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7396 if (Matches[I].second->getPrimaryTemplate() == 0)
7397 ++I;
7398 else {
7399 Matches[I] = Matches[--N];
7400 Matches.set_size(N);
7401 }
7402 }
7403 }
7404
7405public:
7406 void ComplainNoMatchesFound() const {
7407 assert(Matches.empty());
7408 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7409 << OvlExpr->getName() << TargetFunctionType
7410 << OvlExpr->getSourceRange();
7411 S.NoteAllOverloadCandidates(OvlExpr);
7412 }
7413
7414 bool IsInvalidFormOfPointerToMemberFunction() const {
7415 return TargetTypeIsNonStaticMemberFunction &&
7416 !OvlExprInfo.HasFormOfMemberPointer;
7417 }
7418
7419 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7420 // TODO: Should we condition this on whether any functions might
7421 // have matched, or is it more appropriate to do that in callers?
7422 // TODO: a fixit wouldn't hurt.
7423 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7424 << TargetType << OvlExpr->getSourceRange();
7425 }
7426
7427 void ComplainOfInvalidConversion() const {
7428 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7429 << OvlExpr->getName() << TargetType;
7430 }
7431
7432 void ComplainMultipleMatchesFound() const {
7433 assert(Matches.size() > 1);
7434 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7435 << OvlExpr->getName()
7436 << OvlExpr->getSourceRange();
7437 S.NoteAllOverloadCandidates(OvlExpr);
7438 }
7439
7440 int getNumMatches() const { return Matches.size(); }
7441
7442 FunctionDecl* getMatchingFunctionDecl() const {
7443 if (Matches.size() != 1) return 0;
7444 return Matches[0].second;
7445 }
7446
7447 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7448 if (Matches.size() != 1) return 0;
7449 return &Matches[0].first;
7450 }
7451};
7452
7453/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7454/// an overloaded function (C++ [over.over]), where @p From is an
7455/// expression with overloaded function type and @p ToType is the type
7456/// we're trying to resolve to. For example:
7457///
7458/// @code
7459/// int f(double);
7460/// int f(int);
7461///
7462/// int (*pfd)(double) = f; // selects f(double)
7463/// @endcode
7464///
7465/// This routine returns the resulting FunctionDecl if it could be
7466/// resolved, and NULL otherwise. When @p Complain is true, this
7467/// routine will emit diagnostics if there is an error.
7468FunctionDecl *
7469Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7470 bool Complain,
7471 DeclAccessPair &FoundResult) {
7472
7473 assert(AddressOfExpr->getType() == Context.OverloadTy);
7474
7475 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7476 int NumMatches = Resolver.getNumMatches();
7477 FunctionDecl* Fn = 0;
7478 if ( NumMatches == 0 && Complain) {
7479 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7480 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7481 else
7482 Resolver.ComplainNoMatchesFound();
7483 }
7484 else if (NumMatches > 1 && Complain)
7485 Resolver.ComplainMultipleMatchesFound();
7486 else if (NumMatches == 1) {
7487 Fn = Resolver.getMatchingFunctionDecl();
7488 assert(Fn);
7489 FoundResult = *Resolver.getMatchingFunctionAccessPair();
7490 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00007491 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007492 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00007493 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007494
7495 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00007496}
7497
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007498/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00007499/// resolve that overloaded function expression down to a single function.
7500///
7501/// This routine can only resolve template-ids that refer to a single function
7502/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007503/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00007504/// as described in C++0x [temp.arg.explicit]p3.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007505FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From,
7506 bool Complain,
7507 DeclAccessPair* FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00007508 // C++ [over.over]p1:
7509 // [...] [Note: any redundant set of parentheses surrounding the
7510 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00007511 // C++ [over.over]p1:
7512 // [...] The overloaded function name can be preceded by the &
7513 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00007514 if (From->getType() != Context.OverloadTy)
7515 return 0;
7516
John McCall9c72c602010-08-27 09:08:28 +00007517 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007518
Douglas Gregor4b52e252009-12-21 23:17:24 +00007519 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00007520 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00007521 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00007522
7523 TemplateArgumentListInfo ExplicitTemplateArgs;
7524 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007525
Douglas Gregor4b52e252009-12-21 23:17:24 +00007526 // Look through all of the overloaded functions, searching for one
7527 // whose type matches exactly.
7528 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00007529 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7530 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00007531 // C++0x [temp.arg.explicit]p3:
7532 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007533 // where deduction is not done, if a template argument list is
7534 // specified and it, along with any default template arguments,
7535 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00007536 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00007537 FunctionTemplateDecl *FunctionTemplate
7538 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007539
Douglas Gregor4b52e252009-12-21 23:17:24 +00007540 // C++ [over.over]p2:
7541 // If the name is a function template, template argument deduction is
7542 // done (14.8.2.2), and if the argument deduction succeeds, the
7543 // resulting template argument list is used to generate a single
7544 // function template specialization, which is added to the set of
7545 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00007546 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00007547 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00007548 if (TemplateDeductionResult Result
7549 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7550 Specialization, Info)) {
7551 // FIXME: make a note of the failed deduction for diagnostics.
7552 (void)Result;
7553 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007554 }
7555
Douglas Gregor4b52e252009-12-21 23:17:24 +00007556 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007557 if (Matched) {
7558 if (FoundResult)
7559 *FoundResult = DeclAccessPair();
7560
7561 if (Complain) {
7562 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
7563 << OvlExpr->getName();
7564 NoteAllOverloadCandidates(OvlExpr);
7565 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00007566 return 0;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007567 }
7568
7569 if ((Matched = Specialization) && FoundResult)
7570 *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00007571 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007572
Douglas Gregor4b52e252009-12-21 23:17:24 +00007573 return Matched;
7574}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007575
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007576
7577
7578
7579// Resolve and fix an overloaded expression that
7580// can be resolved because it identifies a single function
7581// template specialization
7582// Last three arguments should only be supplied if Complain = true
7583ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
7584 Expr *SrcExpr, bool DoFunctionPointerConverion, bool Complain,
7585 const SourceRange& OpRangeForComplaining,
7586 QualType DestTypeForComplaining,
7587 unsigned DiagIDForComplaining ) {
7588
7589 assert(SrcExpr->getType() == Context.OverloadTy);
7590
7591 DeclAccessPair Found;
John Wiegley429bb272011-04-08 18:41:53 +00007592 ExprResult SingleFunctionExpression;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007593 if (FunctionDecl* Fn = ResolveSingleFunctionTemplateSpecialization(
7594 SrcExpr, false, // false -> Complain
7595 &Found)) {
7596 if (!DiagnoseUseOfDecl(Fn, SrcExpr->getSourceRange().getBegin())) {
7597 // mark the expression as resolved to Fn
John Wiegley429bb272011-04-08 18:41:53 +00007598 SingleFunctionExpression = Owned(FixOverloadedFunctionReference(SrcExpr,
7599 Found, Fn));
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007600 if (DoFunctionPointerConverion)
John Wiegley429bb272011-04-08 18:41:53 +00007601 SingleFunctionExpression =
7602 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007603 }
7604 }
John Wiegley429bb272011-04-08 18:41:53 +00007605 if (!SingleFunctionExpression.isUsable()) {
Douglas Gregordb2eae62011-03-16 19:16:25 +00007606 if (Complain) {
7607 OverloadExpr* oe = OverloadExpr::find(SrcExpr).Expression;
7608 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
7609 << oe->getName() << DestTypeForComplaining << OpRangeForComplaining
7610 << oe->getQualifierLoc().getSourceRange();
7611 NoteAllOverloadCandidates(SrcExpr);
7612 }
7613 return ExprError();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007614 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00007615
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007616 return SingleFunctionExpression;
7617}
7618
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007619/// \brief Add a single candidate to the overload set.
7620static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00007621 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00007622 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007623 Expr **Args, unsigned NumArgs,
7624 OverloadCandidateSet &CandidateSet,
7625 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00007626 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00007627 if (isa<UsingShadowDecl>(Callee))
7628 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7629
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007630 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00007631 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00007632 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00007633 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007634 return;
John McCallba135432009-11-21 08:51:07 +00007635 }
7636
7637 if (FunctionTemplateDecl *FuncTemplate
7638 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00007639 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7640 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00007641 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00007642 return;
7643 }
7644
7645 assert(false && "unhandled case in overloaded call candidate");
7646
7647 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007648}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007649
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007650/// \brief Add the overload candidates named by callee and/or found by argument
7651/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00007652void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007653 Expr **Args, unsigned NumArgs,
7654 OverloadCandidateSet &CandidateSet,
7655 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00007656
7657#ifndef NDEBUG
7658 // Verify that ArgumentDependentLookup is consistent with the rules
7659 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007660 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007661 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7662 // and let Y be the lookup set produced by argument dependent
7663 // lookup (defined as follows). If X contains
7664 //
7665 // -- a declaration of a class member, or
7666 //
7667 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00007668 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007669 //
7670 // -- a declaration that is neither a function or a function
7671 // template
7672 //
7673 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00007674
John McCall3b4294e2009-12-16 12:17:52 +00007675 if (ULE->requiresADL()) {
7676 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7677 E = ULE->decls_end(); I != E; ++I) {
7678 assert(!(*I)->getDeclContext()->isRecord());
7679 assert(isa<UsingShadowDecl>(*I) ||
7680 !(*I)->getDeclContext()->isFunctionOrMethod());
7681 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00007682 }
7683 }
7684#endif
7685
John McCall3b4294e2009-12-16 12:17:52 +00007686 // It would be nice to avoid this copy.
7687 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00007688 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00007689 if (ULE->hasExplicitTemplateArgs()) {
7690 ULE->copyTemplateArgumentsInto(TABuffer);
7691 ExplicitTemplateArgs = &TABuffer;
7692 }
7693
7694 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7695 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00007696 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007697 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007698 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00007699
John McCall3b4294e2009-12-16 12:17:52 +00007700 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00007701 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7702 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007703 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007704 CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00007705 PartialOverloading,
7706 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007707}
John McCall578b69b2009-12-16 08:11:27 +00007708
7709/// Attempts to recover from a call where no functions were found.
7710///
7711/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00007712static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00007713BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00007714 UnresolvedLookupExpr *ULE,
7715 SourceLocation LParenLoc,
7716 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00007717 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00007718
7719 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00007720 SS.Adopt(ULE->getQualifierLoc());
John McCall578b69b2009-12-16 08:11:27 +00007721
John McCall3b4294e2009-12-16 12:17:52 +00007722 TemplateArgumentListInfo TABuffer;
7723 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7724 if (ULE->hasExplicitTemplateArgs()) {
7725 ULE->copyTemplateArgumentsInto(TABuffer);
7726 ExplicitTemplateArgs = &TABuffer;
7727 }
7728
John McCall578b69b2009-12-16 08:11:27 +00007729 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7730 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00007731 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallf312b1e2010-08-26 23:41:50 +00007732 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00007733
John McCall3b4294e2009-12-16 12:17:52 +00007734 assert(!R.empty() && "lookup results empty despite recovery");
7735
7736 // Build an implicit member call if appropriate. Just drop the
7737 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00007738 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00007739 if ((*R.begin())->isCXXClassMember())
Chandler Carruth6df868e2010-12-12 08:17:55 +00007740 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7741 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00007742 else if (ExplicitTemplateArgs)
7743 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7744 else
7745 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7746
7747 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007748 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00007749
7750 // This shouldn't cause an infinite loop because we're giving it
7751 // an expression with non-empty lookup results, which should never
7752 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00007753 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00007754 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00007755}
Douglas Gregord7a95972010-06-08 17:35:15 +00007756
Douglas Gregorf6b89692008-11-26 05:54:23 +00007757/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00007758/// (which eventually refers to the declaration Func) and the call
7759/// arguments Args/NumArgs, attempt to resolve the function call down
7760/// to a specific function. If overload resolution succeeds, returns
7761/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00007762/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00007763/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00007764ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00007765Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00007766 SourceLocation LParenLoc,
7767 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00007768 SourceLocation RParenLoc,
7769 Expr *ExecConfig) {
John McCall3b4294e2009-12-16 12:17:52 +00007770#ifndef NDEBUG
7771 if (ULE->requiresADL()) {
7772 // To do ADL, we must have found an unqualified name.
7773 assert(!ULE->getQualifier() && "qualified name with ADL");
7774
7775 // We don't perform ADL for implicit declarations of builtins.
7776 // Verify that this was correctly set up.
7777 FunctionDecl *F;
7778 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7779 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7780 F->getBuiltinID() && F->isImplicit())
7781 assert(0 && "performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007782
John McCall3b4294e2009-12-16 12:17:52 +00007783 // We don't perform ADL in C.
7784 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00007785 } else
7786 assert(!ULE->isStdAssociatedNamespace() &&
7787 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00007788#endif
7789
John McCall5769d612010-02-08 23:07:23 +00007790 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00007791
John McCall3b4294e2009-12-16 12:17:52 +00007792 // Add the functions denoted by the callee to the set of candidate
7793 // functions, including those from argument-dependent lookup.
7794 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00007795
7796 // If we found nothing, try to recover.
7797 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7798 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00007799 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00007800 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00007801 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00007802
Douglas Gregorf6b89692008-11-26 05:54:23 +00007803 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007804 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00007805 case OR_Success: {
7806 FunctionDecl *FDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00007807 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCall9aa472c2010-03-19 07:35:19 +00007808 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007809 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7810 ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00007811 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00007812 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
7813 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00007814 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00007815
7816 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00007817 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00007818 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00007819 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007820 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00007821 break;
7822
7823 case OR_Ambiguous:
7824 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00007825 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007826 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00007827 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007828
7829 case OR_Deleted:
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00007830 {
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00007831 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7832 << Best->Function->isDeleted()
7833 << ULE->getName()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00007834 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00007835 << Fn->getSourceRange();
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00007836 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7837 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007838 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00007839 }
7840
Douglas Gregorff331c12010-07-25 18:17:45 +00007841 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00007842 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00007843}
7844
John McCall6e266892010-01-26 03:27:55 +00007845static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00007846 return Functions.size() > 1 ||
7847 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7848}
7849
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007850/// \brief Create a unary operation that may resolve to an overloaded
7851/// operator.
7852///
7853/// \param OpLoc The location of the operator itself (e.g., '*').
7854///
7855/// \param OpcIn The UnaryOperator::Opcode that describes this
7856/// operator.
7857///
7858/// \param Functions The set of non-member functions that will be
7859/// considered by overload resolution. The caller needs to build this
7860/// set based on the context using, e.g.,
7861/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7862/// set should not contain any member functions; those will be added
7863/// by CreateOverloadedUnaryOp().
7864///
7865/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00007866ExprResult
John McCall6e266892010-01-26 03:27:55 +00007867Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7868 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00007869 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007870 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007871
7872 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7873 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7874 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00007875 // TODO: provide better source location info.
7876 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007877
John Wiegley429bb272011-04-08 18:41:53 +00007878 if (Input->getObjectKind() == OK_ObjCProperty) {
7879 ExprResult Result = ConvertPropertyForRValue(Input);
7880 if (Result.isInvalid())
7881 return ExprError();
7882 Input = Result.take();
7883 }
John McCall0e800c92010-12-04 08:14:53 +00007884
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007885 Expr *Args[2] = { Input, 0 };
7886 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00007887
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007888 // For post-increment and post-decrement, add the implicit '0' as
7889 // the second argument, so that we know this is a post-increment or
7890 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00007891 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007892 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007893 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7894 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007895 NumArgs = 2;
7896 }
7897
7898 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00007899 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00007900 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007901 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00007902 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007903 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00007904 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007905
John McCallc373d482010-01-27 01:50:18 +00007906 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00007907 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00007908 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00007909 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007910 /*ADL*/ true, IsOverloaded(Fns),
7911 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007912 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor4c9be892011-02-28 20:01:57 +00007913 &Args[0], NumArgs,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007914 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007915 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007916 OpLoc));
7917 }
7918
7919 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007920 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007921
7922 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00007923 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007924
7925 // Add operator candidates that are member functions.
7926 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7927
John McCall6e266892010-01-26 03:27:55 +00007928 // Add candidates from ADL.
7929 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00007930 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00007931 /*ExplicitTemplateArgs*/ 0,
7932 CandidateSet);
7933
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007934 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00007935 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007936
7937 // Perform overload resolution.
7938 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007939 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007940 case OR_Success: {
7941 // We found a built-in operator or an overloaded operator.
7942 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00007943
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007944 if (FnDecl) {
7945 // We matched an overloaded operator. Build a call to that
7946 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00007947
Chandler Carruth25ca4212011-02-25 19:41:05 +00007948 MarkDeclarationReferenced(OpLoc, FnDecl);
7949
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007950 // Convert the arguments.
7951 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00007952 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007953
John Wiegley429bb272011-04-08 18:41:53 +00007954 ExprResult InputRes =
7955 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7956 Best->FoundDecl, Method);
7957 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007958 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00007959 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007960 } else {
7961 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007962 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00007963 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007964 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00007965 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007966 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00007967 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00007968 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007969 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00007970 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007971 }
7972
John McCallb697e082010-05-06 18:15:07 +00007973 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7974
John McCallf89e55a2010-11-18 06:31:45 +00007975 // Determine the result type.
7976 QualType ResultTy = FnDecl->getResultType();
7977 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7978 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00007979
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007980 // Build the actual expression node.
John Wiegley429bb272011-04-08 18:41:53 +00007981 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl);
7982 if (FnExpr.isInvalid())
7983 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00007984
Eli Friedman4c3b8962009-11-18 03:58:17 +00007985 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00007986 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00007987 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00007988 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00007989
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007990 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00007991 FnDecl))
7992 return ExprError();
7993
John McCall9ae2f072010-08-23 23:25:46 +00007994 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007995 } else {
7996 // We matched a built-in operator. Convert the arguments, then
7997 // break out so that we will build the appropriate built-in
7998 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00007999 ExprResult InputRes =
8000 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8001 Best->Conversions[0], AA_Passing);
8002 if (InputRes.isInvalid())
8003 return ExprError();
8004 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008005 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008006 }
John Wiegley429bb272011-04-08 18:41:53 +00008007 }
8008
8009 case OR_No_Viable_Function:
8010 // No viable function; fall through to handling this as a
8011 // built-in operator, which will produce an error message for us.
8012 break;
8013
8014 case OR_Ambiguous:
8015 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8016 << UnaryOperator::getOpcodeStr(Opc)
8017 << Input->getType()
8018 << Input->getSourceRange();
8019 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
8020 Args, NumArgs,
8021 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8022 return ExprError();
8023
8024 case OR_Deleted:
8025 Diag(OpLoc, diag::err_ovl_deleted_oper)
8026 << Best->Function->isDeleted()
8027 << UnaryOperator::getOpcodeStr(Opc)
8028 << getDeletedOrUnavailableSuffix(Best->Function)
8029 << Input->getSourceRange();
8030 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8031 return ExprError();
8032 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008033
8034 // Either we found no viable overloaded operator or we matched a
8035 // built-in operator. In either case, fall through to trying to
8036 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00008037 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008038}
8039
Douglas Gregor063daf62009-03-13 18:40:31 +00008040/// \brief Create a binary operation that may resolve to an overloaded
8041/// operator.
8042///
8043/// \param OpLoc The location of the operator itself (e.g., '+').
8044///
8045/// \param OpcIn The BinaryOperator::Opcode that describes this
8046/// operator.
8047///
8048/// \param Functions The set of non-member functions that will be
8049/// considered by overload resolution. The caller needs to build this
8050/// set based on the context using, e.g.,
8051/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8052/// set should not contain any member functions; those will be added
8053/// by CreateOverloadedBinOp().
8054///
8055/// \param LHS Left-hand argument.
8056/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00008057ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00008058Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00008059 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00008060 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00008061 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00008062 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008063 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00008064
8065 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8066 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8067 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8068
8069 // If either side is type-dependent, create an appropriate dependent
8070 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008071 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00008072 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008073 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008074 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00008075 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008076 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +00008077 Context.DependentTy,
8078 VK_RValue, OK_Ordinary,
8079 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008080
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008081 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8082 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008083 VK_LValue,
8084 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008085 Context.DependentTy,
8086 Context.DependentTy,
8087 OpLoc));
8088 }
John McCall6e266892010-01-26 03:27:55 +00008089
8090 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00008091 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00008092 // TODO: provide better source location info in DNLoc component.
8093 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00008094 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +00008095 = UnresolvedLookupExpr::Create(Context, NamingClass,
8096 NestedNameSpecifierLoc(), OpNameInfo,
8097 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00008098 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00008099 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00008100 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00008101 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008102 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +00008103 OpLoc));
8104 }
8105
John McCall0e800c92010-12-04 08:14:53 +00008106 // Always do property rvalue conversions on the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00008107 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8108 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8109 if (Result.isInvalid())
8110 return ExprError();
8111 Args[1] = Result.take();
8112 }
John McCall0e800c92010-12-04 08:14:53 +00008113
8114 // The LHS is more complicated.
8115 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8116
8117 // There's a tension for assignment operators between primitive
8118 // property assignment and the overloaded operators.
8119 if (BinaryOperator::isAssignmentOp(Opc)) {
8120 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8121
8122 // Is the property "logically" settable?
8123 bool Settable = (PRE->isExplicitProperty() ||
8124 PRE->getImplicitPropertySetter());
8125
8126 // To avoid gratuitously inventing semantics, use the primitive
8127 // unless it isn't. Thoughts in case we ever really care:
8128 // - If the property isn't logically settable, we have to
8129 // load and hope.
8130 // - If the property is settable and this is simple assignment,
8131 // we really should use the primitive.
8132 // - If the property is settable, then we could try overloading
8133 // on a generic lvalue of the appropriate type; if it works
8134 // out to a builtin candidate, we would do that same operation
8135 // on the property, and otherwise just error.
8136 if (Settable)
8137 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8138 }
8139
John Wiegley429bb272011-04-08 18:41:53 +00008140 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8141 if (Result.isInvalid())
8142 return ExprError();
8143 Args[0] = Result.take();
John McCall0e800c92010-12-04 08:14:53 +00008144 }
Douglas Gregor063daf62009-03-13 18:40:31 +00008145
Sebastian Redl275c2b42009-11-18 23:10:33 +00008146 // If this is the assignment operator, we only perform overload resolution
8147 // if the left-hand side is a class or enumeration type. This is actually
8148 // a hack. The standard requires that we do overload resolution between the
8149 // various built-in candidates, but as DR507 points out, this can lead to
8150 // problems. So we do it this way, which pretty much follows what GCC does.
8151 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00008152 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008153 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00008154
John McCall0e800c92010-12-04 08:14:53 +00008155 // If this is the .* operator, which is not overloadable, just
8156 // create a built-in binary operator.
8157 if (Opc == BO_PtrMemD)
8158 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8159
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008160 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00008161 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00008162
8163 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00008164 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00008165
8166 // Add operator candidates that are member functions.
8167 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8168
John McCall6e266892010-01-26 03:27:55 +00008169 // Add candidates from ADL.
8170 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8171 Args, 2,
8172 /*ExplicitTemplateArgs*/ 0,
8173 CandidateSet);
8174
Douglas Gregor063daf62009-03-13 18:40:31 +00008175 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00008176 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00008177
8178 // Perform overload resolution.
8179 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008180 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00008181 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00008182 // We found a built-in operator or an overloaded operator.
8183 FunctionDecl *FnDecl = Best->Function;
8184
8185 if (FnDecl) {
8186 // We matched an overloaded operator. Build a call to that
8187 // operator.
8188
Chandler Carruth25ca4212011-02-25 19:41:05 +00008189 MarkDeclarationReferenced(OpLoc, FnDecl);
8190
Douglas Gregor063daf62009-03-13 18:40:31 +00008191 // Convert the arguments.
8192 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00008193 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00008194 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00008195
Chandler Carruth6df868e2010-12-12 08:17:55 +00008196 ExprResult Arg1 =
8197 PerformCopyInitialization(
8198 InitializedEntity::InitializeParameter(Context,
8199 FnDecl->getParamDecl(0)),
8200 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008201 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00008202 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008203
John Wiegley429bb272011-04-08 18:41:53 +00008204 ExprResult Arg0 =
8205 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8206 Best->FoundDecl, Method);
8207 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008208 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008209 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008210 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00008211 } else {
8212 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +00008213 ExprResult Arg0 = PerformCopyInitialization(
8214 InitializedEntity::InitializeParameter(Context,
8215 FnDecl->getParamDecl(0)),
8216 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008217 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00008218 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008219
Chandler Carruth6df868e2010-12-12 08:17:55 +00008220 ExprResult Arg1 =
8221 PerformCopyInitialization(
8222 InitializedEntity::InitializeParameter(Context,
8223 FnDecl->getParamDecl(1)),
8224 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008225 if (Arg1.isInvalid())
8226 return ExprError();
8227 Args[0] = LHS = Arg0.takeAs<Expr>();
8228 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00008229 }
8230
John McCallb697e082010-05-06 18:15:07 +00008231 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8232
John McCallf89e55a2010-11-18 06:31:45 +00008233 // Determine the result type.
8234 QualType ResultTy = FnDecl->getResultType();
8235 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8236 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00008237
8238 // Build the actual expression node.
John Wiegley429bb272011-04-08 18:41:53 +00008239 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
8240 if (FnExpr.isInvalid())
8241 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +00008242
John McCall9ae2f072010-08-23 23:25:46 +00008243 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00008244 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00008245 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008246
8247 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00008248 FnDecl))
8249 return ExprError();
8250
John McCall9ae2f072010-08-23 23:25:46 +00008251 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00008252 } else {
8253 // We matched a built-in operator. Convert the arguments, then
8254 // break out so that we will build the appropriate built-in
8255 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00008256 ExprResult ArgsRes0 =
8257 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8258 Best->Conversions[0], AA_Passing);
8259 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00008260 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008261 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00008262
John Wiegley429bb272011-04-08 18:41:53 +00008263 ExprResult ArgsRes1 =
8264 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8265 Best->Conversions[1], AA_Passing);
8266 if (ArgsRes1.isInvalid())
8267 return ExprError();
8268 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00008269 break;
8270 }
8271 }
8272
Douglas Gregor33074752009-09-30 21:46:01 +00008273 case OR_No_Viable_Function: {
8274 // C++ [over.match.oper]p9:
8275 // If the operator is the operator , [...] and there are no
8276 // viable functions, then the operator is assumed to be the
8277 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00008278 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00008279 break;
8280
Chandler Carruth6df868e2010-12-12 08:17:55 +00008281 // For class as left operand for assignment or compound assigment
8282 // operator do not fall through to handling in built-in, but report that
8283 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00008284 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008285 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00008286 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00008287 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8288 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008289 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00008290 } else {
8291 // No viable function; try to create a built-in operation, which will
8292 // produce an error. Then, show the non-viable candidates.
8293 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00008294 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008295 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +00008296 "C++ binary operator overloading is missing candidates!");
8297 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00008298 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8299 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00008300 return move(Result);
8301 }
Douglas Gregor063daf62009-03-13 18:40:31 +00008302
8303 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00008304 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +00008305 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00008306 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008307 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008308 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8309 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00008310 return ExprError();
8311
8312 case OR_Deleted:
8313 Diag(OpLoc, diag::err_ovl_deleted_oper)
8314 << Best->Function->isDeleted()
8315 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00008316 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008317 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008318 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00008319 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00008320 }
Douglas Gregor063daf62009-03-13 18:40:31 +00008321
Douglas Gregor33074752009-09-30 21:46:01 +00008322 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008323 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00008324}
8325
John McCall60d7b3a2010-08-24 06:29:42 +00008326ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +00008327Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8328 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +00008329 Expr *Base, Expr *Idx) {
8330 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +00008331 DeclarationName OpName =
8332 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8333
8334 // If either side is type-dependent, create an appropriate dependent
8335 // expression.
8336 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8337
John McCallc373d482010-01-27 01:50:18 +00008338 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00008339 // CHECKME: no 'operator' keyword?
8340 DeclarationNameInfo OpNameInfo(OpName, LLoc);
8341 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00008342 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00008343 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00008344 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00008345 /*ADL*/ true, /*Overloaded*/ false,
8346 UnresolvedSetIterator(),
8347 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00008348 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00008349
Sebastian Redlf322ed62009-10-29 20:17:01 +00008350 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8351 Args, 2,
8352 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008353 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +00008354 RLoc));
8355 }
8356
John Wiegley429bb272011-04-08 18:41:53 +00008357 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8358 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8359 if (Result.isInvalid())
8360 return ExprError();
8361 Args[0] = Result.take();
8362 }
8363 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8364 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8365 if (Result.isInvalid())
8366 return ExprError();
8367 Args[1] = Result.take();
8368 }
John McCall0e800c92010-12-04 08:14:53 +00008369
Sebastian Redlf322ed62009-10-29 20:17:01 +00008370 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00008371 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008372
8373 // Subscript can only be overloaded as a member function.
8374
8375 // Add operator candidates that are member functions.
8376 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8377
8378 // Add builtin operator candidates.
8379 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8380
8381 // Perform overload resolution.
8382 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008383 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00008384 case OR_Success: {
8385 // We found a built-in operator or an overloaded operator.
8386 FunctionDecl *FnDecl = Best->Function;
8387
8388 if (FnDecl) {
8389 // We matched an overloaded operator. Build a call to that
8390 // operator.
8391
Chandler Carruth25ca4212011-02-25 19:41:05 +00008392 MarkDeclarationReferenced(LLoc, FnDecl);
8393
John McCall9aa472c2010-03-19 07:35:19 +00008394 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008395 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00008396
Sebastian Redlf322ed62009-10-29 20:17:01 +00008397 // Convert the arguments.
8398 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +00008399 ExprResult Arg0 =
8400 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8401 Best->FoundDecl, Method);
8402 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +00008403 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008404 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +00008405
Anders Carlsson38f88ab2010-01-29 18:37:50 +00008406 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00008407 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +00008408 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00008409 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +00008410 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008411 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +00008412 Owned(Args[1]));
8413 if (InputInit.isInvalid())
8414 return ExprError();
8415
8416 Args[1] = InputInit.takeAs<Expr>();
8417
Sebastian Redlf322ed62009-10-29 20:17:01 +00008418 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +00008419 QualType ResultTy = FnDecl->getResultType();
8420 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8421 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008422
8423 // Build the actual expression node.
John Wiegley429bb272011-04-08 18:41:53 +00008424 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
8425 if (FnExpr.isInvalid())
8426 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00008427
John McCall9ae2f072010-08-23 23:25:46 +00008428 CXXOperatorCallExpr *TheCall =
8429 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley429bb272011-04-08 18:41:53 +00008430 FnExpr.take(), Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +00008431 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008432
John McCall9ae2f072010-08-23 23:25:46 +00008433 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +00008434 FnDecl))
8435 return ExprError();
8436
John McCall9ae2f072010-08-23 23:25:46 +00008437 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008438 } else {
8439 // We matched a built-in operator. Convert the arguments, then
8440 // break out so that we will build the appropriate built-in
8441 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00008442 ExprResult ArgsRes0 =
8443 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8444 Best->Conversions[0], AA_Passing);
8445 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +00008446 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008447 Args[0] = ArgsRes0.take();
8448
8449 ExprResult ArgsRes1 =
8450 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8451 Best->Conversions[1], AA_Passing);
8452 if (ArgsRes1.isInvalid())
8453 return ExprError();
8454 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +00008455
8456 break;
8457 }
8458 }
8459
8460 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00008461 if (CandidateSet.empty())
8462 Diag(LLoc, diag::err_ovl_no_oper)
8463 << Args[0]->getType() << /*subscript*/ 0
8464 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8465 else
8466 Diag(LLoc, diag::err_ovl_no_viable_subscript)
8467 << Args[0]->getType()
8468 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008469 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8470 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +00008471 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00008472 }
8473
8474 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00008475 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008476 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +00008477 << Args[0]->getType() << Args[1]->getType()
8478 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008479 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8480 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008481 return ExprError();
8482
8483 case OR_Deleted:
8484 Diag(LLoc, diag::err_ovl_deleted_oper)
8485 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00008486 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +00008487 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008488 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8489 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008490 return ExprError();
8491 }
8492
8493 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +00008494 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008495}
8496
Douglas Gregor88a35142008-12-22 05:46:06 +00008497/// BuildCallToMemberFunction - Build a call to a member
8498/// function. MemExpr is the expression that refers to the member
8499/// function (and includes the object parameter), Args/NumArgs are the
8500/// arguments to the function call (not including the object
8501/// parameter). The caller needs to validate that the member
8502/// expression refers to a member function or an overloaded member
8503/// function.
John McCall60d7b3a2010-08-24 06:29:42 +00008504ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00008505Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
8506 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +00008507 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor88a35142008-12-22 05:46:06 +00008508 // Dig out the member expression. This holds both the object
8509 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00008510 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008511
John McCall129e2df2009-11-30 22:42:35 +00008512 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00008513 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00008514 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00008515 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00008516 if (isa<MemberExpr>(NakedMemExpr)) {
8517 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00008518 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00008519 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00008520 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00008521 } else {
8522 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00008523 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008524
John McCall701c89e2009-12-03 04:06:58 +00008525 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00008526 Expr::Classification ObjectClassification
8527 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
8528 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +00008529
Douglas Gregor88a35142008-12-22 05:46:06 +00008530 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00008531 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00008532
John McCallaa81e162009-12-01 22:10:20 +00008533 // FIXME: avoid copy.
8534 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8535 if (UnresExpr->hasExplicitTemplateArgs()) {
8536 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8537 TemplateArgs = &TemplateArgsBuffer;
8538 }
8539
John McCall129e2df2009-11-30 22:42:35 +00008540 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
8541 E = UnresExpr->decls_end(); I != E; ++I) {
8542
John McCall701c89e2009-12-03 04:06:58 +00008543 NamedDecl *Func = *I;
8544 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
8545 if (isa<UsingShadowDecl>(Func))
8546 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
8547
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00008548
Francois Pichetdbee3412011-01-18 05:04:39 +00008549 // Microsoft supports direct constructor calls.
8550 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
8551 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
8552 CandidateSet);
8553 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00008554 // If explicit template arguments were provided, we can't call a
8555 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00008556 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00008557 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008558
John McCall9aa472c2010-03-19 07:35:19 +00008559 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008560 ObjectClassification,
8561 Args, NumArgs, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00008562 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00008563 } else {
John McCall129e2df2009-11-30 22:42:35 +00008564 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00008565 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008566 ObjectType, ObjectClassification,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00008567 Args, NumArgs, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +00008568 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00008569 }
Douglas Gregordec06662009-08-21 18:42:58 +00008570 }
Mike Stump1eb44332009-09-09 15:08:12 +00008571
John McCall129e2df2009-11-30 22:42:35 +00008572 DeclarationName DeclName = UnresExpr->getMemberName();
8573
Douglas Gregor88a35142008-12-22 05:46:06 +00008574 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008575 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +00008576 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00008577 case OR_Success:
8578 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth25ca4212011-02-25 19:41:05 +00008579 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +00008580 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00008581 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008582 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00008583 break;
8584
8585 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00008586 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00008587 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00008588 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008589 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00008590 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00008591 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00008592
8593 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00008594 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00008595 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008596 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00008597 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00008598 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008599
8600 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00008601 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008602 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00008603 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00008604 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00008605 << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008606 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008607 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00008608 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00008609 }
8610
John McCall6bb80172010-03-30 21:47:33 +00008611 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00008612
John McCallaa81e162009-12-01 22:10:20 +00008613 // If overload resolution picked a static member, build a
8614 // non-member call based on that function.
8615 if (Method->isStatic()) {
8616 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8617 Args, NumArgs, RParenLoc);
8618 }
8619
John McCall129e2df2009-11-30 22:42:35 +00008620 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00008621 }
8622
John McCallf89e55a2010-11-18 06:31:45 +00008623 QualType ResultType = Method->getResultType();
8624 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8625 ResultType = ResultType.getNonLValueExprType(Context);
8626
Douglas Gregor88a35142008-12-22 05:46:06 +00008627 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008628 CXXMemberCallExpr *TheCall =
John McCall9ae2f072010-08-23 23:25:46 +00008629 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +00008630 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +00008631
Anders Carlssoneed3e692009-10-10 00:06:20 +00008632 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008633 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +00008634 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +00008635 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008636
Douglas Gregor88a35142008-12-22 05:46:06 +00008637 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00008638 // We only need to do this if there was actually an overload; otherwise
8639 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +00008640 if (!Method->isStatic()) {
8641 ExprResult ObjectArg =
8642 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
8643 FoundDecl, Method);
8644 if (ObjectArg.isInvalid())
8645 return ExprError();
8646 MemExpr->setBase(ObjectArg.take());
8647 }
Douglas Gregor88a35142008-12-22 05:46:06 +00008648
8649 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +00008650 const FunctionProtoType *Proto =
8651 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +00008652 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00008653 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00008654 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00008655
John McCall9ae2f072010-08-23 23:25:46 +00008656 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +00008657 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00008658
John McCall9ae2f072010-08-23 23:25:46 +00008659 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +00008660}
8661
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008662/// BuildCallToObjectOfClassType - Build a call to an object of class
8663/// type (C++ [over.call.object]), which can end up invoking an
8664/// overloaded function call operator (@c operator()) or performing a
8665/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +00008666ExprResult
John Wiegley429bb272011-04-08 18:41:53 +00008667Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +00008668 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008669 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008670 SourceLocation RParenLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00008671 ExprResult Object = Owned(Obj);
8672 if (Object.get()->getObjectKind() == OK_ObjCProperty) {
8673 Object = ConvertPropertyForRValue(Object.take());
8674 if (Object.isInvalid())
8675 return ExprError();
8676 }
John McCall0e800c92010-12-04 08:14:53 +00008677
John Wiegley429bb272011-04-08 18:41:53 +00008678 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
8679 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00008680
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008681 // C++ [over.call.object]p1:
8682 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00008683 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008684 // candidate functions includes at least the function call
8685 // operators of T. The function call operators of T are obtained by
8686 // ordinary lookup of the name operator() in the context of
8687 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00008688 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00008689 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00008690
John Wiegley429bb272011-04-08 18:41:53 +00008691 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008692 PDiag(diag::err_incomplete_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00008693 << Object.get()->getSourceRange()))
Douglas Gregor593564b2009-11-15 07:48:03 +00008694 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008695
John McCalla24dc2e2009-11-17 02:14:36 +00008696 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8697 LookupQualifiedName(R, Record->getDecl());
8698 R.suppressDiagnostics();
8699
Douglas Gregor593564b2009-11-15 07:48:03 +00008700 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00008701 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +00008702 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
8703 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00008704 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00008705 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008706
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008707 // C++ [over.call.object]p2:
8708 // In addition, for each conversion function declared in T of the
8709 // form
8710 //
8711 // operator conversion-type-id () cv-qualifier;
8712 //
8713 // where cv-qualifier is the same cv-qualification as, or a
8714 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00008715 // denotes the type "pointer to function of (P1,...,Pn) returning
8716 // R", or the type "reference to pointer to function of
8717 // (P1,...,Pn) returning R", or the type "reference to function
8718 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008719 // is also considered as a candidate function. Similarly,
8720 // surrogate call functions are added to the set of candidate
8721 // functions for each conversion function declared in an
8722 // accessible base class provided the function is not hidden
8723 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00008724 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00008725 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00008726 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00008727 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00008728 NamedDecl *D = *I;
8729 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8730 if (isa<UsingShadowDecl>(D))
8731 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008732
Douglas Gregor4a27d702009-10-21 06:18:39 +00008733 // Skip over templated conversion functions; they aren't
8734 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00008735 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00008736 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00008737
John McCall701c89e2009-12-03 04:06:58 +00008738 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00008739
Douglas Gregor4a27d702009-10-21 06:18:39 +00008740 // Strip the reference type (if any) and then the pointer type (if
8741 // any) to get down to what might be a function type.
8742 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8743 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8744 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008745
Douglas Gregor4a27d702009-10-21 06:18:39 +00008746 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00008747 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John Wiegley429bb272011-04-08 18:41:53 +00008748 Object.get(), Args, NumArgs, CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008749 }
Mike Stump1eb44332009-09-09 15:08:12 +00008750
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008751 // Perform overload resolution.
8752 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +00008753 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +00008754 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008755 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008756 // Overload resolution succeeded; we'll build the appropriate call
8757 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008758 break;
8759
8760 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00008761 if (CandidateSet.empty())
John Wiegley429bb272011-04-08 18:41:53 +00008762 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8763 << Object.get()->getType() << /*call*/ 1
8764 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +00008765 else
John Wiegley429bb272011-04-08 18:41:53 +00008766 Diag(Object.get()->getSourceRange().getBegin(),
John McCall1eb3e102010-01-07 02:04:15 +00008767 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00008768 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008769 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008770 break;
8771
8772 case OR_Ambiguous:
John Wiegley429bb272011-04-08 18:41:53 +00008773 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008774 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00008775 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008776 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008777 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008778
8779 case OR_Deleted:
John Wiegley429bb272011-04-08 18:41:53 +00008780 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008781 diag::err_ovl_deleted_object_call)
8782 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +00008783 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00008784 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +00008785 << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008786 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008787 break;
Mike Stump1eb44332009-09-09 15:08:12 +00008788 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008789
Douglas Gregorff331c12010-07-25 18:17:45 +00008790 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008791 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008792
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008793 if (Best->Function == 0) {
8794 // Since there is no function declaration, this is one of the
8795 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00008796 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008797 = cast<CXXConversionDecl>(
8798 Best->Conversions[0].UserDefined.ConversionFunction);
8799
John Wiegley429bb272011-04-08 18:41:53 +00008800 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008801 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00008802
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008803 // We selected one of the surrogate functions that converts the
8804 // object parameter to a function pointer. Perform the conversion
8805 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008806
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00008807 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00008808 // and then call it.
John Wiegley429bb272011-04-08 18:41:53 +00008809 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00008810 if (Call.isInvalid())
8811 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008812
Douglas Gregorf2ae5262011-01-20 00:18:04 +00008813 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008814 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008815 }
8816
Chandler Carruth25ca4212011-02-25 19:41:05 +00008817 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +00008818 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008819 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00008820
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008821 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8822 // that calls this method, using Object for the implicit object
8823 // parameter and passing along the remaining arguments.
8824 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +00008825 const FunctionProtoType *Proto =
8826 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008827
8828 unsigned NumArgsInProto = Proto->getNumArgs();
8829 unsigned NumArgsToCheck = NumArgs;
8830
8831 // Build the full argument list for the method call (the
8832 // implicit object parameter is placed at the beginning of the
8833 // list).
8834 Expr **MethodArgs;
8835 if (NumArgs < NumArgsInProto) {
8836 NumArgsToCheck = NumArgsInProto;
8837 MethodArgs = new Expr*[NumArgsInProto + 1];
8838 } else {
8839 MethodArgs = new Expr*[NumArgs + 1];
8840 }
John Wiegley429bb272011-04-08 18:41:53 +00008841 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008842 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8843 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00008844
John Wiegley429bb272011-04-08 18:41:53 +00008845 ExprResult NewFn = CreateFunctionRefExpr(*this, Method);
8846 if (NewFn.isInvalid())
8847 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008848
8849 // Once we've built TheCall, all of the expressions are properly
8850 // owned.
John McCallf89e55a2010-11-18 06:31:45 +00008851 QualType ResultTy = Method->getResultType();
8852 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8853 ResultTy = ResultTy.getNonLValueExprType(Context);
8854
John McCall9ae2f072010-08-23 23:25:46 +00008855 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00008856 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCall9ae2f072010-08-23 23:25:46 +00008857 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +00008858 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008859 delete [] MethodArgs;
8860
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008861 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +00008862 Method))
8863 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008864
Douglas Gregor518fda12009-01-13 05:10:00 +00008865 // We may have default arguments. If so, we need to allocate more
8866 // slots in the call for them.
8867 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00008868 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00008869 else if (NumArgs > NumArgsInProto)
8870 NumArgsToCheck = NumArgsInProto;
8871
Chris Lattner312531a2009-04-12 08:11:20 +00008872 bool IsError = false;
8873
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008874 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +00008875 ExprResult ObjRes =
8876 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
8877 Best->FoundDecl, Method);
8878 if (ObjRes.isInvalid())
8879 IsError = true;
8880 else
8881 Object = move(ObjRes);
8882 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +00008883
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008884 // Check the argument types.
8885 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008886 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00008887 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008888 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00008889
Douglas Gregor518fda12009-01-13 05:10:00 +00008890 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00008891
John McCall60d7b3a2010-08-24 06:29:42 +00008892 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +00008893 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00008894 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +00008895 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +00008896 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008897
Anders Carlsson3faa4862010-01-29 18:43:53 +00008898 IsError |= InputInit.isInvalid();
8899 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00008900 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00008901 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +00008902 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8903 if (DefArg.isInvalid()) {
8904 IsError = true;
8905 break;
8906 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008907
Douglas Gregord47c47d2009-11-09 19:27:57 +00008908 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00008909 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008910
8911 TheCall->setArg(i + 1, Arg);
8912 }
8913
8914 // If this is a variadic call, handle args passed through "...".
8915 if (Proto->isVariadic()) {
8916 // Promote the arguments (C99 6.5.2.2p7).
8917 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +00008918 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
8919 IsError |= Arg.isInvalid();
8920 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008921 }
8922 }
8923
Chris Lattner312531a2009-04-12 08:11:20 +00008924 if (IsError) return true;
8925
John McCall9ae2f072010-08-23 23:25:46 +00008926 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00008927 return true;
8928
John McCall182f7092010-08-24 06:09:16 +00008929 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008930}
8931
Douglas Gregor8ba10742008-11-20 16:27:02 +00008932/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00008933/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00008934/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +00008935ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008936Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008937 assert(Base->getType()->isRecordType() &&
8938 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00008939
John Wiegley429bb272011-04-08 18:41:53 +00008940 if (Base->getObjectKind() == OK_ObjCProperty) {
8941 ExprResult Result = ConvertPropertyForRValue(Base);
8942 if (Result.isInvalid())
8943 return ExprError();
8944 Base = Result.take();
8945 }
John McCall0e800c92010-12-04 08:14:53 +00008946
John McCall5769d612010-02-08 23:07:23 +00008947 SourceLocation Loc = Base->getExprLoc();
8948
Douglas Gregor8ba10742008-11-20 16:27:02 +00008949 // C++ [over.ref]p1:
8950 //
8951 // [...] An expression x->m is interpreted as (x.operator->())->m
8952 // for a class object x of type T if T::operator->() exists and if
8953 // the operator is selected as the best match function by the
8954 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +00008955 DeclarationName OpName =
8956 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00008957 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00008958 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008959
John McCall5769d612010-02-08 23:07:23 +00008960 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00008961 PDiag(diag::err_typecheck_incomplete_tag)
8962 << Base->getSourceRange()))
8963 return ExprError();
8964
John McCalla24dc2e2009-11-17 02:14:36 +00008965 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8966 LookupQualifiedName(R, BaseRecord->getDecl());
8967 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00008968
8969 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00008970 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00008971 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
8972 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00008973 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00008974
8975 // Perform overload resolution.
8976 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008977 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00008978 case OR_Success:
8979 // Overload resolution succeeded; we'll build the call below.
8980 break;
8981
8982 case OR_No_Viable_Function:
8983 if (CandidateSet.empty())
8984 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008985 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00008986 else
8987 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008988 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008989 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008990 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00008991
8992 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00008993 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8994 << "->" << Base->getType() << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008995 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008996 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008997
8998 case OR_Deleted:
8999 Diag(OpLoc, diag::err_ovl_deleted_oper)
9000 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009001 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009002 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009003 << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009004 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009005 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00009006 }
9007
Chandler Carruth25ca4212011-02-25 19:41:05 +00009008 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +00009009 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009010 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00009011
Douglas Gregor8ba10742008-11-20 16:27:02 +00009012 // Convert the object parameter.
9013 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +00009014 ExprResult BaseResult =
9015 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9016 Best->FoundDecl, Method);
9017 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009018 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009019 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00009020
Douglas Gregor8ba10742008-11-20 16:27:02 +00009021 // Build the operator call.
John Wiegley429bb272011-04-08 18:41:53 +00009022 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method);
9023 if (FnExpr.isInvalid())
9024 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009025
John McCallf89e55a2010-11-18 06:31:45 +00009026 QualType ResultTy = Method->getResultType();
9027 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9028 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +00009029 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009030 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009031 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00009032
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009033 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00009034 Method))
9035 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +00009036
9037 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00009038}
9039
Douglas Gregor904eed32008-11-10 20:40:00 +00009040/// FixOverloadedFunctionReference - E is an expression that refers to
9041/// a C++ overloaded function (possibly with some parentheses and
9042/// perhaps a '&' around it). We have resolved the overloaded function
9043/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00009044/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00009045Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00009046 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00009047 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00009048 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9049 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00009050 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00009051 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009052
Douglas Gregor699ee522009-11-20 19:42:02 +00009053 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009054 }
9055
Douglas Gregor699ee522009-11-20 19:42:02 +00009056 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00009057 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9058 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009059 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00009060 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00009061 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +00009062 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +00009063 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00009064 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009065
9066 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +00009067 ICE->getCastKind(),
9068 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00009069 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009070 }
9071
Douglas Gregor699ee522009-11-20 19:42:02 +00009072 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00009073 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00009074 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00009075 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9076 if (Method->isStatic()) {
9077 // Do nothing: static member functions aren't any different
9078 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00009079 } else {
John McCallf7a1a742009-11-24 19:00:30 +00009080 // Fix the sub expression, which really has to be an
9081 // UnresolvedLookupExpr holding an overloaded member function
9082 // or template.
John McCall6bb80172010-03-30 21:47:33 +00009083 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9084 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00009085 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00009086 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +00009087
John McCallba135432009-11-21 08:51:07 +00009088 assert(isa<DeclRefExpr>(SubExpr)
9089 && "fixed to something other than a decl ref");
9090 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
9091 && "fixed to a member ref with no nested name qualifier");
9092
9093 // We have taken the address of a pointer to member
9094 // function. Perform the computation here so that we get the
9095 // appropriate pointer to member type.
9096 QualType ClassType
9097 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
9098 QualType MemPtrType
9099 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9100
John McCallf89e55a2010-11-18 06:31:45 +00009101 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9102 VK_RValue, OK_Ordinary,
9103 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00009104 }
9105 }
John McCall6bb80172010-03-30 21:47:33 +00009106 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9107 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00009108 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00009109 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009110
John McCall2de56d12010-08-25 11:45:40 +00009111 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +00009112 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00009113 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +00009114 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009115 }
John McCallba135432009-11-21 08:51:07 +00009116
9117 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00009118 // FIXME: avoid copy.
9119 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00009120 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00009121 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9122 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00009123 }
9124
John McCallba135432009-11-21 08:51:07 +00009125 return DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00009126 ULE->getQualifierLoc(),
John McCallba135432009-11-21 08:51:07 +00009127 Fn,
9128 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00009129 Fn->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00009130 VK_LValue,
John McCallaa81e162009-12-01 22:10:20 +00009131 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00009132 }
9133
John McCall129e2df2009-11-30 22:42:35 +00009134 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00009135 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00009136 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9137 if (MemExpr->hasExplicitTemplateArgs()) {
9138 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9139 TemplateArgs = &TemplateArgsBuffer;
9140 }
John McCalld5532b62009-11-23 01:53:49 +00009141
John McCallaa81e162009-12-01 22:10:20 +00009142 Expr *Base;
9143
John McCallf89e55a2010-11-18 06:31:45 +00009144 // If we're filling in a static method where we used to have an
9145 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +00009146 if (MemExpr->isImplicitAccess()) {
9147 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9148 return DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00009149 MemExpr->getQualifierLoc(),
John McCallaa81e162009-12-01 22:10:20 +00009150 Fn,
9151 MemExpr->getMemberLoc(),
9152 Fn->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00009153 VK_LValue,
John McCallaa81e162009-12-01 22:10:20 +00009154 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00009155 } else {
9156 SourceLocation Loc = MemExpr->getMemberLoc();
9157 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +00009158 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregor828a1972010-01-07 23:12:05 +00009159 Base = new (Context) CXXThisExpr(Loc,
9160 MemExpr->getBaseType(),
9161 /*isImplicit=*/true);
9162 }
John McCallaa81e162009-12-01 22:10:20 +00009163 } else
John McCall3fa5cae2010-10-26 07:05:15 +00009164 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +00009165
9166 return MemberExpr::Create(Context, Base,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009167 MemExpr->isArrow(),
Douglas Gregor40d96a62011-02-28 21:54:11 +00009168 MemExpr->getQualifierLoc(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009169 Fn,
John McCall6bb80172010-03-30 21:47:33 +00009170 Found,
Abramo Bagnara25777432010-08-11 22:01:17 +00009171 MemExpr->getMemberNameInfo(),
John McCallaa81e162009-12-01 22:10:20 +00009172 TemplateArgs,
John McCallf89e55a2010-11-18 06:31:45 +00009173 Fn->getType(),
9174 cast<CXXMethodDecl>(Fn)->isStatic()
9175 ? VK_LValue : VK_RValue,
9176 OK_Ordinary);
Douglas Gregor699ee522009-11-20 19:42:02 +00009177 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009178
John McCall3fa5cae2010-10-26 07:05:15 +00009179 llvm_unreachable("Invalid reference to overloaded function");
9180 return E;
Douglas Gregor904eed32008-11-10 20:40:00 +00009181}
9182
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009183ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +00009184 DeclAccessPair Found,
9185 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00009186 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00009187}
9188
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009189} // end namespace clang