blob: 72a43d89e8ce5ba703cede48587d6dd0b2af0b14 [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,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000041 SourceLocation Loc = SourceLocation(),
42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
43 ExprResult E = S.Owned(new (S.Context) DeclRefExpr(Fn, Fn->getType(),
44 VK_LValue, Loc, LocInfo));
John Wiegley429bb272011-04-08 18:41:53 +000045 E = S.DefaultFunctionArrayConversion(E.take());
46 if (E.isInvalid())
47 return ExprError();
48 return move(E);
John McCallf89e55a2010-11-18 06:31:45 +000049}
50
John McCall120d63c2010-08-24 20:38:10 +000051static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
52 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000053 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000054 bool CStyle,
55 bool AllowObjCWritebackConversion);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000056
57static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
58 QualType &ToType,
59 bool InOverloadResolution,
60 StandardConversionSequence &SCS,
61 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000062static OverloadingResult
63IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
64 UserDefinedConversionSequence& User,
65 OverloadCandidateSet& Conversions,
66 bool AllowExplicit);
67
68
69static ImplicitConversionSequence::CompareKind
70CompareStandardConversionSequences(Sema &S,
71 const StandardConversionSequence& SCS1,
72 const StandardConversionSequence& SCS2);
73
74static ImplicitConversionSequence::CompareKind
75CompareQualificationConversions(Sema &S,
76 const StandardConversionSequence& SCS1,
77 const StandardConversionSequence& SCS2);
78
79static ImplicitConversionSequence::CompareKind
80CompareDerivedToBaseConversions(Sema &S,
81 const StandardConversionSequence& SCS1,
82 const StandardConversionSequence& SCS2);
83
84
85
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000086/// GetConversionCategory - Retrieve the implicit conversion
87/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000088ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000089GetConversionCategory(ImplicitConversionKind Kind) {
90 static const ImplicitConversionCategory
91 Category[(int)ICK_Num_Conversion_Kinds] = {
92 ICC_Identity,
93 ICC_Lvalue_Transformation,
94 ICC_Lvalue_Transformation,
95 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000096 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000097 ICC_Qualification_Adjustment,
98 ICC_Promotion,
99 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000100 ICC_Promotion,
101 ICC_Conversion,
102 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000103 ICC_Conversion,
104 ICC_Conversion,
105 ICC_Conversion,
106 ICC_Conversion,
107 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000108 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000109 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000110 ICC_Conversion,
111 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000112 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000113 ICC_Conversion
114 };
115 return Category[(int)Kind];
116}
117
118/// GetConversionRank - Retrieve the implicit conversion rank
119/// corresponding to the given implicit conversion kind.
120ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
121 static const ImplicitConversionRank
122 Rank[(int)ICK_Num_Conversion_Kinds] = {
123 ICR_Exact_Match,
124 ICR_Exact_Match,
125 ICR_Exact_Match,
126 ICR_Exact_Match,
127 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000128 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000129 ICR_Promotion,
130 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000131 ICR_Promotion,
132 ICR_Conversion,
133 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000134 ICR_Conversion,
135 ICR_Conversion,
136 ICR_Conversion,
137 ICR_Conversion,
138 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000139 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000140 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000141 ICR_Conversion,
142 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000143 ICR_Complex_Real_Conversion,
144 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000145 ICR_Conversion,
146 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000147 };
148 return Rank[(int)Kind];
149}
150
151/// GetImplicitConversionName - Return the name of this kind of
152/// implicit conversion.
153const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000154 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000155 "No conversion",
156 "Lvalue-to-rvalue",
157 "Array-to-pointer",
158 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000159 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000160 "Qualification",
161 "Integral promotion",
162 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000163 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000164 "Integral conversion",
165 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000166 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000167 "Floating-integral conversion",
168 "Pointer conversion",
169 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000170 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000171 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000172 "Derived-to-base conversion",
173 "Vector conversion",
174 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000175 "Complex-real conversion",
176 "Block Pointer conversion",
177 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000178 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000179 };
180 return Name[Kind];
181}
182
Douglas Gregor60d62c22008-10-31 16:23:19 +0000183/// StandardConversionSequence - Set the standard conversion
184/// sequence to the identity conversion.
185void StandardConversionSequence::setAsIdentityConversion() {
186 First = ICK_Identity;
187 Second = ICK_Identity;
188 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000189 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000190 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000191 ReferenceBinding = false;
192 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000193 IsLvalueReference = true;
194 BindsToFunctionLvalue = false;
195 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000196 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000197 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000198 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000199}
200
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000201/// getRank - Retrieve the rank of this standard conversion sequence
202/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203/// implicit conversions.
204ImplicitConversionRank StandardConversionSequence::getRank() const {
205 ImplicitConversionRank Rank = ICR_Exact_Match;
206 if (GetConversionRank(First) > Rank)
207 Rank = GetConversionRank(First);
208 if (GetConversionRank(Second) > Rank)
209 Rank = GetConversionRank(Second);
210 if (GetConversionRank(Third) > Rank)
211 Rank = GetConversionRank(Third);
212 return Rank;
213}
214
215/// isPointerConversionToBool - Determines whether this conversion is
216/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000217/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000218/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000219bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000220 // Note that FromType has not necessarily been transformed by the
221 // array-to-pointer or function-to-pointer implicit conversions, so
222 // check for their presence as well as checking whether FromType is
223 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000224 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000225 (getFromType()->isPointerType() ||
226 getFromType()->isObjCObjectPointerType() ||
227 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000228 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230 return true;
231
232 return false;
233}
234
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000235/// isPointerConversionToVoidPointer - Determines whether this
236/// conversion is a conversion of a pointer to a void pointer. This is
237/// used as part of the ranking of standard conversion sequences (C++
238/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000239bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000240StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000241isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000242 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000243 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000244
245 // Note that FromType has not necessarily been transformed by the
246 // array-to-pointer implicit conversion, so check for its presence
247 // and redo the conversion to get a pointer.
248 if (First == ICK_Array_To_Pointer)
249 FromType = Context.getArrayDecayedType(FromType);
250
Douglas Gregorf9af5242011-04-15 20:45:44 +0000251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000253 return ToPtrType->getPointeeType()->isVoidType();
254
255 return false;
256}
257
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000258/// DebugPrint - Print this standard conversion sequence to standard
259/// error. Useful for debugging overloading issues.
260void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000261 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000262 bool PrintedSomething = false;
263 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000264 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000265 PrintedSomething = true;
266 }
267
268 if (Second != ICK_Identity) {
269 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000270 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000271 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000272 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000273
274 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000275 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000276 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000277 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000278 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000279 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000280 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000281 PrintedSomething = true;
282 }
283
284 if (Third != ICK_Identity) {
285 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000286 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000287 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000288 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000289 PrintedSomething = true;
290 }
291
292 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000293 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000294 }
295}
296
297/// DebugPrint - Print this user-defined conversion sequence to standard
298/// error. Useful for debugging overloading issues.
299void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000300 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000301 if (Before.First || Before.Second || Before.Third) {
302 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000303 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000304 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000305 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000306 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000307 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000308 After.DebugPrint();
309 }
310}
311
312/// DebugPrint - Print this implicit conversion sequence to standard
313/// error. Useful for debugging overloading issues.
314void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000315 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000316 switch (ConversionKind) {
317 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000318 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000319 Standard.DebugPrint();
320 break;
321 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000322 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000323 UserDefined.DebugPrint();
324 break;
325 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000326 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000327 break;
John McCall1d318332010-01-12 00:44:57 +0000328 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000329 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000330 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000331 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000332 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000333 break;
334 }
335
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000336 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000337}
338
John McCall1d318332010-01-12 00:44:57 +0000339void AmbiguousConversionSequence::construct() {
340 new (&conversions()) ConversionSet();
341}
342
343void AmbiguousConversionSequence::destruct() {
344 conversions().~ConversionSet();
345}
346
347void
348AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
349 FromTypePtr = O.FromTypePtr;
350 ToTypePtr = O.ToTypePtr;
351 new (&conversions()) ConversionSet(O.conversions());
352}
353
Douglas Gregora9333192010-05-08 17:41:32 +0000354namespace {
355 // Structure used by OverloadCandidate::DeductionFailureInfo to store
356 // template parameter and template argument information.
357 struct DFIParamWithArguments {
358 TemplateParameter Param;
359 TemplateArgument FirstArg;
360 TemplateArgument SecondArg;
361 };
362}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000363
Douglas Gregora9333192010-05-08 17:41:32 +0000364/// \brief Convert from Sema's representation of template deduction information
365/// to the form used in overload-candidate information.
366OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000367static MakeDeductionFailureInfo(ASTContext &Context,
368 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000369 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000370 OverloadCandidate::DeductionFailureInfo Result;
371 Result.Result = static_cast<unsigned>(TDK);
372 Result.Data = 0;
373 switch (TDK) {
374 case Sema::TDK_Success:
375 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000376 case Sema::TDK_TooManyArguments:
377 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000378 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000379
Douglas Gregora9333192010-05-08 17:41:32 +0000380 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000381 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000382 Result.Data = Info.Param.getOpaqueValue();
383 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000384
Douglas Gregora9333192010-05-08 17:41:32 +0000385 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000386 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000387 // FIXME: Should allocate from normal heap so that we can free this later.
388 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000389 Saved->Param = Info.Param;
390 Saved->FirstArg = Info.FirstArg;
391 Saved->SecondArg = Info.SecondArg;
392 Result.Data = Saved;
393 break;
394 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000395
Douglas Gregora9333192010-05-08 17:41:32 +0000396 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000397 Result.Data = Info.take();
398 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000399
Douglas Gregora9333192010-05-08 17:41:32 +0000400 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000401 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000402 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000403 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000404
Douglas Gregora9333192010-05-08 17:41:32 +0000405 return Result;
406}
John McCall1d318332010-01-12 00:44:57 +0000407
Douglas Gregora9333192010-05-08 17:41:32 +0000408void OverloadCandidate::DeductionFailureInfo::Destroy() {
409 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
410 case Sema::TDK_Success:
411 case Sema::TDK_InstantiationDepth:
412 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000413 case Sema::TDK_TooManyArguments:
414 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000415 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000416 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000417
Douglas Gregora9333192010-05-08 17:41:32 +0000418 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000419 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000420 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000421 Data = 0;
422 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000423
424 case Sema::TDK_SubstitutionFailure:
425 // FIXME: Destroy the template arugment list?
426 Data = 0;
427 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000428
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000429 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000430 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000431 case Sema::TDK_FailedOverloadResolution:
432 break;
433 }
434}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000435
436TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000437OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
438 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
439 case Sema::TDK_Success:
440 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000441 case Sema::TDK_TooManyArguments:
442 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000443 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000444 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000445
Douglas Gregora9333192010-05-08 17:41:32 +0000446 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000447 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000448 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000449
450 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000451 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000452 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000453
Douglas Gregora9333192010-05-08 17:41:32 +0000454 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000455 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000456 case Sema::TDK_FailedOverloadResolution:
457 break;
458 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000459
Douglas Gregora9333192010-05-08 17:41:32 +0000460 return TemplateParameter();
461}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000462
Douglas Gregorec20f462010-05-08 20:07:26 +0000463TemplateArgumentList *
464OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
465 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
466 case Sema::TDK_Success:
467 case Sema::TDK_InstantiationDepth:
468 case Sema::TDK_TooManyArguments:
469 case Sema::TDK_TooFewArguments:
470 case Sema::TDK_Incomplete:
471 case Sema::TDK_InvalidExplicitArguments:
472 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000473 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000474 return 0;
475
476 case Sema::TDK_SubstitutionFailure:
477 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000478
Douglas Gregorec20f462010-05-08 20:07:26 +0000479 // Unhandled
480 case Sema::TDK_NonDeducedMismatch:
481 case Sema::TDK_FailedOverloadResolution:
482 break;
483 }
484
485 return 0;
486}
487
Douglas Gregora9333192010-05-08 17:41:32 +0000488const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
489 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
490 case Sema::TDK_Success:
491 case Sema::TDK_InstantiationDepth:
492 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000493 case Sema::TDK_TooManyArguments:
494 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000495 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000496 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000497 return 0;
498
Douglas Gregora9333192010-05-08 17:41:32 +0000499 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000500 case Sema::TDK_Underqualified:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000501 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000502
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000503 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000504 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000505 case Sema::TDK_FailedOverloadResolution:
506 break;
507 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000508
Douglas Gregora9333192010-05-08 17:41:32 +0000509 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000510}
Douglas Gregora9333192010-05-08 17:41:32 +0000511
512const TemplateArgument *
513OverloadCandidate::DeductionFailureInfo::getSecondArg() {
514 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
515 case Sema::TDK_Success:
516 case Sema::TDK_InstantiationDepth:
517 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000518 case Sema::TDK_TooManyArguments:
519 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000520 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000521 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000522 return 0;
523
Douglas Gregora9333192010-05-08 17:41:32 +0000524 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000525 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000526 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
527
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000528 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000529 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000530 case Sema::TDK_FailedOverloadResolution:
531 break;
532 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000533
Douglas Gregora9333192010-05-08 17:41:32 +0000534 return 0;
535}
536
537void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000538 inherited::clear();
539 Functions.clear();
540}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000541
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000542// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000543// overload of the declarations in Old. This routine returns false if
544// New and Old cannot be overloaded, e.g., if New has the same
545// signature as some function in Old (C++ 1.3.10) or if the Old
546// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000547// it does return false, MatchedDecl will point to the decl that New
548// cannot be overloaded with. This decl may be a UsingShadowDecl on
549// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000550//
551// Example: Given the following input:
552//
553// void f(int, float); // #1
554// void f(int, int); // #2
555// int f(int, int); // #3
556//
557// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000558// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000559//
John McCall51fa86f2009-12-02 08:47:38 +0000560// When we process #2, Old contains only the FunctionDecl for #1. By
561// comparing the parameter types, we see that #1 and #2 are overloaded
562// (since they have different signatures), so this routine returns
563// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000564//
John McCall51fa86f2009-12-02 08:47:38 +0000565// When we process #3, Old is an overload set containing #1 and #2. We
566// compare the signatures of #3 to #1 (they're overloaded, so we do
567// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
568// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000569// signature), IsOverload returns false and MatchedDecl will be set to
570// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000571//
572// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
573// into a class by a using declaration. The rules for whether to hide
574// shadow declarations ignore some properties which otherwise figure
575// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000576Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000577Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
578 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000579 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000580 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000581 NamedDecl *OldD = *I;
582
583 bool OldIsUsingDecl = false;
584 if (isa<UsingShadowDecl>(OldD)) {
585 OldIsUsingDecl = true;
586
587 // We can always introduce two using declarations into the same
588 // context, even if they have identical signatures.
589 if (NewIsUsingDecl) continue;
590
591 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
592 }
593
594 // If either declaration was introduced by a using declaration,
595 // we'll need to use slightly different rules for matching.
596 // Essentially, these rules are the normal rules, except that
597 // function templates hide function templates with different
598 // return types or template parameter lists.
599 bool UseMemberUsingDeclRules =
600 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
601
John McCall51fa86f2009-12-02 08:47:38 +0000602 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000603 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
604 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
605 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
606 continue;
607 }
608
John McCall871b2e72009-12-09 03:35:25 +0000609 Match = *I;
610 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000611 }
John McCall51fa86f2009-12-02 08:47:38 +0000612 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000613 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
614 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
615 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
616 continue;
617 }
618
John McCall871b2e72009-12-09 03:35:25 +0000619 Match = *I;
620 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000621 }
John McCalld7945c62010-11-10 03:01:53 +0000622 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000623 // We can overload with these, which can show up when doing
624 // redeclaration checks for UsingDecls.
625 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000626 } else if (isa<TagDecl>(OldD)) {
627 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000628 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
629 // Optimistically assume that an unresolved using decl will
630 // overload; if it doesn't, we'll have to diagnose during
631 // template instantiation.
632 } else {
John McCall68263142009-11-18 22:49:29 +0000633 // (C++ 13p1):
634 // Only function declarations can be overloaded; object and type
635 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000636 Match = *I;
637 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000638 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000639 }
John McCall68263142009-11-18 22:49:29 +0000640
John McCall871b2e72009-12-09 03:35:25 +0000641 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000642}
643
John McCallad00b772010-06-16 08:42:20 +0000644bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
645 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000646 // If both of the functions are extern "C", then they are not
647 // overloads.
648 if (Old->isExternC() && New->isExternC())
649 return false;
650
John McCall68263142009-11-18 22:49:29 +0000651 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
652 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
653
654 // C++ [temp.fct]p2:
655 // A function template can be overloaded with other function templates
656 // and with normal (non-template) functions.
657 if ((OldTemplate == 0) != (NewTemplate == 0))
658 return true;
659
660 // Is the function New an overload of the function Old?
661 QualType OldQType = Context.getCanonicalType(Old->getType());
662 QualType NewQType = Context.getCanonicalType(New->getType());
663
664 // Compare the signatures (C++ 1.3.10) of the two functions to
665 // determine whether they are overloads. If we find any mismatch
666 // in the signature, they are overloads.
667
668 // If either of these functions is a K&R-style function (no
669 // prototype), then we consider them to have matching signatures.
670 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
671 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
672 return false;
673
John McCallf4c73712011-01-19 06:33:43 +0000674 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
675 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000676
677 // The signature of a function includes the types of its
678 // parameters (C++ 1.3.10), which includes the presence or absence
679 // of the ellipsis; see C++ DR 357).
680 if (OldQType != NewQType &&
681 (OldType->getNumArgs() != NewType->getNumArgs() ||
682 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000683 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000684 return true;
685
686 // C++ [temp.over.link]p4:
687 // The signature of a function template consists of its function
688 // signature, its return type and its template parameter list. The names
689 // of the template parameters are significant only for establishing the
690 // relationship between the template parameters and the rest of the
691 // signature.
692 //
693 // We check the return type and template parameter lists for function
694 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000695 //
696 // However, we don't consider either of these when deciding whether
697 // a member introduced by a shadow declaration is hidden.
698 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000699 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
700 OldTemplate->getTemplateParameters(),
701 false, TPL_TemplateMatch) ||
702 OldType->getResultType() != NewType->getResultType()))
703 return true;
704
705 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000706 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +0000707 //
708 // As part of this, also check whether one of the member functions
709 // is static, in which case they are not overloads (C++
710 // 13.1p2). While not part of the definition of the signature,
711 // this check is important to determine whether these functions
712 // can be overloaded.
713 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
714 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
715 if (OldMethod && NewMethod &&
716 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000717 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-01-26 21:20:37 +0000718 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
719 if (!UseUsingDeclRules &&
720 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
721 (OldMethod->getRefQualifier() == RQ_None ||
722 NewMethod->getRefQualifier() == RQ_None)) {
723 // C++0x [over.load]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000724 // - Member function declarations with the same name and the same
725 // parameter-type-list as well as member function template
726 // declarations with the same name, the same parameter-type-list, and
727 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorb145ee62011-01-26 21:20:37 +0000728 // them, but not all, have a ref-qualifier (8.3.5).
729 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
730 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
731 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
732 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000733
John McCall68263142009-11-18 22:49:29 +0000734 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +0000735 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000736
John McCall68263142009-11-18 22:49:29 +0000737 // The signatures match; this is not an overload.
738 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000739}
740
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +0000741/// \brief Checks availability of the function depending on the current
742/// function context. Inside an unavailable function, unavailability is ignored.
743///
744/// \returns true if \arg FD is unavailable and current context is inside
745/// an available function, false otherwise.
746bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
747 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
748}
749
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000750/// TryImplicitConversion - Attempt to perform an implicit conversion
751/// from the given expression (Expr) to the given type (ToType). This
752/// function returns an implicit conversion sequence that can be used
753/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000754///
755/// void f(float f);
756/// void g(int i) { f(i); }
757///
758/// this routine would produce an implicit conversion sequence to
759/// describe the initialization of f from i, which will be a standard
760/// conversion sequence containing an lvalue-to-rvalue conversion (C++
761/// 4.1) followed by a floating-integral conversion (C++ 4.9).
762//
763/// Note that this routine only determines how the conversion can be
764/// performed; it does not actually perform the conversion. As such,
765/// it will not produce any diagnostics if no conversion is available,
766/// but will instead return an implicit conversion sequence of kind
767/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000768///
769/// If @p SuppressUserConversions, then user-defined conversions are
770/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000771/// If @p AllowExplicit, then explicit user-defined conversions are
772/// permitted.
John McCallf85e1932011-06-15 23:02:42 +0000773///
774/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
775/// writeback conversion, which allows __autoreleasing id* parameters to
776/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +0000777static ImplicitConversionSequence
778TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
779 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000780 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000781 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +0000782 bool CStyle,
783 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000784 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +0000785 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +0000786 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +0000787 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000788 return ICS;
789 }
790
John McCall120d63c2010-08-24 20:38:10 +0000791 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000792 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000793 return ICS;
794 }
795
Douglas Gregor604eb652010-08-11 02:15:33 +0000796 // C++ [over.ics.user]p4:
797 // A conversion of an expression of class type to the same class
798 // type is given Exact Match rank, and a conversion of an
799 // expression of class type to a base class of that type is
800 // given Conversion rank, in spite of the fact that a copy/move
801 // constructor (i.e., a user-defined conversion function) is
802 // called for those cases.
803 QualType FromType = From->getType();
804 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +0000805 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
806 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000807 ICS.setStandard();
808 ICS.Standard.setAsIdentityConversion();
809 ICS.Standard.setFromType(FromType);
810 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000811
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000812 // We don't actually check at this point whether there is a valid
813 // copy/move constructor, since overloading just assumes that it
814 // exists. When we actually perform initialization, we'll find the
815 // appropriate constructor to copy the returned object, if needed.
816 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000817
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000818 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +0000819 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000820 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000821
Douglas Gregor604eb652010-08-11 02:15:33 +0000822 return ICS;
823 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000824
Douglas Gregor604eb652010-08-11 02:15:33 +0000825 if (SuppressUserConversions) {
826 // We're not in the case above, so there is no conversion that
827 // we can perform.
828 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000829 return ICS;
830 }
831
832 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000833 OverloadCandidateSet Conversions(From->getExprLoc());
834 OverloadingResult UserDefResult
John McCall120d63c2010-08-24 20:38:10 +0000835 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000836 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000837
838 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000839 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000840 // C++ [over.ics.user]p4:
841 // A conversion of an expression of class type to the same class
842 // type is given Exact Match rank, and a conversion of an
843 // expression of class type to a base class of that type is
844 // given Conversion rank, in spite of the fact that a copy
845 // constructor (i.e., a user-defined conversion function) is
846 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000847 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000848 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000849 QualType FromCanon
John McCall120d63c2010-08-24 20:38:10 +0000850 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
851 QualType ToCanon
852 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000853 if (Constructor->isCopyConstructor() &&
John McCall120d63c2010-08-24 20:38:10 +0000854 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000855 // Turn this into a "standard" conversion sequence, so that it
856 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000857 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000858 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000859 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000860 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000861 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000862 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000863 ICS.Standard.Second = ICK_Derived_To_Base;
864 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000865 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000866
867 // C++ [over.best.ics]p4:
868 // However, when considering the argument of a user-defined
869 // conversion function that is a candidate by 13.3.1.3 when
870 // invoked for the copying of the temporary in the second step
871 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
872 // 13.3.1.6 in all cases, only standard conversion sequences and
873 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000874 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000875 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000876 }
John McCallcefd3ad2010-01-13 22:30:33 +0000877 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000878 ICS.setAmbiguous();
879 ICS.Ambiguous.setFromType(From->getType());
880 ICS.Ambiguous.setToType(ToType);
881 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
882 Cand != Conversions.end(); ++Cand)
883 if (Cand->Viable)
884 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000885 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000886 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000887 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000888
889 return ICS;
890}
891
John McCallf85e1932011-06-15 23:02:42 +0000892ImplicitConversionSequence
893Sema::TryImplicitConversion(Expr *From, QualType ToType,
894 bool SuppressUserConversions,
895 bool AllowExplicit,
896 bool InOverloadResolution,
897 bool CStyle,
898 bool AllowObjCWritebackConversion) {
899 return clang::TryImplicitConversion(*this, From, ToType,
900 SuppressUserConversions, AllowExplicit,
901 InOverloadResolution, CStyle,
902 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +0000903}
904
Douglas Gregor575c63a2010-04-16 22:27:05 +0000905/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +0000906/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +0000907/// converted expression. Flavor is the kind of conversion we're
908/// performing, used in the error message. If @p AllowExplicit,
909/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +0000910ExprResult
911Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +0000912 AssignmentAction Action, bool AllowExplicit) {
913 ImplicitConversionSequence ICS;
914 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
915}
916
John Wiegley429bb272011-04-08 18:41:53 +0000917ExprResult
918Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +0000919 AssignmentAction Action, bool AllowExplicit,
920 ImplicitConversionSequence& ICS) {
John McCallf85e1932011-06-15 23:02:42 +0000921 // Objective-C ARC: Determine whether we will allow the writeback conversion.
922 bool AllowObjCWritebackConversion
923 = getLangOptions().ObjCAutoRefCount &&
924 (Action == AA_Passing || Action == AA_Sending);
925
926
John McCall120d63c2010-08-24 20:38:10 +0000927 ICS = clang::TryImplicitConversion(*this, From, ToType,
928 /*SuppressUserConversions=*/false,
929 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000930 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +0000931 /*CStyle=*/false,
932 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +0000933 return PerformImplicitConversion(From, ToType, ICS, Action);
934}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000935
936/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +0000937/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +0000938bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
939 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +0000940 if (Context.hasSameUnqualifiedType(FromType, ToType))
941 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000942
John McCall00ccbef2010-12-21 00:44:39 +0000943 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
944 // where F adds one of the following at most once:
945 // - a pointer
946 // - a member pointer
947 // - a block pointer
948 CanQualType CanTo = Context.getCanonicalType(ToType);
949 CanQualType CanFrom = Context.getCanonicalType(FromType);
950 Type::TypeClass TyClass = CanTo->getTypeClass();
951 if (TyClass != CanFrom->getTypeClass()) return false;
952 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
953 if (TyClass == Type::Pointer) {
954 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
955 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
956 } else if (TyClass == Type::BlockPointer) {
957 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
958 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
959 } else if (TyClass == Type::MemberPointer) {
960 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
961 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
962 } else {
963 return false;
964 }
Douglas Gregor43c79c22009-12-09 00:47:37 +0000965
John McCall00ccbef2010-12-21 00:44:39 +0000966 TyClass = CanTo->getTypeClass();
967 if (TyClass != CanFrom->getTypeClass()) return false;
968 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
969 return false;
970 }
971
972 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
973 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
974 if (!EInfo.getNoReturn()) return false;
975
976 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
977 assert(QualType(FromFn, 0).isCanonical());
978 if (QualType(FromFn, 0) != CanTo) return false;
979
980 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +0000981 return true;
982}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000983
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000984/// \brief Determine whether the conversion from FromType to ToType is a valid
985/// vector conversion.
986///
987/// \param ICK Will be set to the vector conversion kind, if this is a vector
988/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000989static bool IsVectorConversion(ASTContext &Context, QualType FromType,
990 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000991 // We need at least one of these types to be a vector type to have a vector
992 // conversion.
993 if (!ToType->isVectorType() && !FromType->isVectorType())
994 return false;
995
996 // Identical types require no conversions.
997 if (Context.hasSameUnqualifiedType(FromType, ToType))
998 return false;
999
1000 // There are no conversions between extended vector types, only identity.
1001 if (ToType->isExtVectorType()) {
1002 // There are no conversions between extended vector types other than the
1003 // identity conversion.
1004 if (FromType->isExtVectorType())
1005 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001006
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001007 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001008 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001009 ICK = ICK_Vector_Splat;
1010 return true;
1011 }
1012 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001013
1014 // We can perform the conversion between vector types in the following cases:
1015 // 1)vector types are equivalent AltiVec and GCC vector types
1016 // 2)lax vector conversions are permitted and the vector types are of the
1017 // same size
1018 if (ToType->isVectorType() && FromType->isVectorType()) {
1019 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001020 (Context.getLangOptions().LaxVectorConversions &&
1021 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001022 ICK = ICK_Vector_Conversion;
1023 return true;
1024 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001025 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001026
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001027 return false;
1028}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001029
Douglas Gregor60d62c22008-10-31 16:23:19 +00001030/// IsStandardConversion - Determines whether there is a standard
1031/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1032/// expression From to the type ToType. Standard conversion sequences
1033/// only consider non-class types; for conversions that involve class
1034/// types, use TryImplicitConversion. If a conversion exists, SCS will
1035/// contain the standard conversion sequence required to perform this
1036/// conversion and this routine will return true. Otherwise, this
1037/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001038static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1039 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001040 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001041 bool CStyle,
1042 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001043 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001044
Douglas Gregor60d62c22008-10-31 16:23:19 +00001045 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001046 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001047 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001048 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001049 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001050 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001051
Douglas Gregorf9201e02009-02-11 23:02:49 +00001052 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001053 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001054 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +00001055 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001056 return false;
1057
Mike Stump1eb44332009-09-09 15:08:12 +00001058 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001059 }
1060
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001061 // The first conversion can be an lvalue-to-rvalue conversion,
1062 // array-to-pointer conversion, or function-to-pointer conversion
1063 // (C++ 4p1).
1064
John McCall120d63c2010-08-24 20:38:10 +00001065 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001066 DeclAccessPair AccessPair;
1067 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001068 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001069 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001070 // We were able to resolve the address of the overloaded function,
1071 // so we can convert to the type of that function.
1072 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001073
1074 // we can sometimes resolve &foo<int> regardless of ToType, so check
1075 // if the type matches (identity) or we are converting to bool
1076 if (!S.Context.hasSameUnqualifiedType(
1077 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1078 QualType resultTy;
1079 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001080 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001081 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1082 // otherwise, only a boolean conversion is standard
1083 if (!ToType->isBooleanType())
1084 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001085 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001086
Chandler Carruth90434232011-03-29 08:08:18 +00001087 // Check if the "from" expression is taking the address of an overloaded
1088 // function and recompute the FromType accordingly. Take advantage of the
1089 // fact that non-static member functions *must* have such an address-of
1090 // expression.
1091 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1092 if (Method && !Method->isStatic()) {
1093 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1094 "Non-unary operator on non-static member address");
1095 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1096 == UO_AddrOf &&
1097 "Non-address-of operator on non-static member address");
1098 const Type *ClassType
1099 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1100 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001101 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1102 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1103 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001104 "Non-address-of operator for overloaded function expression");
1105 FromType = S.Context.getPointerType(FromType);
1106 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001107
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001108 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001109 assert(S.Context.hasSameType(
1110 FromType,
1111 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001112 } else {
1113 return false;
1114 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001115 }
Mike Stump1eb44332009-09-09 15:08:12 +00001116 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001117 // An lvalue (3.10) of a non-function, non-array type T can be
1118 // converted to an rvalue.
John McCall7eb0a9e2010-11-24 05:12:34 +00001119 bool argIsLValue = From->isLValue();
1120 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001121 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001122 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001123 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001124
1125 // If T is a non-class type, the type of the rvalue is the
1126 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001127 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1128 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001129 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001130 } else if (FromType->isArrayType()) {
1131 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001132 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001133
1134 // An lvalue or rvalue of type "array of N T" or "array of unknown
1135 // bound of T" can be converted to an rvalue of type "pointer to
1136 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001137 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001138
John McCall120d63c2010-08-24 20:38:10 +00001139 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001140 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001141 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001142
1143 // For the purpose of ranking in overload resolution
1144 // (13.3.3.1.1), this conversion is considered an
1145 // array-to-pointer conversion followed by a qualification
1146 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001147 SCS.Second = ICK_Identity;
1148 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001149 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001150 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001151 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001152 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001153 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001154 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001155 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001156
1157 // An lvalue of function type T can be converted to an rvalue of
1158 // type "pointer to T." The result is a pointer to the
1159 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001160 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001161 } else {
1162 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001163 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001164 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001165 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001166
1167 // The second conversion can be an integral promotion, floating
1168 // point promotion, integral conversion, floating point conversion,
1169 // floating-integral conversion, pointer conversion,
1170 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001171 // For overloading in C, this can also be a "compatible-type"
1172 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001173 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001174 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001175 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001176 // The unqualified versions of the types are the same: there's no
1177 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001178 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001179 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001180 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001181 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001182 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001183 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001184 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001185 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001186 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001187 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001188 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001189 SCS.Second = ICK_Complex_Promotion;
1190 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001191 } else if (ToType->isBooleanType() &&
1192 (FromType->isArithmeticType() ||
1193 FromType->isAnyPointerType() ||
1194 FromType->isBlockPointerType() ||
1195 FromType->isMemberPointerType() ||
1196 FromType->isNullPtrType())) {
1197 // Boolean conversions (C++ 4.12).
1198 SCS.Second = ICK_Boolean_Conversion;
1199 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001200 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001201 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001202 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001203 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001204 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001205 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001206 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001207 SCS.Second = ICK_Complex_Conversion;
1208 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001209 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1210 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001211 // Complex-real conversions (C99 6.3.1.7)
1212 SCS.Second = ICK_Complex_Real;
1213 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001214 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001215 // Floating point conversions (C++ 4.8).
1216 SCS.Second = ICK_Floating_Conversion;
1217 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001218 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001219 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001220 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001221 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001222 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001223 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001224 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001225 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001226 SCS.Second = ICK_Block_Pointer_Conversion;
1227 } else if (AllowObjCWritebackConversion &&
1228 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1229 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001230 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1231 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001232 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001233 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001234 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001235 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001236 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001237 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001238 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001239 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001240 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001241 SCS.Second = SecondICK;
1242 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001243 } else if (!S.getLangOptions().CPlusPlus &&
1244 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001245 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001246 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001247 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001248 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001249 // Treat a conversion that strips "noreturn" as an identity conversion.
1250 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001251 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1252 InOverloadResolution,
1253 SCS, CStyle)) {
1254 SCS.Second = ICK_TransparentUnionConversion;
1255 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001256 } else {
1257 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001258 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001259 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001260 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001261
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001262 QualType CanonFrom;
1263 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001264 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001265 bool ObjCLifetimeConversion;
1266 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1267 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001268 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001269 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001270 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001271 CanonFrom = S.Context.getCanonicalType(FromType);
1272 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001273 } else {
1274 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001275 SCS.Third = ICK_Identity;
1276
Mike Stump1eb44332009-09-09 15:08:12 +00001277 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001278 // [...] Any difference in top-level cv-qualification is
1279 // subsumed by the initialization itself and does not constitute
1280 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001281 CanonFrom = S.Context.getCanonicalType(FromType);
1282 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001283 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001284 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001285 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001286 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1287 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001288 FromType = ToType;
1289 CanonFrom = CanonTo;
1290 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001291 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001292 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001293
1294 // If we have not converted the argument type to the parameter type,
1295 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001296 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001297 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001298
Douglas Gregor60d62c22008-10-31 16:23:19 +00001299 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001300}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001301
1302static bool
1303IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1304 QualType &ToType,
1305 bool InOverloadResolution,
1306 StandardConversionSequence &SCS,
1307 bool CStyle) {
1308
1309 const RecordType *UT = ToType->getAsUnionType();
1310 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1311 return false;
1312 // The field to initialize within the transparent union.
1313 RecordDecl *UD = UT->getDecl();
1314 // It's compatible if the expression matches any of the fields.
1315 for (RecordDecl::field_iterator it = UD->field_begin(),
1316 itend = UD->field_end();
1317 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001318 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1319 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001320 ToType = it->getType();
1321 return true;
1322 }
1323 }
1324 return false;
1325}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001326
1327/// IsIntegralPromotion - Determines whether the conversion from the
1328/// expression From (whose potentially-adjusted type is FromType) to
1329/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1330/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001331bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001332 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001333 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001334 if (!To) {
1335 return false;
1336 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001337
1338 // An rvalue of type char, signed char, unsigned char, short int, or
1339 // unsigned short int can be converted to an rvalue of type int if
1340 // int can represent all the values of the source type; otherwise,
1341 // the source rvalue can be converted to an rvalue of type unsigned
1342 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001343 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1344 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001345 if (// We can promote any signed, promotable integer type to an int
1346 (FromType->isSignedIntegerType() ||
1347 // We can promote any unsigned integer type whose size is
1348 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001349 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001350 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001351 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001352 }
1353
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001354 return To->getKind() == BuiltinType::UInt;
1355 }
1356
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001357 // C++0x [conv.prom]p3:
1358 // A prvalue of an unscoped enumeration type whose underlying type is not
1359 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1360 // following types that can represent all the values of the enumeration
1361 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1362 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001363 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001364 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001365 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001366 // with lowest integer conversion rank (4.13) greater than the rank of long
1367 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001368 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001369 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1370 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1371 // provided for a scoped enumeration.
1372 if (FromEnumType->getDecl()->isScoped())
1373 return false;
1374
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001375 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001376 if (ToType->isIntegerType() &&
Douglas Gregor5dde1602010-09-12 03:38:25 +00001377 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001378 return Context.hasSameUnqualifiedType(ToType,
1379 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001380 }
John McCall842aef82009-12-09 09:09:27 +00001381
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001382 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001383 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1384 // to an rvalue a prvalue of the first of the following types that can
1385 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001386 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001387 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001388 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001389 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001390 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001391 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001392 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001393 // Determine whether the type we're converting from is signed or
1394 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001395 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001396 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001397
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001398 // The types we'll try to promote to, in the appropriate
1399 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001400 QualType PromoteTypes[6] = {
1401 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001402 Context.LongTy, Context.UnsignedLongTy ,
1403 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001404 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001405 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001406 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1407 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001408 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001409 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1410 // We found the type that we can promote to. If this is the
1411 // type we wanted, we have a promotion. Otherwise, no
1412 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001413 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001414 }
1415 }
1416 }
1417
1418 // An rvalue for an integral bit-field (9.6) can be converted to an
1419 // rvalue of type int if int can represent all the values of the
1420 // bit-field; otherwise, it can be converted to unsigned int if
1421 // unsigned int can represent all the values of the bit-field. If
1422 // the bit-field is larger yet, no integral promotion applies to
1423 // it. If the bit-field has an enumerated type, it is treated as any
1424 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001425 // FIXME: We should delay checking of bit-fields until we actually perform the
1426 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001427 using llvm::APSInt;
1428 if (From)
1429 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001430 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001431 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001432 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1433 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1434 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Douglas Gregor86f19402008-12-20 23:49:58 +00001436 // Are we promoting to an int from a bitfield that fits in an int?
1437 if (BitWidth < ToSize ||
1438 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1439 return To->getKind() == BuiltinType::Int;
1440 }
Mike Stump1eb44332009-09-09 15:08:12 +00001441
Douglas Gregor86f19402008-12-20 23:49:58 +00001442 // Are we promoting to an unsigned int from an unsigned bitfield
1443 // that fits into an unsigned int?
1444 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1445 return To->getKind() == BuiltinType::UInt;
1446 }
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Douglas Gregor86f19402008-12-20 23:49:58 +00001448 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001449 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001450 }
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001452 // An rvalue of type bool can be converted to an rvalue of type int,
1453 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001454 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001455 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001456 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001457
1458 return false;
1459}
1460
1461/// IsFloatingPointPromotion - Determines whether the conversion from
1462/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1463/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001464bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001465 /// An rvalue of type float can be converted to an rvalue of type
1466 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001467 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1468 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001469 if (FromBuiltin->getKind() == BuiltinType::Float &&
1470 ToBuiltin->getKind() == BuiltinType::Double)
1471 return true;
1472
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001473 // C99 6.3.1.5p1:
1474 // When a float is promoted to double or long double, or a
1475 // double is promoted to long double [...].
1476 if (!getLangOptions().CPlusPlus &&
1477 (FromBuiltin->getKind() == BuiltinType::Float ||
1478 FromBuiltin->getKind() == BuiltinType::Double) &&
1479 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1480 return true;
1481 }
1482
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001483 return false;
1484}
1485
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001486/// \brief Determine if a conversion is a complex promotion.
1487///
1488/// A complex promotion is defined as a complex -> complex conversion
1489/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001490/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001491bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001492 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001493 if (!FromComplex)
1494 return false;
1495
John McCall183700f2009-09-21 23:43:11 +00001496 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001497 if (!ToComplex)
1498 return false;
1499
1500 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001501 ToComplex->getElementType()) ||
1502 IsIntegralPromotion(0, FromComplex->getElementType(),
1503 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001504}
1505
Douglas Gregorcb7de522008-11-26 23:31:11 +00001506/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1507/// the pointer type FromPtr to a pointer to type ToPointee, with the
1508/// same type qualifiers as FromPtr has on its pointee type. ToType,
1509/// if non-empty, will be a pointer to ToType that may or may not have
1510/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001511///
Mike Stump1eb44332009-09-09 15:08:12 +00001512static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001513BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001514 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001515 ASTContext &Context,
1516 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001517 assert((FromPtr->getTypeClass() == Type::Pointer ||
1518 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1519 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001520
John McCallf85e1932011-06-15 23:02:42 +00001521 /// Conversions to 'id' subsume cv-qualifier conversions.
1522 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001523 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001524
1525 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001526 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001527 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001528 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001529
John McCallf85e1932011-06-15 23:02:42 +00001530 if (StripObjCLifetime)
1531 Quals.removeObjCLifetime();
1532
Mike Stump1eb44332009-09-09 15:08:12 +00001533 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001534 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001535 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001536 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001537 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001538
1539 // Build a pointer to ToPointee. It has the right qualifiers
1540 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001541 if (isa<ObjCObjectPointerType>(ToType))
1542 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001543 return Context.getPointerType(ToPointee);
1544 }
1545
1546 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001547 QualType QualifiedCanonToPointee
1548 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001549
Douglas Gregorda80f742010-12-01 21:43:58 +00001550 if (isa<ObjCObjectPointerType>(ToType))
1551 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1552 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001553}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001554
Mike Stump1eb44332009-09-09 15:08:12 +00001555static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001556 bool InOverloadResolution,
1557 ASTContext &Context) {
1558 // Handle value-dependent integral null pointer constants correctly.
1559 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1560 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001561 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001562 return !InOverloadResolution;
1563
Douglas Gregorce940492009-09-25 04:25:58 +00001564 return Expr->isNullPointerConstant(Context,
1565 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1566 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001567}
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001569/// IsPointerConversion - Determines whether the conversion of the
1570/// expression From, which has the (possibly adjusted) type FromType,
1571/// can be converted to the type ToType via a pointer conversion (C++
1572/// 4.10). If so, returns true and places the converted type (that
1573/// might differ from ToType in its cv-qualifiers at some level) into
1574/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001575///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001576/// This routine also supports conversions to and from block pointers
1577/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1578/// pointers to interfaces. FIXME: Once we've determined the
1579/// appropriate overloading rules for Objective-C, we may want to
1580/// split the Objective-C checks into a different routine; however,
1581/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001582/// conversions, so for now they live here. IncompatibleObjC will be
1583/// set if the conversion is an allowed Objective-C conversion that
1584/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001585bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001586 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001587 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001588 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001589 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001590 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1591 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001592 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001593
Mike Stump1eb44332009-09-09 15:08:12 +00001594 // Conversion from a null pointer constant to any Objective-C pointer type.
1595 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001596 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001597 ConvertedType = ToType;
1598 return true;
1599 }
1600
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001601 // Blocks: Block pointers can be converted to void*.
1602 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001603 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001604 ConvertedType = ToType;
1605 return true;
1606 }
1607 // Blocks: A null pointer constant can be converted to a block
1608 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001609 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001610 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001611 ConvertedType = ToType;
1612 return true;
1613 }
1614
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001615 // If the left-hand-side is nullptr_t, the right side can be a null
1616 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001617 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001618 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001619 ConvertedType = ToType;
1620 return true;
1621 }
1622
Ted Kremenek6217b802009-07-29 21:53:49 +00001623 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001624 if (!ToTypePtr)
1625 return false;
1626
1627 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001628 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001629 ConvertedType = ToType;
1630 return true;
1631 }
Sebastian Redl07779722008-10-31 14:43:28 +00001632
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001633 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001634 // , including objective-c pointers.
1635 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001636 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1637 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001638 ConvertedType = BuildSimilarlyQualifiedPointerType(
1639 FromType->getAs<ObjCObjectPointerType>(),
1640 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001641 ToType, Context);
1642 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001643 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001644 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001645 if (!FromTypePtr)
1646 return false;
1647
1648 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001649
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001650 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001651 // pointer conversion, so don't do all of the work below.
1652 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1653 return false;
1654
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001655 // An rvalue of type "pointer to cv T," where T is an object type,
1656 // can be converted to an rvalue of type "pointer to cv void" (C++
1657 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001658 if (FromPointeeType->isIncompleteOrObjectType() &&
1659 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001660 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001661 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00001662 ToType, Context,
1663 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001664 return true;
1665 }
1666
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001667 // MSVC allows implicit function to void* type conversion.
1668 if (getLangOptions().Microsoft && FromPointeeType->isFunctionType() &&
1669 ToPointeeType->isVoidType()) {
1670 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1671 ToPointeeType,
1672 ToType, Context);
1673 return true;
1674 }
1675
Douglas Gregorf9201e02009-02-11 23:02:49 +00001676 // When we're overloading in C, we allow a special kind of pointer
1677 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001678 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001679 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001680 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001681 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001682 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001683 return true;
1684 }
1685
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001686 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001687 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001688 // An rvalue of type "pointer to cv D," where D is a class type,
1689 // can be converted to an rvalue of type "pointer to cv B," where
1690 // B is a base class (clause 10) of D. If B is an inaccessible
1691 // (clause 11) or ambiguous (10.2) base class of D, a program that
1692 // necessitates this conversion is ill-formed. The result of the
1693 // conversion is a pointer to the base class sub-object of the
1694 // derived class object. The null pointer value is converted to
1695 // the null pointer value of the destination type.
1696 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001697 // Note that we do not check for ambiguity or inaccessibility
1698 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001699 if (getLangOptions().CPlusPlus &&
1700 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001701 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001702 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001703 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001704 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001705 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001706 ToType, Context);
1707 return true;
1708 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001709
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00001710 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1711 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1712 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1713 ToPointeeType,
1714 ToType, Context);
1715 return true;
1716 }
1717
Douglas Gregorc7887512008-12-19 19:13:09 +00001718 return false;
1719}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001720
1721/// \brief Adopt the given qualifiers for the given type.
1722static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1723 Qualifiers TQs = T.getQualifiers();
1724
1725 // Check whether qualifiers already match.
1726 if (TQs == Qs)
1727 return T;
1728
1729 if (Qs.compatiblyIncludes(TQs))
1730 return Context.getQualifiedType(T, Qs);
1731
1732 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1733}
Douglas Gregorc7887512008-12-19 19:13:09 +00001734
1735/// isObjCPointerConversion - Determines whether this is an
1736/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1737/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001738bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001739 QualType& ConvertedType,
1740 bool &IncompatibleObjC) {
1741 if (!getLangOptions().ObjC1)
1742 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001743
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001744 // The set of qualifiers on the type we're converting from.
1745 Qualifiers FromQualifiers = FromType.getQualifiers();
1746
Steve Naroff14108da2009-07-10 23:34:53 +00001747 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00001748 const ObjCObjectPointerType* ToObjCPtr =
1749 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001750 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001751 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001752
Steve Naroff14108da2009-07-10 23:34:53 +00001753 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001754 // If the pointee types are the same (ignoring qualifications),
1755 // then this is not a pointer conversion.
1756 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1757 FromObjCPtr->getPointeeType()))
1758 return false;
1759
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001760 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00001761 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001762 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001763 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001764 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001765 return true;
1766 }
1767 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001768 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001769 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001770 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001771 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001772 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001773 return true;
1774 }
1775 // Objective C++: We're able to convert from a pointer to an
1776 // interface to a pointer to a different interface.
1777 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001778 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1779 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1780 if (getLangOptions().CPlusPlus && LHS && RHS &&
1781 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1782 FromObjCPtr->getPointeeType()))
1783 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001784 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00001785 ToObjCPtr->getPointeeType(),
1786 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001787 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001788 return true;
1789 }
1790
1791 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1792 // Okay: this is some kind of implicit downcast of Objective-C
1793 // interfaces, which is permitted. However, we're going to
1794 // complain about it.
1795 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001796 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00001797 ToObjCPtr->getPointeeType(),
1798 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001799 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001800 return true;
1801 }
Mike Stump1eb44332009-09-09 15:08:12 +00001802 }
Steve Naroff14108da2009-07-10 23:34:53 +00001803 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001804 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001805 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001806 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001807 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001808 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001809 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001810 // to a block pointer type.
1811 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001812 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001813 return true;
1814 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001815 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001816 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001817 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001818 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001819 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001820 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001821 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001822 return true;
1823 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001824 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001825 return false;
1826
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001827 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001828 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001829 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00001830 else if (const BlockPointerType *FromBlockPtr =
1831 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001832 FromPointeeType = FromBlockPtr->getPointeeType();
1833 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001834 return false;
1835
Douglas Gregorc7887512008-12-19 19:13:09 +00001836 // If we have pointers to pointers, recursively check whether this
1837 // is an Objective-C conversion.
1838 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1839 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1840 IncompatibleObjC)) {
1841 // We always complain about this conversion.
1842 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00001843 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001844 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00001845 return true;
1846 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001847 // Allow conversion of pointee being objective-c pointer to another one;
1848 // as in I* to id.
1849 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1850 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1851 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1852 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00001853
Douglas Gregorda80f742010-12-01 21:43:58 +00001854 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001855 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001856 return true;
1857 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001858
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001859 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001860 // differences in the argument and result types are in Objective-C
1861 // pointer conversions. If so, we permit the conversion (but
1862 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001863 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001864 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001865 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001866 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001867 if (FromFunctionType && ToFunctionType) {
1868 // If the function types are exactly the same, this isn't an
1869 // Objective-C pointer conversion.
1870 if (Context.getCanonicalType(FromPointeeType)
1871 == Context.getCanonicalType(ToPointeeType))
1872 return false;
1873
1874 // Perform the quick checks that will tell us whether these
1875 // function types are obviously different.
1876 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1877 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1878 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1879 return false;
1880
1881 bool HasObjCConversion = false;
1882 if (Context.getCanonicalType(FromFunctionType->getResultType())
1883 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1884 // Okay, the types match exactly. Nothing to do.
1885 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1886 ToFunctionType->getResultType(),
1887 ConvertedType, IncompatibleObjC)) {
1888 // Okay, we have an Objective-C pointer conversion.
1889 HasObjCConversion = true;
1890 } else {
1891 // Function types are too different. Abort.
1892 return false;
1893 }
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Douglas Gregorc7887512008-12-19 19:13:09 +00001895 // Check argument types.
1896 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1897 ArgIdx != NumArgs; ++ArgIdx) {
1898 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1899 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1900 if (Context.getCanonicalType(FromArgType)
1901 == Context.getCanonicalType(ToArgType)) {
1902 // Okay, the types match exactly. Nothing to do.
1903 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1904 ConvertedType, IncompatibleObjC)) {
1905 // Okay, we have an Objective-C pointer conversion.
1906 HasObjCConversion = true;
1907 } else {
1908 // Argument types are too different. Abort.
1909 return false;
1910 }
1911 }
1912
1913 if (HasObjCConversion) {
1914 // We had an Objective-C conversion. Allow this pointer
1915 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001916 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00001917 IncompatibleObjC = true;
1918 return true;
1919 }
1920 }
1921
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001922 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001923}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001924
John McCallf85e1932011-06-15 23:02:42 +00001925/// \brief Determine whether this is an Objective-C writeback conversion,
1926/// used for parameter passing when performing automatic reference counting.
1927///
1928/// \param FromType The type we're converting form.
1929///
1930/// \param ToType The type we're converting to.
1931///
1932/// \param ConvertedType The type that will be produced after applying
1933/// this conversion.
1934bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
1935 QualType &ConvertedType) {
1936 if (!getLangOptions().ObjCAutoRefCount ||
1937 Context.hasSameUnqualifiedType(FromType, ToType))
1938 return false;
1939
1940 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
1941 QualType ToPointee;
1942 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
1943 ToPointee = ToPointer->getPointeeType();
1944 else
1945 return false;
1946
1947 Qualifiers ToQuals = ToPointee.getQualifiers();
1948 if (!ToPointee->isObjCLifetimeType() ||
1949 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
1950 !ToQuals.withoutObjCGLifetime().empty())
1951 return false;
1952
1953 // Argument must be a pointer to __strong to __weak.
1954 QualType FromPointee;
1955 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
1956 FromPointee = FromPointer->getPointeeType();
1957 else
1958 return false;
1959
1960 Qualifiers FromQuals = FromPointee.getQualifiers();
1961 if (!FromPointee->isObjCLifetimeType() ||
1962 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
1963 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
1964 return false;
1965
1966 // Make sure that we have compatible qualifiers.
1967 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
1968 if (!ToQuals.compatiblyIncludes(FromQuals))
1969 return false;
1970
1971 // Remove qualifiers from the pointee type we're converting from; they
1972 // aren't used in the compatibility check belong, and we'll be adding back
1973 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
1974 FromPointee = FromPointee.getUnqualifiedType();
1975
1976 // The unqualified form of the pointee types must be compatible.
1977 ToPointee = ToPointee.getUnqualifiedType();
1978 bool IncompatibleObjC;
1979 if (Context.typesAreCompatible(FromPointee, ToPointee))
1980 FromPointee = ToPointee;
1981 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
1982 IncompatibleObjC))
1983 return false;
1984
1985 /// \brief Construct the type we're converting to, which is a pointer to
1986 /// __autoreleasing pointee.
1987 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
1988 ConvertedType = Context.getPointerType(FromPointee);
1989 return true;
1990}
1991
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001992bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1993 QualType& ConvertedType) {
1994 QualType ToPointeeType;
1995 if (const BlockPointerType *ToBlockPtr =
1996 ToType->getAs<BlockPointerType>())
1997 ToPointeeType = ToBlockPtr->getPointeeType();
1998 else
1999 return false;
2000
2001 QualType FromPointeeType;
2002 if (const BlockPointerType *FromBlockPtr =
2003 FromType->getAs<BlockPointerType>())
2004 FromPointeeType = FromBlockPtr->getPointeeType();
2005 else
2006 return false;
2007 // We have pointer to blocks, check whether the only
2008 // differences in the argument and result types are in Objective-C
2009 // pointer conversions. If so, we permit the conversion.
2010
2011 const FunctionProtoType *FromFunctionType
2012 = FromPointeeType->getAs<FunctionProtoType>();
2013 const FunctionProtoType *ToFunctionType
2014 = ToPointeeType->getAs<FunctionProtoType>();
2015
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002016 if (!FromFunctionType || !ToFunctionType)
2017 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002018
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002019 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002020 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002021
2022 // Perform the quick checks that will tell us whether these
2023 // function types are obviously different.
2024 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2025 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2026 return false;
2027
2028 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2029 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2030 if (FromEInfo != ToEInfo)
2031 return false;
2032
2033 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002034 if (Context.hasSameType(FromFunctionType->getResultType(),
2035 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002036 // Okay, the types match exactly. Nothing to do.
2037 } else {
2038 QualType RHS = FromFunctionType->getResultType();
2039 QualType LHS = ToFunctionType->getResultType();
2040 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2041 !RHS.hasQualifiers() && LHS.hasQualifiers())
2042 LHS = LHS.getUnqualifiedType();
2043
2044 if (Context.hasSameType(RHS,LHS)) {
2045 // OK exact match.
2046 } else if (isObjCPointerConversion(RHS, LHS,
2047 ConvertedType, IncompatibleObjC)) {
2048 if (IncompatibleObjC)
2049 return false;
2050 // Okay, we have an Objective-C pointer conversion.
2051 }
2052 else
2053 return false;
2054 }
2055
2056 // Check argument types.
2057 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2058 ArgIdx != NumArgs; ++ArgIdx) {
2059 IncompatibleObjC = false;
2060 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2061 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2062 if (Context.hasSameType(FromArgType, ToArgType)) {
2063 // Okay, the types match exactly. Nothing to do.
2064 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2065 ConvertedType, IncompatibleObjC)) {
2066 if (IncompatibleObjC)
2067 return false;
2068 // Okay, we have an Objective-C pointer conversion.
2069 } else
2070 // Argument types are too different. Abort.
2071 return false;
2072 }
2073 ConvertedType = ToType;
2074 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002075}
2076
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002077/// FunctionArgTypesAreEqual - This routine checks two function proto types
2078/// for equlity of their argument types. Caller has already checked that
2079/// they have same number of arguments. This routine assumes that Objective-C
2080/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002081bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCallf4c73712011-01-19 06:33:43 +00002082 const FunctionProtoType *NewType) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002083 if (!getLangOptions().ObjC1)
2084 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
2085 NewType->arg_type_begin());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002086
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002087 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2088 N = NewType->arg_type_begin(),
2089 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2090 QualType ToType = (*O);
2091 QualType FromType = (*N);
2092 if (ToType != FromType) {
2093 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2094 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002095 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2096 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2097 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2098 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002099 continue;
2100 }
John McCallc12c5bb2010-05-15 11:32:37 +00002101 else if (const ObjCObjectPointerType *PTTo =
2102 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002103 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002104 FromType->getAs<ObjCObjectPointerType>())
2105 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2106 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002107 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002108 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002109 }
2110 }
2111 return true;
2112}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002113
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002114/// CheckPointerConversion - Check the pointer conversion from the
2115/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002116/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002117/// conversions for which IsPointerConversion has already returned
2118/// true. It returns true and produces a diagnostic if there was an
2119/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002120bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002121 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002122 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002123 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002124 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002125 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002126
John McCalldaa8e4e2010-11-15 09:13:47 +00002127 Kind = CK_BitCast;
2128
Chandler Carruth88f0aed2011-04-09 07:32:05 +00002129 if (!IsCStyleOrFunctionalCast &&
2130 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2131 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2132 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruthb6006692011-04-09 07:48:17 +00002133 PDiag(diag::warn_impcast_bool_to_null_pointer)
2134 << ToType << From->getSourceRange());
Douglas Gregord7a95972010-06-08 17:35:15 +00002135
Ted Kremenek6217b802009-07-29 21:53:49 +00002136 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
2137 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002138 QualType FromPointeeType = FromPtrType->getPointeeType(),
2139 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002140
Douglas Gregor5fccd362010-03-03 23:55:11 +00002141 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2142 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002143 // We must have a derived-to-base conversion. Check an
2144 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002145 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2146 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002147 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002148 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002149 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002150
Anders Carlsson61faec12009-09-12 04:46:44 +00002151 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002152 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002153 }
2154 }
Mike Stump1eb44332009-09-09 15:08:12 +00002155 if (const ObjCObjectPointerType *FromPtrType =
John McCalldaa8e4e2010-11-15 09:13:47 +00002156 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002157 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00002158 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002159 // Objective-C++ conversions are always okay.
2160 // FIXME: We should have a different class of conversions for the
2161 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002162 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002163 return false;
John McCalldaa8e4e2010-11-15 09:13:47 +00002164 }
Steve Naroff14108da2009-07-10 23:34:53 +00002165 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002166
2167 // We shouldn't fall into this case unless it's valid for other
2168 // reasons.
2169 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2170 Kind = CK_NullToPointer;
2171
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002172 return false;
2173}
2174
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002175/// IsMemberPointerConversion - Determines whether the conversion of the
2176/// expression From, which has the (possibly adjusted) type FromType, can be
2177/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2178/// If so, returns true and places the converted type (that might differ from
2179/// ToType in its cv-qualifiers at some level) into ConvertedType.
2180bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002181 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002182 bool InOverloadResolution,
2183 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002184 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002185 if (!ToTypePtr)
2186 return false;
2187
2188 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002189 if (From->isNullPointerConstant(Context,
2190 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2191 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002192 ConvertedType = ToType;
2193 return true;
2194 }
2195
2196 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002197 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002198 if (!FromTypePtr)
2199 return false;
2200
2201 // A pointer to member of B can be converted to a pointer to member of D,
2202 // where D is derived from B (C++ 4.11p2).
2203 QualType FromClass(FromTypePtr->getClass(), 0);
2204 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002205
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002206 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2207 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2208 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002209 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2210 ToClass.getTypePtr());
2211 return true;
2212 }
2213
2214 return false;
2215}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002216
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002217/// CheckMemberPointerConversion - Check the member pointer conversion from the
2218/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002219/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002220/// for which IsMemberPointerConversion has already returned true. It returns
2221/// true and produces a diagnostic if there was an error, or returns false
2222/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002223bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002224 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002225 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002226 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002227 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002228 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002229 if (!FromPtrType) {
2230 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002231 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002232 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002233 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002234 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002235 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002236 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002237
Ted Kremenek6217b802009-07-29 21:53:49 +00002238 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002239 assert(ToPtrType && "No member pointer cast has a target type "
2240 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002241
Sebastian Redl21593ac2009-01-28 18:33:18 +00002242 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2243 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002244
Sebastian Redl21593ac2009-01-28 18:33:18 +00002245 // FIXME: What about dependent types?
2246 assert(FromClass->isRecordType() && "Pointer into non-class.");
2247 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002248
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002249 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002250 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002251 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2252 assert(DerivationOkay &&
2253 "Should not have been called if derivation isn't OK.");
2254 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002255
Sebastian Redl21593ac2009-01-28 18:33:18 +00002256 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2257 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002258 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2259 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2260 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2261 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002262 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002263
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002264 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002265 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2266 << FromClass << ToClass << QualType(VBase, 0)
2267 << From->getSourceRange();
2268 return true;
2269 }
2270
John McCall6b2accb2010-02-10 09:31:12 +00002271 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002272 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2273 Paths.front(),
2274 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002275
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002276 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002277 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002278 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002279 return false;
2280}
2281
Douglas Gregor98cd5992008-10-21 23:43:52 +00002282/// IsQualificationConversion - Determines whether the conversion from
2283/// an rvalue of type FromType to ToType is a qualification conversion
2284/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002285///
2286/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2287/// when the qualification conversion involves a change in the Objective-C
2288/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002289bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002290Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002291 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002292 FromType = Context.getCanonicalType(FromType);
2293 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002294 ObjCLifetimeConversion = false;
2295
Douglas Gregor98cd5992008-10-21 23:43:52 +00002296 // If FromType and ToType are the same type, this is not a
2297 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002298 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002299 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002300
Douglas Gregor98cd5992008-10-21 23:43:52 +00002301 // (C++ 4.4p4):
2302 // A conversion can add cv-qualifiers at levels other than the first
2303 // in multi-level pointers, subject to the following rules: [...]
2304 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002305 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002306 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002307 // Within each iteration of the loop, we check the qualifiers to
2308 // determine if this still looks like a qualification
2309 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002310 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002311 // until there are no more pointers or pointers-to-members left to
2312 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002313 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002314
Douglas Gregor621c92a2011-04-25 18:40:17 +00002315 Qualifiers FromQuals = FromType.getQualifiers();
2316 Qualifiers ToQuals = ToType.getQualifiers();
2317
John McCallf85e1932011-06-15 23:02:42 +00002318 // Objective-C ARC:
2319 // Check Objective-C lifetime conversions.
2320 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2321 UnwrappedAnyPointer) {
2322 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2323 ObjCLifetimeConversion = true;
2324 FromQuals.removeObjCLifetime();
2325 ToQuals.removeObjCLifetime();
2326 } else {
2327 // Qualification conversions cannot cast between different
2328 // Objective-C lifetime qualifiers.
2329 return false;
2330 }
2331 }
2332
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002333 // Allow addition/removal of GC attributes but not changing GC attributes.
2334 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2335 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2336 FromQuals.removeObjCGCAttr();
2337 ToQuals.removeObjCGCAttr();
2338 }
2339
Douglas Gregor98cd5992008-10-21 23:43:52 +00002340 // -- for every j > 0, if const is in cv 1,j then const is in cv
2341 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002342 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002343 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002344
Douglas Gregor98cd5992008-10-21 23:43:52 +00002345 // -- if the cv 1,j and cv 2,j are different, then const is in
2346 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002347 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002348 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002349 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002350
Douglas Gregor98cd5992008-10-21 23:43:52 +00002351 // Keep track of whether all prior cv-qualifiers in the "to" type
2352 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002353 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002354 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002355 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002356
2357 // We are left with FromType and ToType being the pointee types
2358 // after unwrapping the original FromType and ToType the same number
2359 // of types. If we unwrapped any pointers, and if FromType and
2360 // ToType have the same unqualified type (since we checked
2361 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002362 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002363}
2364
Douglas Gregor734d9862009-01-30 23:27:23 +00002365/// Determines whether there is a user-defined conversion sequence
2366/// (C++ [over.ics.user]) that converts expression From to the type
2367/// ToType. If such a conversion exists, User will contain the
2368/// user-defined conversion sequence that performs such a conversion
2369/// and this routine will return true. Otherwise, this routine returns
2370/// false and User is unspecified.
2371///
Douglas Gregor734d9862009-01-30 23:27:23 +00002372/// \param AllowExplicit true if the conversion should consider C++0x
2373/// "explicit" conversion functions as well as non-explicit conversion
2374/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002375static OverloadingResult
2376IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2377 UserDefinedConversionSequence& User,
2378 OverloadCandidateSet& CandidateSet,
2379 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002380 // Whether we will only visit constructors.
2381 bool ConstructorsOnly = false;
2382
2383 // If the type we are conversion to is a class type, enumerate its
2384 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002385 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002386 // C++ [over.match.ctor]p1:
2387 // When objects of class type are direct-initialized (8.5), or
2388 // copy-initialized from an expression of the same or a
2389 // derived class type (8.5), overload resolution selects the
2390 // constructor. [...] For copy-initialization, the candidate
2391 // functions are all the converting constructors (12.3.1) of
2392 // that class. The argument list is the expression-list within
2393 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002394 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002395 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002396 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002397 ConstructorsOnly = true;
2398
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002399 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2400 // RequireCompleteType may have returned true due to some invalid decl
2401 // during template instantiation, but ToType may be complete enough now
2402 // to try to recover.
2403 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002404 // We're not going to find any constructors.
2405 } else if (CXXRecordDecl *ToRecordDecl
2406 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002407 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002408 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002409 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002410 NamedDecl *D = *Con;
2411 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2412
Douglas Gregordec06662009-08-21 18:42:58 +00002413 // Find the constructor (which may be a template).
2414 CXXConstructorDecl *Constructor = 0;
2415 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002416 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002417 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002418 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002419 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2420 else
John McCall9aa472c2010-03-19 07:35:19 +00002421 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002422
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00002423 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00002424 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00002425 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002426 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2427 /*ExplicitArgs*/ 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002428 &From, 1, CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002429 /*SuppressUserConversions=*/
2430 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002431 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002432 // Allow one user-defined conversion when user specifies a
2433 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002434 S.AddOverloadCandidate(Constructor, FoundDecl,
2435 &From, 1, CandidateSet,
2436 /*SuppressUserConversions=*/
2437 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002438 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002439 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002440 }
2441 }
2442
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002443 // Enumerate conversion functions, if we're allowed to.
2444 if (ConstructorsOnly) {
John McCall120d63c2010-08-24 20:38:10 +00002445 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2446 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002447 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002448 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002449 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002450 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002451 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2452 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002453 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002454 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002455 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002456 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002457 DeclAccessPair FoundDecl = I.getPair();
2458 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002459 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2460 if (isa<UsingShadowDecl>(D))
2461 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2462
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002463 CXXConversionDecl *Conv;
2464 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002465 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2466 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002467 else
John McCall32daa422010-03-31 01:36:47 +00002468 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002469
2470 if (AllowExplicit || !Conv->isExplicit()) {
2471 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002472 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2473 ActingContext, From, ToType,
2474 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002475 else
John McCall120d63c2010-08-24 20:38:10 +00002476 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2477 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002478 }
2479 }
2480 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002481 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002482
2483 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002484 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002485 case OR_Success:
2486 // Record the standard conversion we used and the conversion function.
2487 if (CXXConstructorDecl *Constructor
2488 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth25ca4212011-02-25 19:41:05 +00002489 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2490
John McCall120d63c2010-08-24 20:38:10 +00002491 // C++ [over.ics.user]p1:
2492 // If the user-defined conversion is specified by a
2493 // constructor (12.3.1), the initial standard conversion
2494 // sequence converts the source type to the type required by
2495 // the argument of the constructor.
2496 //
2497 QualType ThisType = Constructor->getThisType(S.Context);
2498 if (Best->Conversions[0].isEllipsis())
2499 User.EllipsisConversion = true;
2500 else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002501 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002502 User.EllipsisConversion = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002503 }
John McCall120d63c2010-08-24 20:38:10 +00002504 User.ConversionFunction = Constructor;
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002505 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall120d63c2010-08-24 20:38:10 +00002506 User.After.setAsIdentityConversion();
2507 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2508 User.After.setAllToTypes(ToType);
2509 return OR_Success;
2510 } else if (CXXConversionDecl *Conversion
2511 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth25ca4212011-02-25 19:41:05 +00002512 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2513
John McCall120d63c2010-08-24 20:38:10 +00002514 // C++ [over.ics.user]p1:
2515 //
2516 // [...] If the user-defined conversion is specified by a
2517 // conversion function (12.3.2), the initial standard
2518 // conversion sequence converts the source type to the
2519 // implicit object parameter of the conversion function.
2520 User.Before = Best->Conversions[0].Standard;
2521 User.ConversionFunction = Conversion;
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002522 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall120d63c2010-08-24 20:38:10 +00002523 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002524
John McCall120d63c2010-08-24 20:38:10 +00002525 // C++ [over.ics.user]p2:
2526 // The second standard conversion sequence converts the
2527 // result of the user-defined conversion to the target type
2528 // for the sequence. Since an implicit conversion sequence
2529 // is an initialization, the special rules for
2530 // initialization by user-defined conversion apply when
2531 // selecting the best user-defined conversion for a
2532 // user-defined conversion sequence (see 13.3.3 and
2533 // 13.3.3.1).
2534 User.After = Best->FinalConversion;
2535 return OR_Success;
2536 } else {
2537 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002538 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002539 }
2540
John McCall120d63c2010-08-24 20:38:10 +00002541 case OR_No_Viable_Function:
2542 return OR_No_Viable_Function;
2543 case OR_Deleted:
2544 // No conversion here! We're done.
2545 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002546
John McCall120d63c2010-08-24 20:38:10 +00002547 case OR_Ambiguous:
2548 return OR_Ambiguous;
2549 }
2550
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002551 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002552}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002553
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002554bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002555Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002556 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002557 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002558 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00002559 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002560 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002561 if (OvResult == OR_Ambiguous)
2562 Diag(From->getSourceRange().getBegin(),
2563 diag::err_typecheck_ambiguous_condition)
2564 << From->getType() << ToType << From->getSourceRange();
2565 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2566 Diag(From->getSourceRange().getBegin(),
2567 diag::err_typecheck_nonviable_condition)
2568 << From->getType() << ToType << From->getSourceRange();
2569 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002570 return false;
John McCall120d63c2010-08-24 20:38:10 +00002571 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002572 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002573}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002574
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002575/// CompareImplicitConversionSequences - Compare two implicit
2576/// conversion sequences to determine whether one is better than the
2577/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00002578static ImplicitConversionSequence::CompareKind
2579CompareImplicitConversionSequences(Sema &S,
2580 const ImplicitConversionSequence& ICS1,
2581 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002582{
2583 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2584 // conversion sequences (as defined in 13.3.3.1)
2585 // -- a standard conversion sequence (13.3.3.1.1) is a better
2586 // conversion sequence than a user-defined conversion sequence or
2587 // an ellipsis conversion sequence, and
2588 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2589 // conversion sequence than an ellipsis conversion sequence
2590 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002591 //
John McCall1d318332010-01-12 00:44:57 +00002592 // C++0x [over.best.ics]p10:
2593 // For the purpose of ranking implicit conversion sequences as
2594 // described in 13.3.3.2, the ambiguous conversion sequence is
2595 // treated as a user-defined sequence that is indistinguishable
2596 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002597 if (ICS1.getKindRank() < ICS2.getKindRank())
2598 return ImplicitConversionSequence::Better;
2599 else if (ICS2.getKindRank() < ICS1.getKindRank())
2600 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002601
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002602 // The following checks require both conversion sequences to be of
2603 // the same kind.
2604 if (ICS1.getKind() != ICS2.getKind())
2605 return ImplicitConversionSequence::Indistinguishable;
2606
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002607 // Two implicit conversion sequences of the same form are
2608 // indistinguishable conversion sequences unless one of the
2609 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002610 if (ICS1.isStandard())
John McCall120d63c2010-08-24 20:38:10 +00002611 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002612 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002613 // User-defined conversion sequence U1 is a better conversion
2614 // sequence than another user-defined conversion sequence U2 if
2615 // they contain the same user-defined conversion function or
2616 // constructor and if the second standard conversion sequence of
2617 // U1 is better than the second standard conversion sequence of
2618 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002619 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002620 ICS2.UserDefined.ConversionFunction)
John McCall120d63c2010-08-24 20:38:10 +00002621 return CompareStandardConversionSequences(S,
2622 ICS1.UserDefined.After,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002623 ICS2.UserDefined.After);
2624 }
2625
2626 return ImplicitConversionSequence::Indistinguishable;
2627}
2628
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002629static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2630 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2631 Qualifiers Quals;
2632 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002633 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002634 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002635
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002636 return Context.hasSameUnqualifiedType(T1, T2);
2637}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002638
Douglas Gregorad323a82010-01-27 03:51:04 +00002639// Per 13.3.3.2p3, compare the given standard conversion sequences to
2640// determine if one is a proper subset of the other.
2641static ImplicitConversionSequence::CompareKind
2642compareStandardConversionSubsets(ASTContext &Context,
2643 const StandardConversionSequence& SCS1,
2644 const StandardConversionSequence& SCS2) {
2645 ImplicitConversionSequence::CompareKind Result
2646 = ImplicitConversionSequence::Indistinguishable;
2647
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002648 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002649 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00002650 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2651 return ImplicitConversionSequence::Better;
2652 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2653 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002654
Douglas Gregorad323a82010-01-27 03:51:04 +00002655 if (SCS1.Second != SCS2.Second) {
2656 if (SCS1.Second == ICK_Identity)
2657 Result = ImplicitConversionSequence::Better;
2658 else if (SCS2.Second == ICK_Identity)
2659 Result = ImplicitConversionSequence::Worse;
2660 else
2661 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002662 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002663 return ImplicitConversionSequence::Indistinguishable;
2664
2665 if (SCS1.Third == SCS2.Third) {
2666 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2667 : ImplicitConversionSequence::Indistinguishable;
2668 }
2669
2670 if (SCS1.Third == ICK_Identity)
2671 return Result == ImplicitConversionSequence::Worse
2672 ? ImplicitConversionSequence::Indistinguishable
2673 : ImplicitConversionSequence::Better;
2674
2675 if (SCS2.Third == ICK_Identity)
2676 return Result == ImplicitConversionSequence::Better
2677 ? ImplicitConversionSequence::Indistinguishable
2678 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002679
Douglas Gregorad323a82010-01-27 03:51:04 +00002680 return ImplicitConversionSequence::Indistinguishable;
2681}
2682
Douglas Gregor440a4832011-01-26 14:52:12 +00002683/// \brief Determine whether one of the given reference bindings is better
2684/// than the other based on what kind of bindings they are.
2685static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2686 const StandardConversionSequence &SCS2) {
2687 // C++0x [over.ics.rank]p3b4:
2688 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2689 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002690 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00002691 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002692 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00002693 // reference*.
2694 //
2695 // FIXME: Rvalue references. We're going rogue with the above edits,
2696 // because the semantics in the current C++0x working paper (N3225 at the
2697 // time of this writing) break the standard definition of std::forward
2698 // and std::reference_wrapper when dealing with references to functions.
2699 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00002700 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2701 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2702 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002703
Douglas Gregor440a4832011-01-26 14:52:12 +00002704 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2705 SCS2.IsLvalueReference) ||
2706 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2707 !SCS2.IsLvalueReference);
2708}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002709
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002710/// CompareStandardConversionSequences - Compare two standard
2711/// conversion sequences to determine whether one is better than the
2712/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00002713static ImplicitConversionSequence::CompareKind
2714CompareStandardConversionSequences(Sema &S,
2715 const StandardConversionSequence& SCS1,
2716 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002717{
2718 // Standard conversion sequence S1 is a better conversion sequence
2719 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2720
2721 // -- S1 is a proper subsequence of S2 (comparing the conversion
2722 // sequences in the canonical form defined by 13.3.3.1.1,
2723 // excluding any Lvalue Transformation; the identity conversion
2724 // sequence is considered to be a subsequence of any
2725 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002726 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00002727 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00002728 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002729
2730 // -- the rank of S1 is better than the rank of S2 (by the rules
2731 // defined below), or, if not that,
2732 ImplicitConversionRank Rank1 = SCS1.getRank();
2733 ImplicitConversionRank Rank2 = SCS2.getRank();
2734 if (Rank1 < Rank2)
2735 return ImplicitConversionSequence::Better;
2736 else if (Rank2 < Rank1)
2737 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002738
Douglas Gregor57373262008-10-22 14:17:15 +00002739 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2740 // are indistinguishable unless one of the following rules
2741 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002742
Douglas Gregor57373262008-10-22 14:17:15 +00002743 // A conversion that is not a conversion of a pointer, or
2744 // pointer to member, to bool is better than another conversion
2745 // that is such a conversion.
2746 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2747 return SCS2.isPointerConversionToBool()
2748 ? ImplicitConversionSequence::Better
2749 : ImplicitConversionSequence::Worse;
2750
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002751 // C++ [over.ics.rank]p4b2:
2752 //
2753 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002754 // conversion of B* to A* is better than conversion of B* to
2755 // void*, and conversion of A* to void* is better than conversion
2756 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002757 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002758 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002759 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002760 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002761 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2762 // Exactly one of the conversion sequences is a conversion to
2763 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002764 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2765 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002766 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2767 // Neither conversion sequence converts to a void pointer; compare
2768 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002769 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00002770 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002771 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00002772 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2773 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002774 // Both conversion sequences are conversions to void
2775 // pointers. Compare the source types to determine if there's an
2776 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002777 QualType FromType1 = SCS1.getFromType();
2778 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002779
2780 // Adjust the types we're converting from via the array-to-pointer
2781 // conversion, if we need to.
2782 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002783 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002784 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002785 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002786
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00002787 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2788 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002789
John McCall120d63c2010-08-24 20:38:10 +00002790 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00002791 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002792 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00002793 return ImplicitConversionSequence::Worse;
2794
2795 // Objective-C++: If one interface is more specific than the
2796 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00002797 const ObjCObjectPointerType* FromObjCPtr1
2798 = FromType1->getAs<ObjCObjectPointerType>();
2799 const ObjCObjectPointerType* FromObjCPtr2
2800 = FromType2->getAs<ObjCObjectPointerType>();
2801 if (FromObjCPtr1 && FromObjCPtr2) {
2802 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2803 FromObjCPtr2);
2804 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2805 FromObjCPtr1);
2806 if (AssignLeft != AssignRight) {
2807 return AssignLeft? ImplicitConversionSequence::Better
2808 : ImplicitConversionSequence::Worse;
2809 }
Douglas Gregor01919692009-12-13 21:37:05 +00002810 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002811 }
Douglas Gregor57373262008-10-22 14:17:15 +00002812
2813 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2814 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002815 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00002816 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002817 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002818
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002819 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00002820 // Check for a better reference binding based on the kind of bindings.
2821 if (isBetterReferenceBindingKind(SCS1, SCS2))
2822 return ImplicitConversionSequence::Better;
2823 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2824 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002825
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002826 // C++ [over.ics.rank]p3b4:
2827 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2828 // which the references refer are the same type except for
2829 // top-level cv-qualifiers, and the type to which the reference
2830 // initialized by S2 refers is more cv-qualified than the type
2831 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002832 QualType T1 = SCS1.getToType(2);
2833 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002834 T1 = S.Context.getCanonicalType(T1);
2835 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002836 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002837 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2838 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002839 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00002840 // Objective-C++ ARC: If the references refer to objects with different
2841 // lifetimes, prefer bindings that don't change lifetime.
2842 if (SCS1.ObjCLifetimeConversionBinding !=
2843 SCS2.ObjCLifetimeConversionBinding) {
2844 return SCS1.ObjCLifetimeConversionBinding
2845 ? ImplicitConversionSequence::Worse
2846 : ImplicitConversionSequence::Better;
2847 }
2848
Chandler Carruth6df868e2010-12-12 08:17:55 +00002849 // If the type is an array type, promote the element qualifiers to the
2850 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002851 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002852 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002853 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002854 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002855 if (T2.isMoreQualifiedThan(T1))
2856 return ImplicitConversionSequence::Better;
2857 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00002858 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002859 }
2860 }
Douglas Gregor57373262008-10-22 14:17:15 +00002861
2862 return ImplicitConversionSequence::Indistinguishable;
2863}
2864
2865/// CompareQualificationConversions - Compares two standard conversion
2866/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002867/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2868ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002869CompareQualificationConversions(Sema &S,
2870 const StandardConversionSequence& SCS1,
2871 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002872 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002873 // -- S1 and S2 differ only in their qualification conversion and
2874 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2875 // cv-qualification signature of type T1 is a proper subset of
2876 // the cv-qualification signature of type T2, and S1 is not the
2877 // deprecated string literal array-to-pointer conversion (4.2).
2878 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2879 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2880 return ImplicitConversionSequence::Indistinguishable;
2881
2882 // FIXME: the example in the standard doesn't use a qualification
2883 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002884 QualType T1 = SCS1.getToType(2);
2885 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002886 T1 = S.Context.getCanonicalType(T1);
2887 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002888 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002889 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2890 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002891
2892 // If the types are the same, we won't learn anything by unwrapped
2893 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002894 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002895 return ImplicitConversionSequence::Indistinguishable;
2896
Chandler Carruth28e318c2009-12-29 07:16:59 +00002897 // If the type is an array type, promote the element qualifiers to the type
2898 // for comparison.
2899 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002900 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002901 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002902 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002903
Mike Stump1eb44332009-09-09 15:08:12 +00002904 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002905 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00002906
2907 // Objective-C++ ARC:
2908 // Prefer qualification conversions not involving a change in lifetime
2909 // to qualification conversions that do not change lifetime.
2910 if (SCS1.QualificationIncludesObjCLifetime !=
2911 SCS2.QualificationIncludesObjCLifetime) {
2912 Result = SCS1.QualificationIncludesObjCLifetime
2913 ? ImplicitConversionSequence::Worse
2914 : ImplicitConversionSequence::Better;
2915 }
2916
John McCall120d63c2010-08-24 20:38:10 +00002917 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002918 // Within each iteration of the loop, we check the qualifiers to
2919 // determine if this still looks like a qualification
2920 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002921 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002922 // until there are no more pointers or pointers-to-members left
2923 // to unwrap. This essentially mimics what
2924 // IsQualificationConversion does, but here we're checking for a
2925 // strict subset of qualifiers.
2926 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2927 // The qualifiers are the same, so this doesn't tell us anything
2928 // about how the sequences rank.
2929 ;
2930 else if (T2.isMoreQualifiedThan(T1)) {
2931 // T1 has fewer qualifiers, so it could be the better sequence.
2932 if (Result == ImplicitConversionSequence::Worse)
2933 // Neither has qualifiers that are a subset of the other's
2934 // qualifiers.
2935 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002936
Douglas Gregor57373262008-10-22 14:17:15 +00002937 Result = ImplicitConversionSequence::Better;
2938 } else if (T1.isMoreQualifiedThan(T2)) {
2939 // T2 has fewer qualifiers, so it could be the better sequence.
2940 if (Result == ImplicitConversionSequence::Better)
2941 // Neither has qualifiers that are a subset of the other's
2942 // qualifiers.
2943 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002944
Douglas Gregor57373262008-10-22 14:17:15 +00002945 Result = ImplicitConversionSequence::Worse;
2946 } else {
2947 // Qualifiers are disjoint.
2948 return ImplicitConversionSequence::Indistinguishable;
2949 }
2950
2951 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00002952 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002953 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002954 }
2955
Douglas Gregor57373262008-10-22 14:17:15 +00002956 // Check that the winning standard conversion sequence isn't using
2957 // the deprecated string literal array to pointer conversion.
2958 switch (Result) {
2959 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002960 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002961 Result = ImplicitConversionSequence::Indistinguishable;
2962 break;
2963
2964 case ImplicitConversionSequence::Indistinguishable:
2965 break;
2966
2967 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002968 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002969 Result = ImplicitConversionSequence::Indistinguishable;
2970 break;
2971 }
2972
2973 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002974}
2975
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002976/// CompareDerivedToBaseConversions - Compares two standard conversion
2977/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002978/// various kinds of derived-to-base conversions (C++
2979/// [over.ics.rank]p4b3). As part of these checks, we also look at
2980/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002981ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002982CompareDerivedToBaseConversions(Sema &S,
2983 const StandardConversionSequence& SCS1,
2984 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002985 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002986 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002987 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002988 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002989
2990 // Adjust the types we're converting from via the array-to-pointer
2991 // conversion, if we need to.
2992 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002993 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002994 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002995 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002996
2997 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00002998 FromType1 = S.Context.getCanonicalType(FromType1);
2999 ToType1 = S.Context.getCanonicalType(ToType1);
3000 FromType2 = S.Context.getCanonicalType(FromType2);
3001 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003002
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003003 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003004 //
3005 // If class B is derived directly or indirectly from class A and
3006 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003007 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003008 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003009 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003010 SCS2.Second == ICK_Pointer_Conversion &&
3011 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3012 FromType1->isPointerType() && FromType2->isPointerType() &&
3013 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003014 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003015 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003016 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003017 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003018 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003019 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003020 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003021 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003022
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003023 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003024 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003025 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003026 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003027 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003028 return ImplicitConversionSequence::Worse;
3029 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003030
3031 // -- conversion of B* to A* is better than conversion of C* to A*,
3032 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003033 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003034 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003035 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003036 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003037 }
3038 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3039 SCS2.Second == ICK_Pointer_Conversion) {
3040 const ObjCObjectPointerType *FromPtr1
3041 = FromType1->getAs<ObjCObjectPointerType>();
3042 const ObjCObjectPointerType *FromPtr2
3043 = FromType2->getAs<ObjCObjectPointerType>();
3044 const ObjCObjectPointerType *ToPtr1
3045 = ToType1->getAs<ObjCObjectPointerType>();
3046 const ObjCObjectPointerType *ToPtr2
3047 = ToType2->getAs<ObjCObjectPointerType>();
3048
3049 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3050 // Apply the same conversion ranking rules for Objective-C pointer types
3051 // that we do for C++ pointers to class types. However, we employ the
3052 // Objective-C pseudo-subtyping relationship used for assignment of
3053 // Objective-C pointer types.
3054 bool FromAssignLeft
3055 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3056 bool FromAssignRight
3057 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3058 bool ToAssignLeft
3059 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3060 bool ToAssignRight
3061 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3062
3063 // A conversion to an a non-id object pointer type or qualified 'id'
3064 // type is better than a conversion to 'id'.
3065 if (ToPtr1->isObjCIdType() &&
3066 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3067 return ImplicitConversionSequence::Worse;
3068 if (ToPtr2->isObjCIdType() &&
3069 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3070 return ImplicitConversionSequence::Better;
3071
3072 // A conversion to a non-id object pointer type is better than a
3073 // conversion to a qualified 'id' type
3074 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3075 return ImplicitConversionSequence::Worse;
3076 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3077 return ImplicitConversionSequence::Better;
3078
3079 // A conversion to an a non-Class object pointer type or qualified 'Class'
3080 // type is better than a conversion to 'Class'.
3081 if (ToPtr1->isObjCClassType() &&
3082 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3083 return ImplicitConversionSequence::Worse;
3084 if (ToPtr2->isObjCClassType() &&
3085 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3086 return ImplicitConversionSequence::Better;
3087
3088 // A conversion to a non-Class object pointer type is better than a
3089 // conversion to a qualified 'Class' type.
3090 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3091 return ImplicitConversionSequence::Worse;
3092 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3093 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003094
Douglas Gregor395cc372011-01-31 18:51:41 +00003095 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3096 if (S.Context.hasSameType(FromType1, FromType2) &&
3097 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3098 (ToAssignLeft != ToAssignRight))
3099 return ToAssignLeft? ImplicitConversionSequence::Worse
3100 : ImplicitConversionSequence::Better;
3101
3102 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3103 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3104 (FromAssignLeft != FromAssignRight))
3105 return FromAssignLeft? ImplicitConversionSequence::Better
3106 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003107 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003108 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003109
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003110 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003111 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3112 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3113 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003114 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003115 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003116 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003117 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003118 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003119 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003120 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003121 ToType2->getAs<MemberPointerType>();
3122 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3123 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3124 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3125 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3126 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3127 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3128 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3129 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003130 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003131 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003132 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003133 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003134 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003135 return ImplicitConversionSequence::Better;
3136 }
3137 // conversion of B::* to C::* is better than conversion of A::* to C::*
3138 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003139 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003140 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003141 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003142 return ImplicitConversionSequence::Worse;
3143 }
3144 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003145
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003146 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003147 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003148 // -- binding of an expression of type C to a reference of type
3149 // B& is better than binding an expression of type C to a
3150 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003151 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3152 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3153 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003154 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003155 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003156 return ImplicitConversionSequence::Worse;
3157 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003158
Douglas Gregor225c41e2008-11-03 19:09:14 +00003159 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003160 // -- binding of an expression of type B to a reference of type
3161 // A& is better than binding an expression of type C to a
3162 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003163 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3164 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3165 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003166 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003167 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003168 return ImplicitConversionSequence::Worse;
3169 }
3170 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003171
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003172 return ImplicitConversionSequence::Indistinguishable;
3173}
3174
Douglas Gregorabe183d2010-04-13 16:31:36 +00003175/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3176/// determine whether they are reference-related,
3177/// reference-compatible, reference-compatible with added
3178/// qualification, or incompatible, for use in C++ initialization by
3179/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3180/// type, and the first type (T1) is the pointee type of the reference
3181/// type being initialized.
3182Sema::ReferenceCompareResult
3183Sema::CompareReferenceRelationship(SourceLocation Loc,
3184 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003185 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003186 bool &ObjCConversion,
3187 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003188 assert(!OrigT1->isReferenceType() &&
3189 "T1 must be the pointee type of the reference type");
3190 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3191
3192 QualType T1 = Context.getCanonicalType(OrigT1);
3193 QualType T2 = Context.getCanonicalType(OrigT2);
3194 Qualifiers T1Quals, T2Quals;
3195 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3196 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3197
3198 // C++ [dcl.init.ref]p4:
3199 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3200 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3201 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003202 DerivedToBase = false;
3203 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003204 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003205 if (UnqualT1 == UnqualT2) {
3206 // Nothing to do.
3207 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003208 IsDerivedFrom(UnqualT2, UnqualT1))
3209 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003210 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3211 UnqualT2->isObjCObjectOrInterfaceType() &&
3212 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3213 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003214 else
3215 return Ref_Incompatible;
3216
3217 // At this point, we know that T1 and T2 are reference-related (at
3218 // least).
3219
3220 // If the type is an array type, promote the element qualifiers to the type
3221 // for comparison.
3222 if (isa<ArrayType>(T1) && T1Quals)
3223 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3224 if (isa<ArrayType>(T2) && T2Quals)
3225 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3226
3227 // C++ [dcl.init.ref]p4:
3228 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3229 // reference-related to T2 and cv1 is the same cv-qualification
3230 // as, or greater cv-qualification than, cv2. For purposes of
3231 // overload resolution, cases for which cv1 is greater
3232 // cv-qualification than cv2 are identified as
3233 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003234 //
3235 // Note that we also require equivalence of Objective-C GC and address-space
3236 // qualifiers when performing these computations, so that e.g., an int in
3237 // address space 1 is not reference-compatible with an int in address
3238 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003239 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3240 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3241 T1Quals.removeObjCLifetime();
3242 T2Quals.removeObjCLifetime();
3243 ObjCLifetimeConversion = true;
3244 }
3245
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003246 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003247 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003248 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003249 return Ref_Compatible_With_Added_Qualification;
3250 else
3251 return Ref_Related;
3252}
3253
Douglas Gregor604eb652010-08-11 02:15:33 +00003254/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003255/// with DeclType. Return true if something definite is found.
3256static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003257FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3258 QualType DeclType, SourceLocation DeclLoc,
3259 Expr *Init, QualType T2, bool AllowRvalues,
3260 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003261 assert(T2->isRecordType() && "Can only find conversions of record types.");
3262 CXXRecordDecl *T2RecordDecl
3263 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3264
3265 OverloadCandidateSet CandidateSet(DeclLoc);
3266 const UnresolvedSetImpl *Conversions
3267 = T2RecordDecl->getVisibleConversionFunctions();
3268 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3269 E = Conversions->end(); I != E; ++I) {
3270 NamedDecl *D = *I;
3271 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3272 if (isa<UsingShadowDecl>(D))
3273 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3274
3275 FunctionTemplateDecl *ConvTemplate
3276 = dyn_cast<FunctionTemplateDecl>(D);
3277 CXXConversionDecl *Conv;
3278 if (ConvTemplate)
3279 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3280 else
3281 Conv = cast<CXXConversionDecl>(D);
3282
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003283 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003284 // explicit conversions, skip it.
3285 if (!AllowExplicit && Conv->isExplicit())
3286 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003287
Douglas Gregor604eb652010-08-11 02:15:33 +00003288 if (AllowRvalues) {
3289 bool DerivedToBase = false;
3290 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003291 bool ObjCLifetimeConversion = false;
Douglas Gregor604eb652010-08-11 02:15:33 +00003292 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00003293 S.CompareReferenceRelationship(
3294 DeclLoc,
3295 Conv->getConversionType().getNonReferenceType()
3296 .getUnqualifiedType(),
3297 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00003298 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00003299 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00003300 continue;
3301 } else {
3302 // If the conversion function doesn't return a reference type,
3303 // it can't be considered for this conversion. An rvalue reference
3304 // is only acceptable if its referencee is a function type.
3305
3306 const ReferenceType *RefType =
3307 Conv->getConversionType()->getAs<ReferenceType>();
3308 if (!RefType ||
3309 (!RefType->isLValueReferenceType() &&
3310 !RefType->getPointeeType()->isFunctionType()))
3311 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003312 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003313
Douglas Gregor604eb652010-08-11 02:15:33 +00003314 if (ConvTemplate)
3315 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003316 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00003317 else
3318 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003319 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003320 }
3321
3322 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003323 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003324 case OR_Success:
3325 // C++ [over.ics.ref]p1:
3326 //
3327 // [...] If the parameter binds directly to the result of
3328 // applying a conversion function to the argument
3329 // expression, the implicit conversion sequence is a
3330 // user-defined conversion sequence (13.3.3.1.2), with the
3331 // second standard conversion sequence either an identity
3332 // conversion or, if the conversion function returns an
3333 // entity of a type that is a derived class of the parameter
3334 // type, a derived-to-base Conversion.
3335 if (!Best->FinalConversion.DirectBinding)
3336 return false;
3337
Chandler Carruth25ca4212011-02-25 19:41:05 +00003338 if (Best->Function)
3339 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003340 ICS.setUserDefined();
3341 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3342 ICS.UserDefined.After = Best->FinalConversion;
3343 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor83eecbe2011-01-20 01:32:05 +00003344 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redl4680bf22010-06-30 18:13:39 +00003345 ICS.UserDefined.EllipsisConversion = false;
3346 assert(ICS.UserDefined.After.ReferenceBinding &&
3347 ICS.UserDefined.After.DirectBinding &&
3348 "Expected a direct reference binding!");
3349 return true;
3350
3351 case OR_Ambiguous:
3352 ICS.setAmbiguous();
3353 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3354 Cand != CandidateSet.end(); ++Cand)
3355 if (Cand->Viable)
3356 ICS.Ambiguous.addConversion(Cand->Function);
3357 return true;
3358
3359 case OR_No_Viable_Function:
3360 case OR_Deleted:
3361 // There was no suitable conversion, or we found a deleted
3362 // conversion; continue with other checks.
3363 return false;
3364 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003365
Eric Christopher1c3d5022010-06-30 18:36:32 +00003366 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003367}
3368
Douglas Gregorabe183d2010-04-13 16:31:36 +00003369/// \brief Compute an implicit conversion sequence for reference
3370/// initialization.
3371static ImplicitConversionSequence
3372TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3373 SourceLocation DeclLoc,
3374 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003375 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003376 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3377
3378 // Most paths end in a failed conversion.
3379 ImplicitConversionSequence ICS;
3380 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3381
3382 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3383 QualType T2 = Init->getType();
3384
3385 // If the initializer is the address of an overloaded function, try
3386 // to resolve the overloaded function. If all goes well, T2 is the
3387 // type of the resulting function.
3388 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3389 DeclAccessPair Found;
3390 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3391 false, Found))
3392 T2 = Fn->getType();
3393 }
3394
3395 // Compute some basic properties of the types and the initializer.
3396 bool isRValRef = DeclType->isRValueReferenceType();
3397 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003398 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003399 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003400 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003401 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003402 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003403 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003404
Douglas Gregorabe183d2010-04-13 16:31:36 +00003405
Sebastian Redl4680bf22010-06-30 18:13:39 +00003406 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00003407 // A reference to type "cv1 T1" is initialized by an expression
3408 // of type "cv2 T2" as follows:
3409
Sebastian Redl4680bf22010-06-30 18:13:39 +00003410 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003411 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003412 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3413 // reference-compatible with "cv2 T2," or
3414 //
3415 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3416 if (InitCategory.isLValue() &&
3417 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003418 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00003419 // When a parameter of reference type binds directly (8.5.3)
3420 // to an argument expression, the implicit conversion sequence
3421 // is the identity conversion, unless the argument expression
3422 // has a type that is a derived class of the parameter type,
3423 // in which case the implicit conversion sequence is a
3424 // derived-to-base Conversion (13.3.3.1).
3425 ICS.setStandard();
3426 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00003427 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3428 : ObjCConversion? ICK_Compatible_Conversion
3429 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003430 ICS.Standard.Third = ICK_Identity;
3431 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3432 ICS.Standard.setToType(0, T2);
3433 ICS.Standard.setToType(1, T1);
3434 ICS.Standard.setToType(2, T1);
3435 ICS.Standard.ReferenceBinding = true;
3436 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003437 ICS.Standard.IsLvalueReference = !isRValRef;
3438 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3439 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003440 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003441 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003442 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003443
Sebastian Redl4680bf22010-06-30 18:13:39 +00003444 // Nothing more to do: the inaccessibility/ambiguity check for
3445 // derived-to-base conversions is suppressed when we're
3446 // computing the implicit conversion sequence (C++
3447 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00003448 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003449 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00003450
Sebastian Redl4680bf22010-06-30 18:13:39 +00003451 // -- has a class type (i.e., T2 is a class type), where T1 is
3452 // not reference-related to T2, and can be implicitly
3453 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3454 // is reference-compatible with "cv3 T3" 92) (this
3455 // conversion is selected by enumerating the applicable
3456 // conversion functions (13.3.1.6) and choosing the best
3457 // one through overload resolution (13.3)),
3458 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003459 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00003460 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00003461 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3462 Init, T2, /*AllowRvalues=*/false,
3463 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00003464 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003465 }
3466 }
3467
Sebastian Redl4680bf22010-06-30 18:13:39 +00003468 // -- Otherwise, the reference shall be an lvalue reference to a
3469 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003470 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003471 //
Douglas Gregor66821b52010-04-18 09:22:00 +00003472 // We actually handle one oddity of C++ [over.ics.ref] at this
3473 // point, which is that, due to p2 (which short-circuits reference
3474 // binding by only attempting a simple conversion for non-direct
3475 // bindings) and p3's strange wording, we allow a const volatile
3476 // reference to bind to an rvalue. Hence the check for the presence
3477 // of "const" rather than checking for "const" being the only
3478 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00003479 // This is also the point where rvalue references and lvalue inits no longer
3480 // go together.
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003481 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00003482 return ICS;
3483
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003484 // -- If the initializer expression
3485 //
3486 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00003487 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003488 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3489 (InitCategory.isXValue() ||
3490 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3491 (InitCategory.isLValue() && T2->isFunctionType()))) {
3492 ICS.setStandard();
3493 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003494 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003495 : ObjCConversion? ICK_Compatible_Conversion
3496 : ICK_Identity;
3497 ICS.Standard.Third = ICK_Identity;
3498 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3499 ICS.Standard.setToType(0, T2);
3500 ICS.Standard.setToType(1, T1);
3501 ICS.Standard.setToType(2, T1);
3502 ICS.Standard.ReferenceBinding = true;
3503 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3504 // binding unless we're binding to a class prvalue.
3505 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3506 // allow the use of rvalue references in C++98/03 for the benefit of
3507 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003508 ICS.Standard.DirectBinding =
3509 S.getLangOptions().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003510 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00003511 ICS.Standard.IsLvalueReference = !isRValRef;
3512 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003513 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003514 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003515 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003516 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003517 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003518 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003519
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003520 // -- has a class type (i.e., T2 is a class type), where T1 is not
3521 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003522 // an xvalue, class prvalue, or function lvalue of type
3523 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003524 // "cv3 T3",
3525 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003526 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003527 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003528 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003529 // class subobject).
3530 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003531 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003532 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3533 Init, T2, /*AllowRvalues=*/true,
3534 AllowExplicit)) {
3535 // In the second case, if the reference is an rvalue reference
3536 // and the second standard conversion sequence of the
3537 // user-defined conversion sequence includes an lvalue-to-rvalue
3538 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003539 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003540 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3541 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3542
Douglas Gregor68ed68b2011-01-21 16:36:05 +00003543 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00003544 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003545
Douglas Gregorabe183d2010-04-13 16:31:36 +00003546 // -- Otherwise, a temporary of type "cv1 T1" is created and
3547 // initialized from the initializer expression using the
3548 // rules for a non-reference copy initialization (8.5). The
3549 // reference is then bound to the temporary. If T1 is
3550 // reference-related to T2, cv1 must be the same
3551 // cv-qualification as, or greater cv-qualification than,
3552 // cv2; otherwise, the program is ill-formed.
3553 if (RefRelationship == Sema::Ref_Related) {
3554 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3555 // we would be reference-compatible or reference-compatible with
3556 // added qualification. But that wasn't the case, so the reference
3557 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00003558 //
3559 // Note that we only want to check address spaces and cvr-qualifiers here.
3560 // ObjC GC and lifetime qualifiers aren't important.
3561 Qualifiers T1Quals = T1.getQualifiers();
3562 Qualifiers T2Quals = T2.getQualifiers();
3563 T1Quals.removeObjCGCAttr();
3564 T1Quals.removeObjCLifetime();
3565 T2Quals.removeObjCGCAttr();
3566 T2Quals.removeObjCLifetime();
3567 if (!T1Quals.compatiblyIncludes(T2Quals))
3568 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003569 }
3570
3571 // If at least one of the types is a class type, the types are not
3572 // related, and we aren't allowed any user conversions, the
3573 // reference binding fails. This case is important for breaking
3574 // recursion, since TryImplicitConversion below will attempt to
3575 // create a temporary through the use of a copy constructor.
3576 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3577 (T1->isRecordType() || T2->isRecordType()))
3578 return ICS;
3579
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003580 // If T1 is reference-related to T2 and the reference is an rvalue
3581 // reference, the initializer expression shall not be an lvalue.
3582 if (RefRelationship >= Sema::Ref_Related &&
3583 isRValRef && Init->Classify(S.Context).isLValue())
3584 return ICS;
3585
Douglas Gregorabe183d2010-04-13 16:31:36 +00003586 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00003587 // When a parameter of reference type is not bound directly to
3588 // an argument expression, the conversion sequence is the one
3589 // required to convert the argument expression to the
3590 // underlying type of the reference according to
3591 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3592 // to copy-initializing a temporary of the underlying type with
3593 // the argument expression. Any difference in top-level
3594 // cv-qualification is subsumed by the initialization itself
3595 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00003596 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3597 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003598 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003599 /*CStyle=*/false,
3600 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003601
3602 // Of course, that's still a reference binding.
3603 if (ICS.isStandard()) {
3604 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003605 ICS.Standard.IsLvalueReference = !isRValRef;
3606 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3607 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003608 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003609 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003610 } else if (ICS.isUserDefined()) {
3611 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003612 ICS.Standard.IsLvalueReference = !isRValRef;
3613 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3614 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003615 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003616 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003617 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003618
Douglas Gregorabe183d2010-04-13 16:31:36 +00003619 return ICS;
3620}
3621
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003622/// TryCopyInitialization - Try to copy-initialize a value of type
3623/// ToType from the expression From. Return the implicit conversion
3624/// sequence required to pass this argument, which may be a bad
3625/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00003626/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00003627/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00003628static ImplicitConversionSequence
3629TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003630 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00003631 bool InOverloadResolution,
3632 bool AllowObjCWritebackConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003633 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00003634 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003635 /*FIXME:*/From->getLocStart(),
3636 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003637 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003638
John McCall120d63c2010-08-24 20:38:10 +00003639 return TryImplicitConversion(S, From, ToType,
3640 SuppressUserConversions,
3641 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003642 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00003643 /*CStyle=*/false,
3644 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003645}
3646
Anna Zaksf3546ee2011-07-28 19:46:48 +00003647static bool TryCopyInitialization(const CanQualType FromQTy,
3648 const CanQualType ToQTy,
3649 Sema &S,
3650 SourceLocation Loc,
3651 ExprValueKind FromVK) {
3652 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
3653 ImplicitConversionSequence ICS =
3654 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
3655
3656 return !ICS.isBad();
3657}
3658
Douglas Gregor96176b32008-11-18 23:14:02 +00003659/// TryObjectArgumentInitialization - Try to initialize the object
3660/// parameter of the given member function (@c Method) from the
3661/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00003662static ImplicitConversionSequence
3663TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003664 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00003665 CXXMethodDecl *Method,
3666 CXXRecordDecl *ActingContext) {
3667 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003668 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3669 // const volatile object.
3670 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3671 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00003672 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00003673
3674 // Set up the conversion sequence as a "bad" conversion, to allow us
3675 // to exit early.
3676 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00003677
3678 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00003679 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003680 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003681 FromType = PT->getPointeeType();
3682
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003683 // When we had a pointer, it's implicitly dereferenced, so we
3684 // better have an lvalue.
3685 assert(FromClassification.isLValue());
3686 }
3687
Anders Carlssona552f7c2009-05-01 18:34:30 +00003688 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00003689
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003690 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003691 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003692 // parameter is
3693 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003694 // - "lvalue reference to cv X" for functions declared without a
3695 // ref-qualifier or with the & ref-qualifier
3696 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003697 // ref-qualifier
3698 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003699 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003700 // cv-qualification on the member function declaration.
3701 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003702 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003703 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00003704 // (C++ [over.match.funcs]p5). We perform a simplified version of
3705 // reference binding here, that allows class rvalues to bind to
3706 // non-constant references.
3707
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003708 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00003709 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003710 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00003711 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00003712 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00003713 ICS.setBad(BadConversionSequence::bad_qualifiers,
3714 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003715 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003716 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003717
3718 // Check that we have either the same type or a derived type. It
3719 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00003720 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00003721 ImplicitConversionKind SecondKind;
3722 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3723 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00003724 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00003725 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00003726 else {
John McCallb1bdc622010-02-25 01:37:24 +00003727 ICS.setBad(BadConversionSequence::unrelated_class,
3728 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003729 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003730 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003731
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003732 // Check the ref-qualifier.
3733 switch (Method->getRefQualifier()) {
3734 case RQ_None:
3735 // Do nothing; we don't care about lvalueness or rvalueness.
3736 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003737
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003738 case RQ_LValue:
3739 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3740 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003741 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003742 ImplicitParamType);
3743 return ICS;
3744 }
3745 break;
3746
3747 case RQ_RValue:
3748 if (!FromClassification.isRValue()) {
3749 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003750 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003751 ImplicitParamType);
3752 return ICS;
3753 }
3754 break;
3755 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003756
Douglas Gregor96176b32008-11-18 23:14:02 +00003757 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00003758 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003759 ICS.Standard.setAsIdentityConversion();
3760 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003761 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003762 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003763 ICS.Standard.ReferenceBinding = true;
3764 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003765 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00003766 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003767 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3768 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3769 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00003770 return ICS;
3771}
3772
3773/// PerformObjectArgumentInitialization - Perform initialization of
3774/// the implicit object parameter for the given Method with the given
3775/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00003776ExprResult
3777Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003778 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003779 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003780 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003781 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003782 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003783 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003784
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003785 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00003786 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003787 FromRecordType = PT->getPointeeType();
3788 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003789 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00003790 } else {
3791 FromRecordType = From->getType();
3792 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003793 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00003794 }
3795
John McCall701c89e2009-12-03 04:06:58 +00003796 // Note that we always use the true parent context when performing
3797 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003798 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003799 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3800 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003801 if (ICS.isBad()) {
3802 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3803 Qualifiers FromQs = FromRecordType.getQualifiers();
3804 Qualifiers ToQs = DestType.getQualifiers();
3805 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3806 if (CVR) {
3807 Diag(From->getSourceRange().getBegin(),
3808 diag::err_member_function_call_bad_cvr)
3809 << Method->getDeclName() << FromRecordType << (CVR - 1)
3810 << From->getSourceRange();
3811 Diag(Method->getLocation(), diag::note_previous_decl)
3812 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00003813 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003814 }
3815 }
3816
Douglas Gregor96176b32008-11-18 23:14:02 +00003817 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003818 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003819 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003820 }
Mike Stump1eb44332009-09-09 15:08:12 +00003821
John Wiegley429bb272011-04-08 18:41:53 +00003822 if (ICS.Standard.Second == ICK_Derived_To_Base) {
3823 ExprResult FromRes =
3824 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3825 if (FromRes.isInvalid())
3826 return ExprError();
3827 From = FromRes.take();
3828 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003829
Douglas Gregor5fccd362010-03-03 23:55:11 +00003830 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00003831 From = ImpCastExprToType(From, DestType, CK_NoOp,
3832 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3833 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00003834}
3835
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003836/// TryContextuallyConvertToBool - Attempt to contextually convert the
3837/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00003838static ImplicitConversionSequence
3839TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003840 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00003841 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003842 // FIXME: Are these flags correct?
3843 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003844 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003845 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003846 /*CStyle=*/false,
3847 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003848}
3849
3850/// PerformContextuallyConvertToBool - Perform a contextual conversion
3851/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00003852ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall120d63c2010-08-24 20:38:10 +00003853 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00003854 if (!ICS.isBad())
3855 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003856
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003857 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall864c0412011-04-26 20:42:42 +00003858 return Diag(From->getSourceRange().getBegin(),
3859 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003860 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003861 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003862}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003863
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003864/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3865/// expression From to 'id'.
John McCall120d63c2010-08-24 20:38:10 +00003866static ImplicitConversionSequence
3867TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3868 QualType Ty = S.Context.getObjCIdType();
3869 return TryImplicitConversion(S, From, Ty,
3870 // FIXME: Are these flags correct?
3871 /*SuppressUserConversions=*/false,
3872 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003873 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003874 /*CStyle=*/false,
3875 /*AllowObjCWritebackConversion=*/false);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003876}
John McCall120d63c2010-08-24 20:38:10 +00003877
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003878/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3879/// of the expression From to 'id'.
John Wiegley429bb272011-04-08 18:41:53 +00003880ExprResult Sema::PerformContextuallyConvertToObjCId(Expr *From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003881 QualType Ty = Context.getObjCIdType();
John McCall120d63c2010-08-24 20:38:10 +00003882 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003883 if (!ICS.isBad())
3884 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00003885 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003886}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003887
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003888/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00003889/// enumeration type.
3890///
3891/// This routine will attempt to convert an expression of class type to an
3892/// integral or enumeration type, if that class type only has a single
3893/// conversion to an integral or enumeration type.
3894///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003895/// \param Loc The source location of the construct that requires the
3896/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003897///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003898/// \param FromE The expression we're converting from.
3899///
3900/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3901/// have integral or enumeration type.
3902///
3903/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3904/// incomplete class type.
3905///
3906/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3907/// explicit conversion function (because no implicit conversion functions
3908/// were available). This is a recovery mode.
3909///
3910/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3911/// showing which conversion was picked.
3912///
3913/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3914/// conversion function that could convert to integral or enumeration type.
3915///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003916/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003917/// usable conversion function.
3918///
3919/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3920/// function, which may be an extension in this case.
3921///
3922/// \returns The expression, converted to an integral or enumeration type if
3923/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003924ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003925Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003926 const PartialDiagnostic &NotIntDiag,
3927 const PartialDiagnostic &IncompleteDiag,
3928 const PartialDiagnostic &ExplicitConvDiag,
3929 const PartialDiagnostic &ExplicitConvNote,
3930 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003931 const PartialDiagnostic &AmbigNote,
3932 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00003933 // We can't perform any more checking for type-dependent expressions.
3934 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00003935 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003936
Douglas Gregorc30614b2010-06-29 23:17:37 +00003937 // If the expression already has integral or enumeration type, we're golden.
3938 QualType T = From->getType();
3939 if (T->isIntegralOrEnumerationType())
John McCall9ae2f072010-08-23 23:25:46 +00003940 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003941
3942 // FIXME: Check for missing '()' if T is a function type?
3943
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003944 // 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 +00003945 // expression of integral or enumeration type.
3946 const RecordType *RecordTy = T->getAs<RecordType>();
3947 if (!RecordTy || !getLangOptions().CPlusPlus) {
3948 Diag(Loc, NotIntDiag)
3949 << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00003950 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003951 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003952
Douglas Gregorc30614b2010-06-29 23:17:37 +00003953 // We must have a complete class type.
3954 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00003955 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003956
Douglas Gregorc30614b2010-06-29 23:17:37 +00003957 // Look for a conversion to an integral or enumeration type.
3958 UnresolvedSet<4> ViableConversions;
3959 UnresolvedSet<4> ExplicitConversions;
3960 const UnresolvedSetImpl *Conversions
3961 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003962
Douglas Gregorc30614b2010-06-29 23:17:37 +00003963 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003964 E = Conversions->end();
3965 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00003966 ++I) {
3967 if (CXXConversionDecl *Conversion
3968 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3969 if (Conversion->getConversionType().getNonReferenceType()
3970 ->isIntegralOrEnumerationType()) {
3971 if (Conversion->isExplicit())
3972 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3973 else
3974 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3975 }
3976 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003977
Douglas Gregorc30614b2010-06-29 23:17:37 +00003978 switch (ViableConversions.size()) {
3979 case 0:
3980 if (ExplicitConversions.size() == 1) {
3981 DeclAccessPair Found = ExplicitConversions[0];
3982 CXXConversionDecl *Conversion
3983 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003984
Douglas Gregorc30614b2010-06-29 23:17:37 +00003985 // The user probably meant to invoke the given explicit
3986 // conversion; use it.
3987 QualType ConvTy
3988 = Conversion->getConversionType().getNonReferenceType();
3989 std::string TypeStr;
3990 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003991
Douglas Gregorc30614b2010-06-29 23:17:37 +00003992 Diag(Loc, ExplicitConvDiag)
3993 << T << ConvTy
3994 << FixItHint::CreateInsertion(From->getLocStart(),
3995 "static_cast<" + TypeStr + ">(")
3996 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3997 ")");
3998 Diag(Conversion->getLocation(), ExplicitConvNote)
3999 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004000
4001 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00004002 // explicit conversion function.
4003 if (isSFINAEContext())
4004 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004005
Douglas Gregorc30614b2010-06-29 23:17:37 +00004006 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004007 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
4008 if (Result.isInvalid())
4009 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004010
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004011 From = Result.get();
Douglas Gregorc30614b2010-06-29 23:17:37 +00004012 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004013
Douglas Gregorc30614b2010-06-29 23:17:37 +00004014 // We'll complain below about a non-integral condition type.
4015 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004016
Douglas Gregorc30614b2010-06-29 23:17:37 +00004017 case 1: {
4018 // Apply this conversion.
4019 DeclAccessPair Found = ViableConversions[0];
4020 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004021
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004022 CXXConversionDecl *Conversion
4023 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4024 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004025 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004026 if (ConvDiag.getDiagID()) {
4027 if (isSFINAEContext())
4028 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004029
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004030 Diag(Loc, ConvDiag)
4031 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4032 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004033
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004034 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorc30614b2010-06-29 23:17:37 +00004035 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004036 if (Result.isInvalid())
4037 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004038
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004039 From = Result.get();
Douglas Gregorc30614b2010-06-29 23:17:37 +00004040 break;
4041 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004042
Douglas Gregorc30614b2010-06-29 23:17:37 +00004043 default:
4044 Diag(Loc, AmbigDiag)
4045 << T << From->getSourceRange();
4046 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4047 CXXConversionDecl *Conv
4048 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4049 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4050 Diag(Conv->getLocation(), AmbigNote)
4051 << ConvTy->isEnumeralType() << ConvTy;
4052 }
John McCall9ae2f072010-08-23 23:25:46 +00004053 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004054 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004055
Douglas Gregoracb0bd82010-06-29 23:25:20 +00004056 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00004057 Diag(Loc, NotIntDiag)
4058 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00004059
John McCall9ae2f072010-08-23 23:25:46 +00004060 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004061}
4062
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004063/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00004064/// candidate functions, using the given function call arguments. If
4065/// @p SuppressUserConversions, then don't allow user-defined
4066/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004067///
4068/// \para PartialOverloading true if we are performing "partial" overloading
4069/// based on an incomplete set of function arguments. This feature is used by
4070/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00004071void
4072Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00004073 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004074 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00004075 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00004076 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004077 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00004078 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00004079 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004080 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00004081 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004082 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00004083
Douglas Gregor88a35142008-12-22 05:46:06 +00004084 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004085 if (!isa<CXXConstructorDecl>(Method)) {
4086 // If we get here, it's because we're calling a member function
4087 // that is named without a member access expression (e.g.,
4088 // "this->f") that was either written explicitly or created
4089 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00004090 // function, e.g., X::f(). We use an empty type for the implied
4091 // object argument (C++ [over.call.func]p3), and the acting context
4092 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00004093 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004094 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004095 Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004096 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004097 return;
4098 }
4099 // We treat a constructor like a non-member function, since its object
4100 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00004101 }
4102
Douglas Gregorfd476482009-11-13 23:59:09 +00004103 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00004104 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00004105
Douglas Gregor7edfb692009-11-23 12:27:39 +00004106 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004107 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004108
Douglas Gregor66724ea2009-11-14 01:20:54 +00004109 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4110 // C++ [class.copy]p3:
4111 // A member function template is never instantiated to perform the copy
4112 // of a class object to an object of its class type.
4113 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004114 if (NumArgs == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00004115 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00004116 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4117 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00004118 return;
4119 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004120
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004121 // Add this candidate
4122 CandidateSet.push_back(OverloadCandidate());
4123 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004124 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004125 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00004126 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004127 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004128 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004129 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004130
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004131 unsigned NumArgsInProto = Proto->getNumArgs();
4132
4133 // (C++ 13.3.2p2): A candidate function having fewer than m
4134 // parameters is viable only if it has an ellipsis in its parameter
4135 // list (8.3.5).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004136 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00004137 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004138 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004139 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004140 return;
4141 }
4142
4143 // (C++ 13.3.2p2): A candidate function having more than m parameters
4144 // is viable only if the (m+1)st parameter has a default argument
4145 // (8.3.6). For the purposes of overload resolution, the
4146 // parameter list is truncated on the right, so that there are
4147 // exactly m parameters.
4148 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004149 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004150 // Not enough arguments.
4151 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004152 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004153 return;
4154 }
4155
4156 // Determine the implicit conversion sequences for each of the
4157 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004158 Candidate.Conversions.resize(NumArgs);
4159 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4160 if (ArgIdx < NumArgsInProto) {
4161 // (C++ 13.3.2p3): for F to be a viable function, there shall
4162 // exist for each argument an implicit conversion sequence
4163 // (13.3.3.1) that converts that argument to the corresponding
4164 // parameter of F.
4165 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004166 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004167 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004168 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004169 /*InOverloadResolution=*/true,
4170 /*AllowObjCWritebackConversion=*/
4171 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00004172 if (Candidate.Conversions[ArgIdx].isBad()) {
4173 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004174 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00004175 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00004176 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004177 } else {
4178 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4179 // argument for which there is no corresponding parameter is
4180 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004181 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004182 }
4183 }
4184}
4185
Douglas Gregor063daf62009-03-13 18:40:31 +00004186/// \brief Add all of the function declarations in the given function set to
4187/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00004188void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00004189 Expr **Args, unsigned NumArgs,
4190 OverloadCandidateSet& CandidateSet,
4191 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00004192 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00004193 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4194 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004195 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00004196 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00004197 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004198 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004199 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00004200 CandidateSet, SuppressUserConversions);
4201 else
John McCall9aa472c2010-03-19 07:35:19 +00004202 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00004203 SuppressUserConversions);
4204 } else {
John McCall9aa472c2010-03-19 07:35:19 +00004205 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00004206 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4207 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00004208 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00004209 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00004210 /*FIXME: explicit args */ 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004211 Args[0]->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004212 Args[0]->Classify(Context),
4213 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00004214 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00004215 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00004216 else
John McCall9aa472c2010-03-19 07:35:19 +00004217 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00004218 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00004219 Args, NumArgs, CandidateSet,
4220 SuppressUserConversions);
4221 }
Douglas Gregor364e0212009-06-27 21:05:07 +00004222 }
Douglas Gregor063daf62009-03-13 18:40:31 +00004223}
4224
John McCall314be4e2009-11-17 07:50:12 +00004225/// AddMethodCandidate - Adds a named decl (which is some kind of
4226/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00004227void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004228 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004229 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00004230 Expr **Args, unsigned NumArgs,
4231 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004232 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00004233 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00004234 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00004235
4236 if (isa<UsingShadowDecl>(Decl))
4237 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004238
John McCall314be4e2009-11-17 07:50:12 +00004239 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4240 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4241 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00004242 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4243 /*ExplicitArgs*/ 0,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004244 ObjectType, ObjectClassification, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00004245 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004246 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00004247 } else {
John McCall9aa472c2010-03-19 07:35:19 +00004248 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004249 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004250 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00004251 }
4252}
4253
Douglas Gregor96176b32008-11-18 23:14:02 +00004254/// AddMethodCandidate - Adds the given C++ member function to the set
4255/// of candidate functions, using the given function call arguments
4256/// and the object argument (@c Object). For example, in a call
4257/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4258/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4259/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00004260/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00004261void
John McCall9aa472c2010-03-19 07:35:19 +00004262Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00004263 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004264 Expr::Classification ObjectClassification,
John McCall86820f52010-01-26 01:37:31 +00004265 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00004266 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004267 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00004268 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00004269 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00004270 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004271 assert(!isa<CXXConstructorDecl>(Method) &&
4272 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00004273
Douglas Gregor3f396022009-09-28 04:47:19 +00004274 if (!CandidateSet.isNewCandidate(Method))
4275 return;
4276
Douglas Gregor7edfb692009-11-23 12:27:39 +00004277 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004278 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004279
Douglas Gregor96176b32008-11-18 23:14:02 +00004280 // Add this candidate
4281 CandidateSet.push_back(OverloadCandidate());
4282 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004283 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00004284 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004285 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004286 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004287 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor96176b32008-11-18 23:14:02 +00004288
4289 unsigned NumArgsInProto = Proto->getNumArgs();
4290
4291 // (C++ 13.3.2p2): A candidate function having fewer than m
4292 // parameters is viable only if it has an ellipsis in its parameter
4293 // list (8.3.5).
4294 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4295 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004296 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00004297 return;
4298 }
4299
4300 // (C++ 13.3.2p2): A candidate function having more than m parameters
4301 // is viable only if the (m+1)st parameter has a default argument
4302 // (8.3.6). For the purposes of overload resolution, the
4303 // parameter list is truncated on the right, so that there are
4304 // exactly m parameters.
4305 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4306 if (NumArgs < MinRequiredArgs) {
4307 // Not enough arguments.
4308 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004309 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00004310 return;
4311 }
4312
4313 Candidate.Viable = true;
4314 Candidate.Conversions.resize(NumArgs + 1);
4315
John McCall701c89e2009-12-03 04:06:58 +00004316 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00004317 // The implicit object argument is ignored.
4318 Candidate.IgnoreObjectArgument = true;
4319 else {
4320 // Determine the implicit conversion sequence for the object
4321 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00004322 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004323 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4324 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00004325 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004326 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004327 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00004328 return;
4329 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004330 }
4331
4332 // Determine the implicit conversion sequences for each of the
4333 // arguments.
4334 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4335 if (ArgIdx < NumArgsInProto) {
4336 // (C++ 13.3.2p3): for F to be a viable function, there shall
4337 // exist for each argument an implicit conversion sequence
4338 // (13.3.3.1) that converts that argument to the corresponding
4339 // parameter of F.
4340 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004341 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004342 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004343 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004344 /*InOverloadResolution=*/true,
4345 /*AllowObjCWritebackConversion=*/
4346 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00004347 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004348 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004349 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004350 break;
4351 }
4352 } else {
4353 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4354 // argument for which there is no corresponding parameter is
4355 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004356 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00004357 }
4358 }
4359}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004360
Douglas Gregor6b906862009-08-21 00:16:32 +00004361/// \brief Add a C++ member function template as a candidate to the candidate
4362/// set, using template argument deduction to produce an appropriate member
4363/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004364void
Douglas Gregor6b906862009-08-21 00:16:32 +00004365Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00004366 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004367 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00004368 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00004369 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004370 Expr::Classification ObjectClassification,
John McCall701c89e2009-12-03 04:06:58 +00004371 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00004372 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004373 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004374 if (!CandidateSet.isNewCandidate(MethodTmpl))
4375 return;
4376
Douglas Gregor6b906862009-08-21 00:16:32 +00004377 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00004378 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00004379 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00004380 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00004381 // candidate functions in the usual way.113) A given name can refer to one
4382 // or more function templates and also to a set of overloaded non-template
4383 // functions. In such a case, the candidate functions generated from each
4384 // function template are combined with the set of non-template candidate
4385 // functions.
John McCall5769d612010-02-08 23:07:23 +00004386 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00004387 FunctionDecl *Specialization = 0;
4388 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004389 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00004390 Args, NumArgs, 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 = MethodTmpl->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 = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004400 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004401 Info);
4402 return;
4403 }
Mike Stump1eb44332009-09-09 15:08:12 +00004404
Douglas Gregor6b906862009-08-21 00:16:32 +00004405 // Add the function template specialization produced by template argument
4406 // deduction as a candidate.
4407 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00004408 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00004409 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00004410 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004411 ActingContext, ObjectType, ObjectClassification,
4412 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00004413}
4414
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004415/// \brief Add a C++ function template specialization as a candidate
4416/// in the candidate set, using template argument deduction to produce
4417/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004418void
Douglas Gregore53060f2009-06-25 22:08:12 +00004419Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00004420 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00004421 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00004422 Expr **Args, unsigned NumArgs,
4423 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004424 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004425 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4426 return;
4427
Douglas Gregore53060f2009-06-25 22:08:12 +00004428 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00004429 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00004430 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00004431 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00004432 // candidate functions in the usual way.113) A given name can refer to one
4433 // or more function templates and also to a set of overloaded non-template
4434 // functions. In such a case, the candidate functions generated from each
4435 // function template are combined with the set of non-template candidate
4436 // functions.
John McCall5769d612010-02-08 23:07:23 +00004437 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00004438 FunctionDecl *Specialization = 0;
4439 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004440 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004441 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00004442 CandidateSet.push_back(OverloadCandidate());
4443 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004444 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00004445 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4446 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004447 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00004448 Candidate.IsSurrogate = false;
4449 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004450 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004451 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004452 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00004453 return;
4454 }
Mike Stump1eb44332009-09-09 15:08:12 +00004455
Douglas Gregore53060f2009-06-25 22:08:12 +00004456 // Add the function template specialization produced by template argument
4457 // deduction as a candidate.
4458 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00004459 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004460 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00004461}
Mike Stump1eb44332009-09-09 15:08:12 +00004462
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004463/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00004464/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004465/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00004466/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004467/// (which may or may not be the same type as the type that the
4468/// conversion function produces).
4469void
4470Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00004471 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004472 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004473 Expr *From, QualType ToType,
4474 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004475 assert(!Conversion->getDescribedFunctionTemplate() &&
4476 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004477 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00004478 if (!CandidateSet.isNewCandidate(Conversion))
4479 return;
4480
Douglas Gregor7edfb692009-11-23 12:27:39 +00004481 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004482 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004483
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004484 // Add this candidate
4485 CandidateSet.push_back(OverloadCandidate());
4486 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004487 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004488 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004489 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004490 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004491 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004492 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004493 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004494 Candidate.Viable = true;
4495 Candidate.Conversions.resize(1);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004496 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004497
Douglas Gregorbca39322010-08-19 15:37:02 +00004498 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004499 // For conversion functions, the function is considered to be a member of
4500 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00004501 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004502 //
4503 // Determine the implicit conversion sequence for the implicit
4504 // object parameter.
4505 QualType ImplicitParamType = From->getType();
4506 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4507 ImplicitParamType = FromPtrType->getPointeeType();
4508 CXXRecordDecl *ConversionContext
4509 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004510
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004511 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004512 = TryObjectArgumentInitialization(*this, From->getType(),
4513 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004514 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004515
John McCall1d318332010-01-12 00:44:57 +00004516 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004517 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004518 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004519 return;
4520 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004521
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004522 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00004523 // derived to base as such conversions are given Conversion Rank. They only
4524 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4525 QualType FromCanon
4526 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4527 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4528 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4529 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00004530 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00004531 return;
4532 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004533
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004534 // To determine what the conversion from the result of calling the
4535 // conversion function to the type we're eventually trying to
4536 // convert to (ToType), we need to synthesize a call to the
4537 // conversion function and attempt copy initialization from it. This
4538 // makes sure that we get the right semantics with respect to
4539 // lvalues/rvalues and the type. Fortunately, we can allocate this
4540 // call on the stack and we don't need its arguments to be
4541 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00004542 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004543 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00004544 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4545 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00004546 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00004547 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00004548
Richard Smith87c1f1f2011-07-13 22:53:21 +00004549 QualType ConversionType = Conversion->getConversionType();
4550 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00004551 Candidate.Viable = false;
4552 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4553 return;
4554 }
4555
Richard Smith87c1f1f2011-07-13 22:53:21 +00004556 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00004557
Mike Stump1eb44332009-09-09 15:08:12 +00004558 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00004559 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4560 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00004561 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00004562 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00004563 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00004564 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00004565 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004566 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00004567 /*InOverloadResolution=*/false,
4568 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004569
John McCall1d318332010-01-12 00:44:57 +00004570 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004571 case ImplicitConversionSequence::StandardConversion:
4572 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004573
Douglas Gregorc520c842010-04-12 23:42:09 +00004574 // C++ [over.ics.user]p3:
4575 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004576 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00004577 // shall have exact match rank.
4578 if (Conversion->getPrimaryTemplate() &&
4579 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4580 Candidate.Viable = false;
4581 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4582 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004583
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004584 // C++0x [dcl.init.ref]p5:
4585 // In the second case, if the reference is an rvalue reference and
4586 // the second standard conversion sequence of the user-defined
4587 // conversion sequence includes an lvalue-to-rvalue conversion, the
4588 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004589 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004590 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4591 Candidate.Viable = false;
4592 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4593 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004594 break;
4595
4596 case ImplicitConversionSequence::BadConversion:
4597 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00004598 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004599 break;
4600
4601 default:
Mike Stump1eb44332009-09-09 15:08:12 +00004602 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004603 "Can only end up with a standard conversion sequence or failure");
4604 }
4605}
4606
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004607/// \brief Adds a conversion function template specialization
4608/// candidate to the overload set, using template argument deduction
4609/// to deduce the template arguments of the conversion function
4610/// template from the type that we are converting to (C++
4611/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00004612void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004613Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00004614 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004615 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004616 Expr *From, QualType ToType,
4617 OverloadCandidateSet &CandidateSet) {
4618 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4619 "Only conversion function templates permitted here");
4620
Douglas Gregor3f396022009-09-28 04:47:19 +00004621 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4622 return;
4623
John McCall5769d612010-02-08 23:07:23 +00004624 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004625 CXXConversionDecl *Specialization = 0;
4626 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00004627 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004628 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00004629 CandidateSet.push_back(OverloadCandidate());
4630 OverloadCandidate &Candidate = CandidateSet.back();
4631 Candidate.FoundDecl = FoundDecl;
4632 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4633 Candidate.Viable = false;
4634 Candidate.FailureKind = ovl_fail_bad_deduction;
4635 Candidate.IsSurrogate = false;
4636 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004637 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004638 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004639 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004640 return;
4641 }
Mike Stump1eb44332009-09-09 15:08:12 +00004642
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004643 // Add the conversion function template specialization produced by
4644 // template argument deduction as a candidate.
4645 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00004646 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00004647 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004648}
4649
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004650/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4651/// converts the given @c Object to a function pointer via the
4652/// conversion function @c Conversion, and then attempts to call it
4653/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4654/// the type of function that we'll eventually be calling.
4655void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00004656 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004657 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00004658 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004659 Expr *Object,
John McCall701c89e2009-12-03 04:06:58 +00004660 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004661 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004662 if (!CandidateSet.isNewCandidate(Conversion))
4663 return;
4664
Douglas Gregor7edfb692009-11-23 12:27:39 +00004665 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004666 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004667
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004668 CandidateSet.push_back(OverloadCandidate());
4669 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004670 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004671 Candidate.Function = 0;
4672 Candidate.Surrogate = Conversion;
4673 Candidate.Viable = true;
4674 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004675 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004676 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004677 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004678
4679 // Determine the implicit conversion sequence for the implicit
4680 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004681 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004682 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004683 Object->Classify(Context),
4684 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00004685 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004686 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004687 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00004688 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004689 return;
4690 }
4691
4692 // The first conversion is actually a user-defined conversion whose
4693 // first conversion is ObjectInit's standard conversion (which is
4694 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00004695 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004696 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004697 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004698 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004699 Candidate.Conversions[0].UserDefined.FoundConversionFunction
Douglas Gregor83eecbe2011-01-20 01:32:05 +00004700 = FoundDecl.getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004701 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004702 = Candidate.Conversions[0].UserDefined.Before;
4703 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4704
Mike Stump1eb44332009-09-09 15:08:12 +00004705 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004706 unsigned NumArgsInProto = Proto->getNumArgs();
4707
4708 // (C++ 13.3.2p2): A candidate function having fewer than m
4709 // parameters is viable only if it has an ellipsis in its parameter
4710 // list (8.3.5).
4711 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4712 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004713 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004714 return;
4715 }
4716
4717 // Function types don't have any default arguments, so just check if
4718 // we have enough arguments.
4719 if (NumArgs < NumArgsInProto) {
4720 // Not enough arguments.
4721 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004722 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004723 return;
4724 }
4725
4726 // Determine the implicit conversion sequences for each of the
4727 // arguments.
4728 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4729 if (ArgIdx < NumArgsInProto) {
4730 // (C++ 13.3.2p3): for F to be a viable function, there shall
4731 // exist for each argument an implicit conversion sequence
4732 // (13.3.3.1) that converts that argument to the corresponding
4733 // parameter of F.
4734 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004735 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004736 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004737 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004738 /*InOverloadResolution=*/false,
4739 /*AllowObjCWritebackConversion=*/
4740 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00004741 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004742 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004743 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004744 break;
4745 }
4746 } else {
4747 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4748 // argument for which there is no corresponding parameter is
4749 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004750 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004751 }
4752 }
4753}
4754
Douglas Gregor063daf62009-03-13 18:40:31 +00004755/// \brief Add overload candidates for overloaded operators that are
4756/// member functions.
4757///
4758/// Add the overloaded operator candidates that are member functions
4759/// for the operator Op that was used in an operator expression such
4760/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4761/// CandidateSet will store the added overload candidates. (C++
4762/// [over.match.oper]).
4763void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4764 SourceLocation OpLoc,
4765 Expr **Args, unsigned NumArgs,
4766 OverloadCandidateSet& CandidateSet,
4767 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004768 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4769
4770 // C++ [over.match.oper]p3:
4771 // For a unary operator @ with an operand of a type whose
4772 // cv-unqualified version is T1, and for a binary operator @ with
4773 // a left operand of a type whose cv-unqualified version is T1 and
4774 // a right operand of a type whose cv-unqualified version is T2,
4775 // three sets of candidate functions, designated member
4776 // candidates, non-member candidates and built-in candidates, are
4777 // constructed as follows:
4778 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00004779
4780 // -- If T1 is a class type, the set of member candidates is the
4781 // result of the qualified lookup of T1::operator@
4782 // (13.3.1.1.1); otherwise, the set of member candidates is
4783 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00004784 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004785 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004786 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004787 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004788
John McCalla24dc2e2009-11-17 02:14:36 +00004789 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4790 LookupQualifiedName(Operators, T1Rec->getDecl());
4791 Operators.suppressDiagnostics();
4792
Mike Stump1eb44332009-09-09 15:08:12 +00004793 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004794 OperEnd = Operators.end();
4795 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00004796 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00004797 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004798 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004799 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00004800 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00004801 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004802}
4803
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004804/// AddBuiltinCandidate - Add a candidate for a built-in
4805/// operator. ResultTy and ParamTys are the result and parameter types
4806/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004807/// arguments being passed to the candidate. IsAssignmentOperator
4808/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004809/// operator. NumContextualBoolArguments is the number of arguments
4810/// (at the beginning of the argument list) that will be contextually
4811/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00004812void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004813 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004814 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004815 bool IsAssignmentOperator,
4816 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00004817 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004818 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004819
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004820 // Add this candidate
4821 CandidateSet.push_back(OverloadCandidate());
4822 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004823 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004824 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004825 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004826 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004827 Candidate.BuiltinTypes.ResultTy = ResultTy;
4828 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4829 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4830
4831 // Determine the implicit conversion sequences for each of the
4832 // arguments.
4833 Candidate.Viable = true;
4834 Candidate.Conversions.resize(NumArgs);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004835 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004836 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004837 // C++ [over.match.oper]p4:
4838 // For the built-in assignment operators, conversions of the
4839 // left operand are restricted as follows:
4840 // -- no temporaries are introduced to hold the left operand, and
4841 // -- no user-defined conversions are applied to the left
4842 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00004843 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004844 //
4845 // We block these conversions by turning off user-defined
4846 // conversions, since that is the only way that initialization of
4847 // a reference to a non-class type can occur from something that
4848 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004849 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004850 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004851 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00004852 Candidate.Conversions[ArgIdx]
4853 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004854 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004855 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004856 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004857 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00004858 /*InOverloadResolution=*/false,
4859 /*AllowObjCWritebackConversion=*/
4860 getLangOptions().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004861 }
John McCall1d318332010-01-12 00:44:57 +00004862 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004863 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004864 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004865 break;
4866 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004867 }
4868}
4869
4870/// BuiltinCandidateTypeSet - A set of types that will be used for the
4871/// candidate operator functions for built-in operators (C++
4872/// [over.built]). The types are separated into pointer types and
4873/// enumeration types.
4874class BuiltinCandidateTypeSet {
4875 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004876 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004877
4878 /// PointerTypes - The set of pointer types that will be used in the
4879 /// built-in candidates.
4880 TypeSet PointerTypes;
4881
Sebastian Redl78eb8742009-04-19 21:53:20 +00004882 /// MemberPointerTypes - The set of member pointer types that will be
4883 /// used in the built-in candidates.
4884 TypeSet MemberPointerTypes;
4885
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004886 /// EnumerationTypes - The set of enumeration types that will be
4887 /// used in the built-in candidates.
4888 TypeSet EnumerationTypes;
4889
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004890 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00004891 /// candidates.
4892 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00004893
4894 /// \brief A flag indicating non-record types are viable candidates
4895 bool HasNonRecordTypes;
4896
4897 /// \brief A flag indicating whether either arithmetic or enumeration types
4898 /// were present in the candidate set.
4899 bool HasArithmeticOrEnumeralTypes;
4900
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00004901 /// \brief A flag indicating whether the nullptr type was present in the
4902 /// candidate set.
4903 bool HasNullPtrType;
4904
Douglas Gregor5842ba92009-08-24 15:23:48 +00004905 /// Sema - The semantic analysis instance where we are building the
4906 /// candidate type set.
4907 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004908
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004909 /// Context - The AST context in which we will build the type sets.
4910 ASTContext &Context;
4911
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004912 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4913 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00004914 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004915
4916public:
4917 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004918 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004919
Mike Stump1eb44332009-09-09 15:08:12 +00004920 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00004921 : HasNonRecordTypes(false),
4922 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00004923 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00004924 SemaRef(SemaRef),
4925 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004926
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004927 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004928 SourceLocation Loc,
4929 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004930 bool AllowExplicitConversions,
4931 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004932
4933 /// pointer_begin - First pointer type found;
4934 iterator pointer_begin() { return PointerTypes.begin(); }
4935
Sebastian Redl78eb8742009-04-19 21:53:20 +00004936 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004937 iterator pointer_end() { return PointerTypes.end(); }
4938
Sebastian Redl78eb8742009-04-19 21:53:20 +00004939 /// member_pointer_begin - First member pointer type found;
4940 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4941
4942 /// member_pointer_end - Past the last member pointer type found;
4943 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4944
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004945 /// enumeration_begin - First enumeration type found;
4946 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4947
Sebastian Redl78eb8742009-04-19 21:53:20 +00004948 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004949 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004950
Douglas Gregor26bcf672010-05-19 03:21:00 +00004951 iterator vector_begin() { return VectorTypes.begin(); }
4952 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00004953
4954 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4955 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00004956 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004957};
4958
Sebastian Redl78eb8742009-04-19 21:53:20 +00004959/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004960/// the set of pointer types along with any more-qualified variants of
4961/// that type. For example, if @p Ty is "int const *", this routine
4962/// will add "int const *", "int const volatile *", "int const
4963/// restrict *", and "int const volatile restrict *" to the set of
4964/// pointer types. Returns true if the add of @p Ty itself succeeded,
4965/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004966///
4967/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004968bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00004969BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4970 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00004971
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004972 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004973 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004974 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004975
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004976 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00004977 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004978 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004979 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004980 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004981 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004982 buildObjCPtr = true;
4983 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004984 else
4985 assert(false && "type was not a pointer type!");
4986 }
4987 else
4988 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004989
Sebastian Redla9efada2009-11-18 20:39:26 +00004990 // Don't add qualified variants of arrays. For one, they're not allowed
4991 // (the qualifier would sink to the element type), and for another, the
4992 // only overload situation where it matters is subscript or pointer +- int,
4993 // and those shouldn't have qualifier variants anyway.
4994 if (PointeeTy->isArrayType())
4995 return true;
John McCall0953e762009-09-24 19:53:00 +00004996 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00004997 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00004998 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004999 bool hasVolatile = VisibleQuals.hasVolatile();
5000 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005001
John McCall0953e762009-09-24 19:53:00 +00005002 // Iterate through all strict supersets of BaseCVR.
5003 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5004 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005005 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5006 // in the types.
5007 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5008 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00005009 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005010 if (!buildObjCPtr)
5011 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5012 else
5013 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005014 }
5015
5016 return true;
5017}
5018
Sebastian Redl78eb8742009-04-19 21:53:20 +00005019/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5020/// to the set of pointer types along with any more-qualified variants of
5021/// that type. For example, if @p Ty is "int const *", this routine
5022/// will add "int const *", "int const volatile *", "int const
5023/// restrict *", and "int const volatile restrict *" to the set of
5024/// pointer types. Returns true if the add of @p Ty itself succeeded,
5025/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00005026///
5027/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00005028bool
5029BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5030 QualType Ty) {
5031 // Insert this type.
5032 if (!MemberPointerTypes.insert(Ty))
5033 return false;
5034
John McCall0953e762009-09-24 19:53:00 +00005035 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5036 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00005037
John McCall0953e762009-09-24 19:53:00 +00005038 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00005039 // Don't add qualified variants of arrays. For one, they're not allowed
5040 // (the qualifier would sink to the element type), and for another, the
5041 // only overload situation where it matters is subscript or pointer +- int,
5042 // and those shouldn't have qualifier variants anyway.
5043 if (PointeeTy->isArrayType())
5044 return true;
John McCall0953e762009-09-24 19:53:00 +00005045 const Type *ClassTy = PointerTy->getClass();
5046
5047 // Iterate through all strict supersets of the pointee type's CVR
5048 // qualifiers.
5049 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5050 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5051 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005052
John McCall0953e762009-09-24 19:53:00 +00005053 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00005054 MemberPointerTypes.insert(
5055 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00005056 }
5057
5058 return true;
5059}
5060
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005061/// AddTypesConvertedFrom - Add each of the types to which the type @p
5062/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00005063/// primarily interested in pointer types and enumeration types. We also
5064/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005065/// AllowUserConversions is true if we should look at the conversion
5066/// functions of a class type, and AllowExplicitConversions if we
5067/// should also include the explicit conversion functions of a class
5068/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00005069void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005070BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00005071 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005072 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005073 bool AllowExplicitConversions,
5074 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005075 // Only deal with canonical types.
5076 Ty = Context.getCanonicalType(Ty);
5077
5078 // Look through reference types; they aren't part of the type of an
5079 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00005080 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005081 Ty = RefTy->getPointeeType();
5082
John McCall3b657512011-01-19 10:06:00 +00005083 // If we're dealing with an array type, decay to the pointer.
5084 if (Ty->isArrayType())
5085 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5086
5087 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005088 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005089
Chandler Carruth6a577462010-12-13 01:44:01 +00005090 // Flag if we ever add a non-record type.
5091 const RecordType *TyRec = Ty->getAs<RecordType>();
5092 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5093
Chandler Carruth6a577462010-12-13 01:44:01 +00005094 // Flag if we encounter an arithmetic type.
5095 HasArithmeticOrEnumeralTypes =
5096 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5097
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005098 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5099 PointerTypes.insert(Ty);
5100 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005101 // Insert our type, and its more-qualified variants, into the set
5102 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005103 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005104 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00005105 } else if (Ty->isMemberPointerType()) {
5106 // Member pointers are far easier, since the pointee can't be converted.
5107 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5108 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005109 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005110 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00005111 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00005112 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005113 // We treat vector types as arithmetic types in many contexts as an
5114 // extension.
5115 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00005116 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005117 } else if (Ty->isNullPtrType()) {
5118 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00005119 } else if (AllowUserConversions && TyRec) {
5120 // No conversion functions in incomplete types.
5121 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5122 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005123
Chandler Carruth6a577462010-12-13 01:44:01 +00005124 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5125 const UnresolvedSetImpl *Conversions
5126 = ClassDecl->getVisibleConversionFunctions();
5127 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5128 E = Conversions->end(); I != E; ++I) {
5129 NamedDecl *D = I.getDecl();
5130 if (isa<UsingShadowDecl>(D))
5131 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005132
Chandler Carruth6a577462010-12-13 01:44:01 +00005133 // Skip conversion function templates; they don't tell us anything
5134 // about which builtin types we can convert to.
5135 if (isa<FunctionTemplateDecl>(D))
5136 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005137
Chandler Carruth6a577462010-12-13 01:44:01 +00005138 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5139 if (AllowExplicitConversions || !Conv->isExplicit()) {
5140 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5141 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005142 }
5143 }
5144 }
5145}
5146
Douglas Gregor19b7b152009-08-24 13:43:27 +00005147/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5148/// the volatile- and non-volatile-qualified assignment operators for the
5149/// given type to the candidate set.
5150static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5151 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00005152 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00005153 unsigned NumArgs,
5154 OverloadCandidateSet &CandidateSet) {
5155 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00005156
Douglas Gregor19b7b152009-08-24 13:43:27 +00005157 // T& operator=(T&, T)
5158 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5159 ParamTypes[1] = T;
5160 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5161 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00005162
Douglas Gregor19b7b152009-08-24 13:43:27 +00005163 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5164 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00005165 ParamTypes[0]
5166 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00005167 ParamTypes[1] = T;
5168 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00005169 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00005170 }
5171}
Mike Stump1eb44332009-09-09 15:08:12 +00005172
Sebastian Redl9994a342009-10-25 17:03:50 +00005173/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5174/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005175static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5176 Qualifiers VRQuals;
5177 const RecordType *TyRec;
5178 if (const MemberPointerType *RHSMPType =
5179 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00005180 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005181 else
5182 TyRec = ArgExpr->getType()->getAs<RecordType>();
5183 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005184 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005185 VRQuals.addVolatile();
5186 VRQuals.addRestrict();
5187 return VRQuals;
5188 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005189
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005190 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00005191 if (!ClassDecl->hasDefinition())
5192 return VRQuals;
5193
John McCalleec51cf2010-01-20 00:46:10 +00005194 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00005195 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005196
John McCalleec51cf2010-01-20 00:46:10 +00005197 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00005198 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00005199 NamedDecl *D = I.getDecl();
5200 if (isa<UsingShadowDecl>(D))
5201 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5202 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005203 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5204 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5205 CanTy = ResTypeRef->getPointeeType();
5206 // Need to go down the pointer/mempointer chain and add qualifiers
5207 // as see them.
5208 bool done = false;
5209 while (!done) {
5210 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5211 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005212 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005213 CanTy->getAs<MemberPointerType>())
5214 CanTy = ResTypeMPtr->getPointeeType();
5215 else
5216 done = true;
5217 if (CanTy.isVolatileQualified())
5218 VRQuals.addVolatile();
5219 if (CanTy.isRestrictQualified())
5220 VRQuals.addRestrict();
5221 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5222 return VRQuals;
5223 }
5224 }
5225 }
5226 return VRQuals;
5227}
John McCall00071ec2010-11-13 05:51:15 +00005228
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005229namespace {
John McCall00071ec2010-11-13 05:51:15 +00005230
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005231/// \brief Helper class to manage the addition of builtin operator overload
5232/// candidates. It provides shared state and utility methods used throughout
5233/// the process, as well as a helper method to add each group of builtin
5234/// operator overloads from the standard to a candidate set.
5235class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00005236 // Common instance state available to all overload candidate addition methods.
5237 Sema &S;
5238 Expr **Args;
5239 unsigned NumArgs;
5240 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00005241 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005242 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00005243 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005244
Chandler Carruth6d695582010-12-12 10:35:00 +00005245 // Define some constants used to index and iterate over the arithemetic types
5246 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00005247 // The "promoted arithmetic types" are the arithmetic
5248 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00005249 static const unsigned FirstIntegralType = 3;
5250 static const unsigned LastIntegralType = 18;
5251 static const unsigned FirstPromotedIntegralType = 3,
5252 LastPromotedIntegralType = 9;
5253 static const unsigned FirstPromotedArithmeticType = 0,
5254 LastPromotedArithmeticType = 9;
5255 static const unsigned NumArithmeticTypes = 18;
5256
Chandler Carruth6d695582010-12-12 10:35:00 +00005257 /// \brief Get the canonical type for a given arithmetic type index.
5258 CanQualType getArithmeticType(unsigned index) {
5259 assert(index < NumArithmeticTypes);
5260 static CanQualType ASTContext::* const
5261 ArithmeticTypes[NumArithmeticTypes] = {
5262 // Start of promoted types.
5263 &ASTContext::FloatTy,
5264 &ASTContext::DoubleTy,
5265 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00005266
Chandler Carruth6d695582010-12-12 10:35:00 +00005267 // Start of integral types.
5268 &ASTContext::IntTy,
5269 &ASTContext::LongTy,
5270 &ASTContext::LongLongTy,
5271 &ASTContext::UnsignedIntTy,
5272 &ASTContext::UnsignedLongTy,
5273 &ASTContext::UnsignedLongLongTy,
5274 // End of promoted types.
5275
5276 &ASTContext::BoolTy,
5277 &ASTContext::CharTy,
5278 &ASTContext::WCharTy,
5279 &ASTContext::Char16Ty,
5280 &ASTContext::Char32Ty,
5281 &ASTContext::SignedCharTy,
5282 &ASTContext::ShortTy,
5283 &ASTContext::UnsignedCharTy,
5284 &ASTContext::UnsignedShortTy,
5285 // End of integral types.
5286 // FIXME: What about complex?
5287 };
5288 return S.Context.*ArithmeticTypes[index];
5289 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005290
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005291 /// \brief Gets the canonical type resulting from the usual arithemetic
5292 /// converions for the given arithmetic types.
5293 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5294 // Accelerator table for performing the usual arithmetic conversions.
5295 // The rules are basically:
5296 // - if either is floating-point, use the wider floating-point
5297 // - if same signedness, use the higher rank
5298 // - if same size, use unsigned of the higher rank
5299 // - use the larger type
5300 // These rules, together with the axiom that higher ranks are
5301 // never smaller, are sufficient to precompute all of these results
5302 // *except* when dealing with signed types of higher rank.
5303 // (we could precompute SLL x UI for all known platforms, but it's
5304 // better not to make any assumptions).
5305 enum PromotedType {
5306 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5307 };
5308 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5309 [LastPromotedArithmeticType] = {
5310 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5311 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5312 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5313 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5314 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5315 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5316 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5317 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5318 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5319 };
5320
5321 assert(L < LastPromotedArithmeticType);
5322 assert(R < LastPromotedArithmeticType);
5323 int Idx = ConversionsTable[L][R];
5324
5325 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00005326 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005327
5328 // Slow path: we need to compare widths.
5329 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00005330 CanQualType LT = getArithmeticType(L),
5331 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005332 unsigned LW = S.Context.getIntWidth(LT),
5333 RW = S.Context.getIntWidth(RT);
5334
5335 // If they're different widths, use the signed type.
5336 if (LW > RW) return LT;
5337 else if (LW < RW) return RT;
5338
5339 // Otherwise, use the unsigned type of the signed type's rank.
5340 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5341 assert(L == SLL || R == SLL);
5342 return S.Context.UnsignedLongLongTy;
5343 }
5344
Chandler Carruth3c69dc42010-12-12 09:22:45 +00005345 /// \brief Helper method to factor out the common pattern of adding overloads
5346 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005347 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5348 bool HasVolatile) {
5349 QualType ParamTypes[2] = {
5350 S.Context.getLValueReferenceType(CandidateTy),
5351 S.Context.IntTy
5352 };
5353
5354 // Non-volatile version.
5355 if (NumArgs == 1)
5356 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5357 else
5358 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5359
5360 // Use a heuristic to reduce number of builtin candidates in the set:
5361 // add volatile version only if there are conversions to a volatile type.
5362 if (HasVolatile) {
5363 ParamTypes[0] =
5364 S.Context.getLValueReferenceType(
5365 S.Context.getVolatileType(CandidateTy));
5366 if (NumArgs == 1)
5367 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5368 else
5369 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5370 }
5371 }
5372
5373public:
5374 BuiltinOperatorOverloadBuilder(
5375 Sema &S, Expr **Args, unsigned NumArgs,
5376 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00005377 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005378 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005379 OverloadCandidateSet &CandidateSet)
5380 : S(S), Args(Args), NumArgs(NumArgs),
5381 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00005382 HasArithmeticOrEnumeralCandidateType(
5383 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005384 CandidateTypes(CandidateTypes),
5385 CandidateSet(CandidateSet) {
5386 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00005387 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005388 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005389 assert(getArithmeticType(LastPromotedIntegralType - 1)
5390 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005391 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005392 assert(getArithmeticType(FirstPromotedArithmeticType)
5393 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005394 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005395 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5396 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005397 "Invalid last promoted arithmetic type");
5398 }
5399
5400 // C++ [over.built]p3:
5401 //
5402 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5403 // is either volatile or empty, there exist candidate operator
5404 // functions of the form
5405 //
5406 // VQ T& operator++(VQ T&);
5407 // T operator++(VQ T&, int);
5408 //
5409 // C++ [over.built]p4:
5410 //
5411 // For every pair (T, VQ), where T is an arithmetic type other
5412 // than bool, and VQ is either volatile or empty, there exist
5413 // candidate operator functions of the form
5414 //
5415 // VQ T& operator--(VQ T&);
5416 // T operator--(VQ T&, int);
5417 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005418 if (!HasArithmeticOrEnumeralCandidateType)
5419 return;
5420
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005421 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5422 Arith < NumArithmeticTypes; ++Arith) {
5423 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00005424 getArithmeticType(Arith),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005425 VisibleTypeConversionsQuals.hasVolatile());
5426 }
5427 }
5428
5429 // C++ [over.built]p5:
5430 //
5431 // For every pair (T, VQ), where T is a cv-qualified or
5432 // cv-unqualified object type, and VQ is either volatile or
5433 // empty, there exist candidate operator functions of the form
5434 //
5435 // T*VQ& operator++(T*VQ&);
5436 // T*VQ& operator--(T*VQ&);
5437 // T* operator++(T*VQ&, int);
5438 // T* operator--(T*VQ&, int);
5439 void addPlusPlusMinusMinusPointerOverloads() {
5440 for (BuiltinCandidateTypeSet::iterator
5441 Ptr = CandidateTypes[0].pointer_begin(),
5442 PtrEnd = CandidateTypes[0].pointer_end();
5443 Ptr != PtrEnd; ++Ptr) {
5444 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005445 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005446 continue;
5447
5448 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5449 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5450 VisibleTypeConversionsQuals.hasVolatile()));
5451 }
5452 }
5453
5454 // C++ [over.built]p6:
5455 // For every cv-qualified or cv-unqualified object type T, there
5456 // exist candidate operator functions of the form
5457 //
5458 // T& operator*(T*);
5459 //
5460 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005461 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005462 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005463 // T& operator*(T*);
5464 void addUnaryStarPointerOverloads() {
5465 for (BuiltinCandidateTypeSet::iterator
5466 Ptr = CandidateTypes[0].pointer_begin(),
5467 PtrEnd = CandidateTypes[0].pointer_end();
5468 Ptr != PtrEnd; ++Ptr) {
5469 QualType ParamTy = *Ptr;
5470 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005471 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5472 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005473
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005474 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5475 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5476 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005477
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005478 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5479 &ParamTy, Args, 1, CandidateSet);
5480 }
5481 }
5482
5483 // C++ [over.built]p9:
5484 // For every promoted arithmetic type T, there exist candidate
5485 // operator functions of the form
5486 //
5487 // T operator+(T);
5488 // T operator-(T);
5489 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00005490 if (!HasArithmeticOrEnumeralCandidateType)
5491 return;
5492
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005493 for (unsigned Arith = FirstPromotedArithmeticType;
5494 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005495 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005496 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5497 }
5498
5499 // Extension: We also add these operators for vector types.
5500 for (BuiltinCandidateTypeSet::iterator
5501 Vec = CandidateTypes[0].vector_begin(),
5502 VecEnd = CandidateTypes[0].vector_end();
5503 Vec != VecEnd; ++Vec) {
5504 QualType VecTy = *Vec;
5505 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5506 }
5507 }
5508
5509 // C++ [over.built]p8:
5510 // For every type T, there exist candidate operator functions of
5511 // the form
5512 //
5513 // T* operator+(T*);
5514 void addUnaryPlusPointerOverloads() {
5515 for (BuiltinCandidateTypeSet::iterator
5516 Ptr = CandidateTypes[0].pointer_begin(),
5517 PtrEnd = CandidateTypes[0].pointer_end();
5518 Ptr != PtrEnd; ++Ptr) {
5519 QualType ParamTy = *Ptr;
5520 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5521 }
5522 }
5523
5524 // C++ [over.built]p10:
5525 // For every promoted integral type T, there exist candidate
5526 // operator functions of the form
5527 //
5528 // T operator~(T);
5529 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00005530 if (!HasArithmeticOrEnumeralCandidateType)
5531 return;
5532
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005533 for (unsigned Int = FirstPromotedIntegralType;
5534 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005535 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005536 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5537 }
5538
5539 // Extension: We also add this operator for vector types.
5540 for (BuiltinCandidateTypeSet::iterator
5541 Vec = CandidateTypes[0].vector_begin(),
5542 VecEnd = CandidateTypes[0].vector_end();
5543 Vec != VecEnd; ++Vec) {
5544 QualType VecTy = *Vec;
5545 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5546 }
5547 }
5548
5549 // C++ [over.match.oper]p16:
5550 // For every pointer to member type T, there exist candidate operator
5551 // functions of the form
5552 //
5553 // bool operator==(T,T);
5554 // bool operator!=(T,T);
5555 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5556 /// Set of (canonical) types that we've already handled.
5557 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5558
5559 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5560 for (BuiltinCandidateTypeSet::iterator
5561 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5562 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5563 MemPtr != MemPtrEnd;
5564 ++MemPtr) {
5565 // Don't add the same builtin candidate twice.
5566 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5567 continue;
5568
5569 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5570 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5571 CandidateSet);
5572 }
5573 }
5574 }
5575
5576 // C++ [over.built]p15:
5577 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005578 // For every T, where T is an enumeration type, a pointer type, or
5579 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005580 //
5581 // bool operator<(T, T);
5582 // bool operator>(T, T);
5583 // bool operator<=(T, T);
5584 // bool operator>=(T, T);
5585 // bool operator==(T, T);
5586 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005587 void addRelationalPointerOrEnumeralOverloads() {
5588 // C++ [over.built]p1:
5589 // If there is a user-written candidate with the same name and parameter
5590 // types as a built-in candidate operator function, the built-in operator
5591 // function is hidden and is not included in the set of candidate
5592 // functions.
5593 //
5594 // The text is actually in a note, but if we don't implement it then we end
5595 // up with ambiguities when the user provides an overloaded operator for
5596 // an enumeration type. Note that only enumeration types have this problem,
5597 // so we track which enumeration types we've seen operators for. Also, the
5598 // only other overloaded operator with enumeration argumenst, operator=,
5599 // cannot be overloaded for enumeration types, so this is the only place
5600 // where we must suppress candidates like this.
5601 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5602 UserDefinedBinaryOperators;
5603
5604 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5605 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5606 CandidateTypes[ArgIdx].enumeration_end()) {
5607 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5608 CEnd = CandidateSet.end();
5609 C != CEnd; ++C) {
5610 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5611 continue;
5612
5613 QualType FirstParamType =
5614 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5615 QualType SecondParamType =
5616 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5617
5618 // Skip if either parameter isn't of enumeral type.
5619 if (!FirstParamType->isEnumeralType() ||
5620 !SecondParamType->isEnumeralType())
5621 continue;
5622
5623 // Add this operator to the set of known user-defined operators.
5624 UserDefinedBinaryOperators.insert(
5625 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5626 S.Context.getCanonicalType(SecondParamType)));
5627 }
5628 }
5629 }
5630
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005631 /// Set of (canonical) types that we've already handled.
5632 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5633
5634 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5635 for (BuiltinCandidateTypeSet::iterator
5636 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5637 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5638 Ptr != PtrEnd; ++Ptr) {
5639 // Don't add the same builtin candidate twice.
5640 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5641 continue;
5642
5643 QualType ParamTypes[2] = { *Ptr, *Ptr };
5644 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5645 CandidateSet);
5646 }
5647 for (BuiltinCandidateTypeSet::iterator
5648 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5649 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5650 Enum != EnumEnd; ++Enum) {
5651 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5652
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005653 // Don't add the same builtin candidate twice, or if a user defined
5654 // candidate exists.
5655 if (!AddedTypes.insert(CanonType) ||
5656 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5657 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005658 continue;
5659
5660 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005661 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5662 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005663 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005664
5665 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5666 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5667 if (AddedTypes.insert(NullPtrTy) &&
5668 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
5669 NullPtrTy))) {
5670 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5671 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5672 CandidateSet);
5673 }
5674 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005675 }
5676 }
5677
5678 // C++ [over.built]p13:
5679 //
5680 // For every cv-qualified or cv-unqualified object type T
5681 // there exist candidate operator functions of the form
5682 //
5683 // T* operator+(T*, ptrdiff_t);
5684 // T& operator[](T*, ptrdiff_t); [BELOW]
5685 // T* operator-(T*, ptrdiff_t);
5686 // T* operator+(ptrdiff_t, T*);
5687 // T& operator[](ptrdiff_t, T*); [BELOW]
5688 //
5689 // C++ [over.built]p14:
5690 //
5691 // For every T, where T is a pointer to object type, there
5692 // exist candidate operator functions of the form
5693 //
5694 // ptrdiff_t operator-(T, T);
5695 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5696 /// Set of (canonical) types that we've already handled.
5697 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5698
5699 for (int Arg = 0; Arg < 2; ++Arg) {
5700 QualType AsymetricParamTypes[2] = {
5701 S.Context.getPointerDiffType(),
5702 S.Context.getPointerDiffType(),
5703 };
5704 for (BuiltinCandidateTypeSet::iterator
5705 Ptr = CandidateTypes[Arg].pointer_begin(),
5706 PtrEnd = CandidateTypes[Arg].pointer_end();
5707 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005708 QualType PointeeTy = (*Ptr)->getPointeeType();
5709 if (!PointeeTy->isObjectType())
5710 continue;
5711
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005712 AsymetricParamTypes[Arg] = *Ptr;
5713 if (Arg == 0 || Op == OO_Plus) {
5714 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5715 // T* operator+(ptrdiff_t, T*);
5716 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5717 CandidateSet);
5718 }
5719 if (Op == OO_Minus) {
5720 // ptrdiff_t operator-(T, T);
5721 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5722 continue;
5723
5724 QualType ParamTypes[2] = { *Ptr, *Ptr };
5725 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5726 Args, 2, CandidateSet);
5727 }
5728 }
5729 }
5730 }
5731
5732 // C++ [over.built]p12:
5733 //
5734 // For every pair of promoted arithmetic types L and R, there
5735 // exist candidate operator functions of the form
5736 //
5737 // LR operator*(L, R);
5738 // LR operator/(L, R);
5739 // LR operator+(L, R);
5740 // LR operator-(L, R);
5741 // bool operator<(L, R);
5742 // bool operator>(L, R);
5743 // bool operator<=(L, R);
5744 // bool operator>=(L, R);
5745 // bool operator==(L, R);
5746 // bool operator!=(L, R);
5747 //
5748 // where LR is the result of the usual arithmetic conversions
5749 // between types L and R.
5750 //
5751 // C++ [over.built]p24:
5752 //
5753 // For every pair of promoted arithmetic types L and R, there exist
5754 // candidate operator functions of the form
5755 //
5756 // LR operator?(bool, L, R);
5757 //
5758 // where LR is the result of the usual arithmetic conversions
5759 // between types L and R.
5760 // Our candidates ignore the first parameter.
5761 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005762 if (!HasArithmeticOrEnumeralCandidateType)
5763 return;
5764
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005765 for (unsigned Left = FirstPromotedArithmeticType;
5766 Left < LastPromotedArithmeticType; ++Left) {
5767 for (unsigned Right = FirstPromotedArithmeticType;
5768 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005769 QualType LandR[2] = { getArithmeticType(Left),
5770 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005771 QualType Result =
5772 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005773 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005774 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5775 }
5776 }
5777
5778 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5779 // conditional operator for vector types.
5780 for (BuiltinCandidateTypeSet::iterator
5781 Vec1 = CandidateTypes[0].vector_begin(),
5782 Vec1End = CandidateTypes[0].vector_end();
5783 Vec1 != Vec1End; ++Vec1) {
5784 for (BuiltinCandidateTypeSet::iterator
5785 Vec2 = CandidateTypes[1].vector_begin(),
5786 Vec2End = CandidateTypes[1].vector_end();
5787 Vec2 != Vec2End; ++Vec2) {
5788 QualType LandR[2] = { *Vec1, *Vec2 };
5789 QualType Result = S.Context.BoolTy;
5790 if (!isComparison) {
5791 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5792 Result = *Vec1;
5793 else
5794 Result = *Vec2;
5795 }
5796
5797 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5798 }
5799 }
5800 }
5801
5802 // C++ [over.built]p17:
5803 //
5804 // For every pair of promoted integral types L and R, there
5805 // exist candidate operator functions of the form
5806 //
5807 // LR operator%(L, R);
5808 // LR operator&(L, R);
5809 // LR operator^(L, R);
5810 // LR operator|(L, R);
5811 // L operator<<(L, R);
5812 // L operator>>(L, R);
5813 //
5814 // where LR is the result of the usual arithmetic conversions
5815 // between types L and R.
5816 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005817 if (!HasArithmeticOrEnumeralCandidateType)
5818 return;
5819
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005820 for (unsigned Left = FirstPromotedIntegralType;
5821 Left < LastPromotedIntegralType; ++Left) {
5822 for (unsigned Right = FirstPromotedIntegralType;
5823 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005824 QualType LandR[2] = { getArithmeticType(Left),
5825 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005826 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5827 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005828 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005829 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5830 }
5831 }
5832 }
5833
5834 // C++ [over.built]p20:
5835 //
5836 // For every pair (T, VQ), where T is an enumeration or
5837 // pointer to member type and VQ is either volatile or
5838 // empty, there exist candidate operator functions of the form
5839 //
5840 // VQ T& operator=(VQ T&, T);
5841 void addAssignmentMemberPointerOrEnumeralOverloads() {
5842 /// Set of (canonical) types that we've already handled.
5843 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5844
5845 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5846 for (BuiltinCandidateTypeSet::iterator
5847 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5848 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5849 Enum != EnumEnd; ++Enum) {
5850 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5851 continue;
5852
5853 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5854 CandidateSet);
5855 }
5856
5857 for (BuiltinCandidateTypeSet::iterator
5858 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5859 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5860 MemPtr != MemPtrEnd; ++MemPtr) {
5861 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5862 continue;
5863
5864 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5865 CandidateSet);
5866 }
5867 }
5868 }
5869
5870 // C++ [over.built]p19:
5871 //
5872 // For every pair (T, VQ), where T is any type and VQ is either
5873 // volatile or empty, there exist candidate operator functions
5874 // of the form
5875 //
5876 // T*VQ& operator=(T*VQ&, T*);
5877 //
5878 // C++ [over.built]p21:
5879 //
5880 // For every pair (T, VQ), where T is a cv-qualified or
5881 // cv-unqualified object type and VQ is either volatile or
5882 // empty, there exist candidate operator functions of the form
5883 //
5884 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5885 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5886 void addAssignmentPointerOverloads(bool isEqualOp) {
5887 /// Set of (canonical) types that we've already handled.
5888 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5889
5890 for (BuiltinCandidateTypeSet::iterator
5891 Ptr = CandidateTypes[0].pointer_begin(),
5892 PtrEnd = CandidateTypes[0].pointer_end();
5893 Ptr != PtrEnd; ++Ptr) {
5894 // If this is operator=, keep track of the builtin candidates we added.
5895 if (isEqualOp)
5896 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005897 else if (!(*Ptr)->getPointeeType()->isObjectType())
5898 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005899
5900 // non-volatile version
5901 QualType ParamTypes[2] = {
5902 S.Context.getLValueReferenceType(*Ptr),
5903 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5904 };
5905 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5906 /*IsAssigmentOperator=*/ isEqualOp);
5907
5908 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5909 VisibleTypeConversionsQuals.hasVolatile()) {
5910 // volatile version
5911 ParamTypes[0] =
5912 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5913 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5914 /*IsAssigmentOperator=*/isEqualOp);
5915 }
5916 }
5917
5918 if (isEqualOp) {
5919 for (BuiltinCandidateTypeSet::iterator
5920 Ptr = CandidateTypes[1].pointer_begin(),
5921 PtrEnd = CandidateTypes[1].pointer_end();
5922 Ptr != PtrEnd; ++Ptr) {
5923 // Make sure we don't add the same candidate twice.
5924 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5925 continue;
5926
Chandler Carruth6df868e2010-12-12 08:17:55 +00005927 QualType ParamTypes[2] = {
5928 S.Context.getLValueReferenceType(*Ptr),
5929 *Ptr,
5930 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005931
5932 // non-volatile version
5933 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5934 /*IsAssigmentOperator=*/true);
5935
5936 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5937 VisibleTypeConversionsQuals.hasVolatile()) {
5938 // volatile version
5939 ParamTypes[0] =
5940 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00005941 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5942 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005943 }
5944 }
5945 }
5946 }
5947
5948 // C++ [over.built]p18:
5949 //
5950 // For every triple (L, VQ, R), where L is an arithmetic type,
5951 // VQ is either volatile or empty, and R is a promoted
5952 // arithmetic type, there exist candidate operator functions of
5953 // the form
5954 //
5955 // VQ L& operator=(VQ L&, R);
5956 // VQ L& operator*=(VQ L&, R);
5957 // VQ L& operator/=(VQ L&, R);
5958 // VQ L& operator+=(VQ L&, R);
5959 // VQ L& operator-=(VQ L&, R);
5960 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005961 if (!HasArithmeticOrEnumeralCandidateType)
5962 return;
5963
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005964 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5965 for (unsigned Right = FirstPromotedArithmeticType;
5966 Right < LastPromotedArithmeticType; ++Right) {
5967 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00005968 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005969
5970 // Add this built-in operator as a candidate (VQ is empty).
5971 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00005972 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005973 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5974 /*IsAssigmentOperator=*/isEqualOp);
5975
5976 // Add this built-in operator as a candidate (VQ is 'volatile').
5977 if (VisibleTypeConversionsQuals.hasVolatile()) {
5978 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00005979 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005980 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00005981 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5982 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005983 /*IsAssigmentOperator=*/isEqualOp);
5984 }
5985 }
5986 }
5987
5988 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5989 for (BuiltinCandidateTypeSet::iterator
5990 Vec1 = CandidateTypes[0].vector_begin(),
5991 Vec1End = CandidateTypes[0].vector_end();
5992 Vec1 != Vec1End; ++Vec1) {
5993 for (BuiltinCandidateTypeSet::iterator
5994 Vec2 = CandidateTypes[1].vector_begin(),
5995 Vec2End = CandidateTypes[1].vector_end();
5996 Vec2 != Vec2End; ++Vec2) {
5997 QualType ParamTypes[2];
5998 ParamTypes[1] = *Vec2;
5999 // Add this built-in operator as a candidate (VQ is empty).
6000 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6001 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6002 /*IsAssigmentOperator=*/isEqualOp);
6003
6004 // Add this built-in operator as a candidate (VQ is 'volatile').
6005 if (VisibleTypeConversionsQuals.hasVolatile()) {
6006 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6007 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006008 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6009 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006010 /*IsAssigmentOperator=*/isEqualOp);
6011 }
6012 }
6013 }
6014 }
6015
6016 // C++ [over.built]p22:
6017 //
6018 // For every triple (L, VQ, R), where L is an integral type, VQ
6019 // is either volatile or empty, and R is a promoted integral
6020 // type, there exist candidate operator functions of the form
6021 //
6022 // VQ L& operator%=(VQ L&, R);
6023 // VQ L& operator<<=(VQ L&, R);
6024 // VQ L& operator>>=(VQ L&, R);
6025 // VQ L& operator&=(VQ L&, R);
6026 // VQ L& operator^=(VQ L&, R);
6027 // VQ L& operator|=(VQ L&, R);
6028 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006029 if (!HasArithmeticOrEnumeralCandidateType)
6030 return;
6031
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006032 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6033 for (unsigned Right = FirstPromotedIntegralType;
6034 Right < LastPromotedIntegralType; ++Right) {
6035 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00006036 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006037
6038 // Add this built-in operator as a candidate (VQ is empty).
6039 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006040 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006041 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6042 if (VisibleTypeConversionsQuals.hasVolatile()) {
6043 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00006044 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006045 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6046 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6047 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6048 CandidateSet);
6049 }
6050 }
6051 }
6052 }
6053
6054 // C++ [over.operator]p23:
6055 //
6056 // There also exist candidate operator functions of the form
6057 //
6058 // bool operator!(bool);
6059 // bool operator&&(bool, bool);
6060 // bool operator||(bool, bool);
6061 void addExclaimOverload() {
6062 QualType ParamTy = S.Context.BoolTy;
6063 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6064 /*IsAssignmentOperator=*/false,
6065 /*NumContextualBoolArguments=*/1);
6066 }
6067 void addAmpAmpOrPipePipeOverload() {
6068 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6069 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6070 /*IsAssignmentOperator=*/false,
6071 /*NumContextualBoolArguments=*/2);
6072 }
6073
6074 // C++ [over.built]p13:
6075 //
6076 // For every cv-qualified or cv-unqualified object type T there
6077 // exist candidate operator functions of the form
6078 //
6079 // T* operator+(T*, ptrdiff_t); [ABOVE]
6080 // T& operator[](T*, ptrdiff_t);
6081 // T* operator-(T*, ptrdiff_t); [ABOVE]
6082 // T* operator+(ptrdiff_t, T*); [ABOVE]
6083 // T& operator[](ptrdiff_t, T*);
6084 void addSubscriptOverloads() {
6085 for (BuiltinCandidateTypeSet::iterator
6086 Ptr = CandidateTypes[0].pointer_begin(),
6087 PtrEnd = CandidateTypes[0].pointer_end();
6088 Ptr != PtrEnd; ++Ptr) {
6089 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6090 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006091 if (!PointeeType->isObjectType())
6092 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006093
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006094 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6095
6096 // T& operator[](T*, ptrdiff_t)
6097 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6098 }
6099
6100 for (BuiltinCandidateTypeSet::iterator
6101 Ptr = CandidateTypes[1].pointer_begin(),
6102 PtrEnd = CandidateTypes[1].pointer_end();
6103 Ptr != PtrEnd; ++Ptr) {
6104 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6105 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006106 if (!PointeeType->isObjectType())
6107 continue;
6108
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006109 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6110
6111 // T& operator[](ptrdiff_t, T*)
6112 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6113 }
6114 }
6115
6116 // C++ [over.built]p11:
6117 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6118 // C1 is the same type as C2 or is a derived class of C2, T is an object
6119 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6120 // there exist candidate operator functions of the form
6121 //
6122 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6123 //
6124 // where CV12 is the union of CV1 and CV2.
6125 void addArrowStarOverloads() {
6126 for (BuiltinCandidateTypeSet::iterator
6127 Ptr = CandidateTypes[0].pointer_begin(),
6128 PtrEnd = CandidateTypes[0].pointer_end();
6129 Ptr != PtrEnd; ++Ptr) {
6130 QualType C1Ty = (*Ptr);
6131 QualType C1;
6132 QualifierCollector Q1;
6133 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6134 if (!isa<RecordType>(C1))
6135 continue;
6136 // heuristic to reduce number of builtin candidates in the set.
6137 // Add volatile/restrict version only if there are conversions to a
6138 // volatile/restrict type.
6139 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6140 continue;
6141 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6142 continue;
6143 for (BuiltinCandidateTypeSet::iterator
6144 MemPtr = CandidateTypes[1].member_pointer_begin(),
6145 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6146 MemPtr != MemPtrEnd; ++MemPtr) {
6147 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6148 QualType C2 = QualType(mptr->getClass(), 0);
6149 C2 = C2.getUnqualifiedType();
6150 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6151 break;
6152 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6153 // build CV12 T&
6154 QualType T = mptr->getPointeeType();
6155 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6156 T.isVolatileQualified())
6157 continue;
6158 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6159 T.isRestrictQualified())
6160 continue;
6161 T = Q1.apply(S.Context, T);
6162 QualType ResultTy = S.Context.getLValueReferenceType(T);
6163 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6164 }
6165 }
6166 }
6167
6168 // Note that we don't consider the first argument, since it has been
6169 // contextually converted to bool long ago. The candidates below are
6170 // therefore added as binary.
6171 //
6172 // C++ [over.built]p25:
6173 // For every type T, where T is a pointer, pointer-to-member, or scoped
6174 // enumeration type, there exist candidate operator functions of the form
6175 //
6176 // T operator?(bool, T, T);
6177 //
6178 void addConditionalOperatorOverloads() {
6179 /// Set of (canonical) types that we've already handled.
6180 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6181
6182 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6183 for (BuiltinCandidateTypeSet::iterator
6184 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6185 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6186 Ptr != PtrEnd; ++Ptr) {
6187 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6188 continue;
6189
6190 QualType ParamTypes[2] = { *Ptr, *Ptr };
6191 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6192 }
6193
6194 for (BuiltinCandidateTypeSet::iterator
6195 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6196 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6197 MemPtr != MemPtrEnd; ++MemPtr) {
6198 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6199 continue;
6200
6201 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6202 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6203 }
6204
6205 if (S.getLangOptions().CPlusPlus0x) {
6206 for (BuiltinCandidateTypeSet::iterator
6207 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6208 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6209 Enum != EnumEnd; ++Enum) {
6210 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6211 continue;
6212
6213 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6214 continue;
6215
6216 QualType ParamTypes[2] = { *Enum, *Enum };
6217 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6218 }
6219 }
6220 }
6221 }
6222};
6223
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006224} // end anonymous namespace
6225
6226/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6227/// operator overloads to the candidate set (C++ [over.built]), based
6228/// on the operator @p Op and the arguments given. For example, if the
6229/// operator is a binary '+', this routine might add "int
6230/// operator+(int, int)" to cover integer addition.
6231void
6232Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6233 SourceLocation OpLoc,
6234 Expr **Args, unsigned NumArgs,
6235 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006236 // Find all of the types that the arguments can convert to, but only
6237 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00006238 // that make use of these types. Also record whether we encounter non-record
6239 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006240 Qualifiers VisibleTypeConversionsQuals;
6241 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00006242 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6243 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00006244
6245 bool HasNonRecordCandidateType = false;
6246 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006247 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00006248 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6249 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6250 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6251 OpLoc,
6252 true,
6253 (Op == OO_Exclaim ||
6254 Op == OO_AmpAmp ||
6255 Op == OO_PipePipe),
6256 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00006257 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6258 CandidateTypes[ArgIdx].hasNonRecordTypes();
6259 HasArithmeticOrEnumeralCandidateType =
6260 HasArithmeticOrEnumeralCandidateType ||
6261 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00006262 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006263
Chandler Carruth6a577462010-12-13 01:44:01 +00006264 // Exit early when no non-record types have been added to the candidate set
6265 // for any of the arguments to the operator.
6266 if (!HasNonRecordCandidateType)
6267 return;
6268
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006269 // Setup an object to manage the common state for building overloads.
6270 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6271 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006272 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006273 CandidateTypes, CandidateSet);
6274
6275 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006276 switch (Op) {
6277 case OO_None:
6278 case NUM_OVERLOADED_OPERATORS:
6279 assert(false && "Expected an overloaded operator");
6280 break;
6281
Chandler Carruthabb71842010-12-12 08:51:33 +00006282 case OO_New:
6283 case OO_Delete:
6284 case OO_Array_New:
6285 case OO_Array_Delete:
6286 case OO_Call:
6287 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
6288 break;
6289
6290 case OO_Comma:
6291 case OO_Arrow:
6292 // C++ [over.match.oper]p3:
6293 // -- For the operator ',', the unary operator '&', or the
6294 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00006295 break;
6296
6297 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00006298 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006299 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00006300 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00006301
6302 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00006303 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006304 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00006305 } else {
6306 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6307 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6308 }
Douglas Gregor74253732008-11-19 15:42:04 +00006309 break;
6310
Chandler Carruthabb71842010-12-12 08:51:33 +00006311 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00006312 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00006313 OpBuilder.addUnaryStarPointerOverloads();
6314 else
6315 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6316 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006317
Chandler Carruthabb71842010-12-12 08:51:33 +00006318 case OO_Slash:
6319 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00006320 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006321
6322 case OO_PlusPlus:
6323 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006324 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6325 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00006326 break;
6327
Douglas Gregor19b7b152009-08-24 13:43:27 +00006328 case OO_EqualEqual:
6329 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006330 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00006331 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00006332
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006333 case OO_Less:
6334 case OO_Greater:
6335 case OO_LessEqual:
6336 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006337 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00006338 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6339 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006340
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006341 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006342 case OO_Caret:
6343 case OO_Pipe:
6344 case OO_LessLess:
6345 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006346 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006347 break;
6348
Chandler Carruthabb71842010-12-12 08:51:33 +00006349 case OO_Amp: // '&' is either unary or binary
6350 if (NumArgs == 1)
6351 // C++ [over.match.oper]p3:
6352 // -- For the operator ',', the unary operator '&', or the
6353 // operator '->', the built-in candidates set is empty.
6354 break;
6355
6356 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6357 break;
6358
6359 case OO_Tilde:
6360 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6361 break;
6362
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006363 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006364 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00006365 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006366
6367 case OO_PlusEqual:
6368 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006369 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006370 // Fall through.
6371
6372 case OO_StarEqual:
6373 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006374 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006375 break;
6376
6377 case OO_PercentEqual:
6378 case OO_LessLessEqual:
6379 case OO_GreaterGreaterEqual:
6380 case OO_AmpEqual:
6381 case OO_CaretEqual:
6382 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006383 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006384 break;
6385
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006386 case OO_Exclaim:
6387 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00006388 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006389
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006390 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006391 case OO_PipePipe:
6392 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006393 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006394
6395 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006396 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006397 break;
6398
6399 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006400 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006401 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006402
6403 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006404 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00006405 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6406 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006407 }
6408}
6409
Douglas Gregorfa047642009-02-04 00:32:51 +00006410/// \brief Add function candidates found via argument-dependent lookup
6411/// to the set of overloading candidates.
6412///
6413/// This routine performs argument-dependent name lookup based on the
6414/// given function name (which may also be an operator name) and adds
6415/// all of the overload candidates found by ADL to the overload
6416/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00006417void
Douglas Gregorfa047642009-02-04 00:32:51 +00006418Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00006419 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00006420 Expr **Args, unsigned NumArgs,
Douglas Gregor67714232011-03-03 02:41:12 +00006421 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006422 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00006423 bool PartialOverloading,
6424 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00006425 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00006426
John McCalla113e722010-01-26 06:04:06 +00006427 // FIXME: This approach for uniquing ADL results (and removing
6428 // redundant candidates from the set) relies on pointer-equality,
6429 // which means we need to key off the canonical decl. However,
6430 // always going back to the canonical decl might not get us the
6431 // right set of default arguments. What default arguments are
6432 // we supposed to consider on ADL candidates, anyway?
6433
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006434 // FIXME: Pass in the explicit template arguments?
Richard Smithad762fc2011-04-14 22:09:26 +00006435 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6436 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00006437
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006438 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006439 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6440 CandEnd = CandidateSet.end();
6441 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00006442 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00006443 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00006444 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00006445 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00006446 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006447
6448 // For each of the ADL candidates we found, add it to the overload
6449 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00006450 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00006451 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00006452 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00006453 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006454 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006455
John McCall9aa472c2010-03-19 07:35:19 +00006456 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006457 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006458 } else
John McCall6e266892010-01-26 03:27:55 +00006459 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00006460 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00006461 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00006462 }
Douglas Gregorfa047642009-02-04 00:32:51 +00006463}
6464
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006465/// isBetterOverloadCandidate - Determines whether the first overload
6466/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00006467bool
John McCall120d63c2010-08-24 20:38:10 +00006468isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00006469 const OverloadCandidate &Cand1,
6470 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006471 SourceLocation Loc,
6472 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006473 // Define viable functions to be better candidates than non-viable
6474 // functions.
6475 if (!Cand2.Viable)
6476 return Cand1.Viable;
6477 else if (!Cand1.Viable)
6478 return false;
6479
Douglas Gregor88a35142008-12-22 05:46:06 +00006480 // C++ [over.match.best]p1:
6481 //
6482 // -- if F is a static member function, ICS1(F) is defined such
6483 // that ICS1(F) is neither better nor worse than ICS1(G) for
6484 // any function G, and, symmetrically, ICS1(G) is neither
6485 // better nor worse than ICS1(F).
6486 unsigned StartArg = 0;
6487 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6488 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006489
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006490 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00006491 // A viable function F1 is defined to be a better function than another
6492 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006493 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006494 unsigned NumArgs = Cand1.Conversions.size();
6495 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6496 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006497 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00006498 switch (CompareImplicitConversionSequences(S,
6499 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006500 Cand2.Conversions[ArgIdx])) {
6501 case ImplicitConversionSequence::Better:
6502 // Cand1 has a better conversion sequence.
6503 HasBetterConversion = true;
6504 break;
6505
6506 case ImplicitConversionSequence::Worse:
6507 // Cand1 can't be better than Cand2.
6508 return false;
6509
6510 case ImplicitConversionSequence::Indistinguishable:
6511 // Do nothing.
6512 break;
6513 }
6514 }
6515
Mike Stump1eb44332009-09-09 15:08:12 +00006516 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006517 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006518 if (HasBetterConversion)
6519 return true;
6520
Mike Stump1eb44332009-09-09 15:08:12 +00006521 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006522 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00006523 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006524 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6525 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006526
6527 // -- F1 and F2 are function template specializations, and the function
6528 // template for F1 is more specialized than the template for F2
6529 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006530 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00006531 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00006532 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006533 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00006534 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6535 Cand2.Function->getPrimaryTemplate(),
6536 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006537 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00006538 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00006539 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006540 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00006541 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006542
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006543 // -- the context is an initialization by user-defined conversion
6544 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6545 // from the return type of F1 to the destination type (i.e.,
6546 // the type of the entity being initialized) is a better
6547 // conversion sequence than the standard conversion sequence
6548 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006549 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00006550 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006551 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00006552 switch (CompareStandardConversionSequences(S,
6553 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006554 Cand2.FinalConversion)) {
6555 case ImplicitConversionSequence::Better:
6556 // Cand1 has a better conversion sequence.
6557 return true;
6558
6559 case ImplicitConversionSequence::Worse:
6560 // Cand1 can't be better than Cand2.
6561 return false;
6562
6563 case ImplicitConversionSequence::Indistinguishable:
6564 // Do nothing
6565 break;
6566 }
6567 }
6568
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006569 return false;
6570}
6571
Mike Stump1eb44332009-09-09 15:08:12 +00006572/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00006573/// within an overload candidate set.
6574///
6575/// \param CandidateSet the set of candidate functions.
6576///
6577/// \param Loc the location of the function name (or operator symbol) for
6578/// which overload resolution occurs.
6579///
Mike Stump1eb44332009-09-09 15:08:12 +00006580/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00006581/// function, Best points to the candidate function found.
6582///
6583/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00006584OverloadingResult
6585OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00006586 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00006587 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006588 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00006589 Best = end();
6590 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6591 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006592 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006593 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006594 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006595 }
6596
6597 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00006598 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006599 return OR_No_Viable_Function;
6600
6601 // Make sure that this function is better than every other viable
6602 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00006603 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00006604 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006605 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006606 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006607 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00006608 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006609 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006610 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006611 }
Mike Stump1eb44332009-09-09 15:08:12 +00006612
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006613 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006614 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00006615 (Best->Function->isDeleted() ||
6616 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006617 return OR_Deleted;
6618
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006619 return OR_Success;
6620}
6621
John McCall3c80f572010-01-12 02:15:36 +00006622namespace {
6623
6624enum OverloadCandidateKind {
6625 oc_function,
6626 oc_method,
6627 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00006628 oc_function_template,
6629 oc_method_template,
6630 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00006631 oc_implicit_default_constructor,
6632 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00006633 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006634 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00006635 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006636 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00006637};
6638
John McCall220ccbf2010-01-13 00:25:19 +00006639OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6640 FunctionDecl *Fn,
6641 std::string &Description) {
6642 bool isTemplate = false;
6643
6644 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6645 isTemplate = true;
6646 Description = S.getTemplateArgumentBindingsText(
6647 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6648 }
John McCallb1622a12010-01-06 09:43:14 +00006649
6650 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00006651 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00006652 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00006653
Sebastian Redlf677ea32011-02-05 19:23:19 +00006654 if (Ctor->getInheritedConstructor())
6655 return oc_implicit_inherited_constructor;
6656
Sean Hunt82713172011-05-25 23:16:36 +00006657 if (Ctor->isDefaultConstructor())
6658 return oc_implicit_default_constructor;
6659
6660 if (Ctor->isMoveConstructor())
6661 return oc_implicit_move_constructor;
6662
6663 assert(Ctor->isCopyConstructor() &&
6664 "unexpected sort of implicit constructor");
6665 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00006666 }
6667
6668 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6669 // This actually gets spelled 'candidate function' for now, but
6670 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00006671 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00006672 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00006673
Sean Hunt82713172011-05-25 23:16:36 +00006674 if (Meth->isMoveAssignmentOperator())
6675 return oc_implicit_move_assignment;
6676
Douglas Gregor3e9438b2010-09-27 22:37:28 +00006677 assert(Meth->isCopyAssignmentOperator()
John McCallb1622a12010-01-06 09:43:14 +00006678 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00006679 return oc_implicit_copy_assignment;
6680 }
6681
John McCall220ccbf2010-01-13 00:25:19 +00006682 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00006683}
6684
Sebastian Redlf677ea32011-02-05 19:23:19 +00006685void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6686 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6687 if (!Ctor) return;
6688
6689 Ctor = Ctor->getInheritedConstructor();
6690 if (!Ctor) return;
6691
6692 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6693}
6694
John McCall3c80f572010-01-12 02:15:36 +00006695} // end anonymous namespace
6696
6697// Notes the location of an overload candidate.
6698void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00006699 std::string FnDesc;
6700 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6701 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6702 << (unsigned) K << FnDesc;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006703 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00006704}
6705
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006706//Notes the location of all overload candidates designated through
6707// OverloadedExpr
6708void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6709 assert(OverloadedExpr->getType() == Context.OverloadTy);
6710
6711 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6712 OverloadExpr *OvlExpr = Ovl.Expression;
6713
6714 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6715 IEnd = OvlExpr->decls_end();
6716 I != IEnd; ++I) {
6717 if (FunctionTemplateDecl *FunTmpl =
6718 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6719 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6720 } else if (FunctionDecl *Fun
6721 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6722 NoteOverloadCandidate(Fun);
6723 }
6724 }
6725}
6726
John McCall1d318332010-01-12 00:44:57 +00006727/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6728/// "lead" diagnostic; it will be given two arguments, the source and
6729/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00006730void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6731 Sema &S,
6732 SourceLocation CaretLoc,
6733 const PartialDiagnostic &PDiag) const {
6734 S.Diag(CaretLoc, PDiag)
6735 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00006736 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00006737 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6738 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00006739 }
John McCall81201622010-01-08 04:41:39 +00006740}
6741
John McCall1d318332010-01-12 00:44:57 +00006742namespace {
6743
John McCalladbb8f82010-01-13 09:16:55 +00006744void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6745 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6746 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00006747 assert(Cand->Function && "for now, candidate must be a function");
6748 FunctionDecl *Fn = Cand->Function;
6749
6750 // There's a conversion slot for the object argument if this is a
6751 // non-constructor method. Note that 'I' corresponds the
6752 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00006753 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00006754 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00006755 if (I == 0)
6756 isObjectArgument = true;
6757 else
6758 I--;
John McCall220ccbf2010-01-13 00:25:19 +00006759 }
6760
John McCall220ccbf2010-01-13 00:25:19 +00006761 std::string FnDesc;
6762 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6763
John McCalladbb8f82010-01-13 09:16:55 +00006764 Expr *FromExpr = Conv.Bad.FromExpr;
6765 QualType FromTy = Conv.Bad.getFromType();
6766 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00006767
John McCall5920dbb2010-02-02 02:42:52 +00006768 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00006769 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00006770 Expr *E = FromExpr->IgnoreParens();
6771 if (isa<UnaryOperator>(E))
6772 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00006773 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00006774
6775 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6776 << (unsigned) FnKind << FnDesc
6777 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6778 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006779 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00006780 return;
6781 }
6782
John McCall258b2032010-01-23 08:10:49 +00006783 // Do some hand-waving analysis to see if the non-viability is due
6784 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00006785 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6786 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6787 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6788 CToTy = RT->getPointeeType();
6789 else {
6790 // TODO: detect and diagnose the full richness of const mismatches.
6791 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6792 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6793 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6794 }
6795
6796 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6797 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6798 // It is dumb that we have to do this here.
6799 while (isa<ArrayType>(CFromTy))
6800 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6801 while (isa<ArrayType>(CToTy))
6802 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6803
6804 Qualifiers FromQs = CFromTy.getQualifiers();
6805 Qualifiers ToQs = CToTy.getQualifiers();
6806
6807 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6808 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6809 << (unsigned) FnKind << FnDesc
6810 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6811 << FromTy
6812 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6813 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006814 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00006815 return;
6816 }
6817
John McCallf85e1932011-06-15 23:02:42 +00006818 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00006819 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00006820 << (unsigned) FnKind << FnDesc
6821 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6822 << FromTy
6823 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
6824 << (unsigned) isObjectArgument << I+1;
6825 MaybeEmitInheritedConstructorNote(S, Fn);
6826 return;
6827 }
6828
Douglas Gregor028ea4b2011-04-26 23:16:46 +00006829 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
6830 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
6831 << (unsigned) FnKind << FnDesc
6832 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6833 << FromTy
6834 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
6835 << (unsigned) isObjectArgument << I+1;
6836 MaybeEmitInheritedConstructorNote(S, Fn);
6837 return;
6838 }
6839
John McCall651f3ee2010-01-14 03:28:57 +00006840 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6841 assert(CVR && "unexpected qualifiers mismatch");
6842
6843 if (isObjectArgument) {
6844 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6845 << (unsigned) FnKind << FnDesc
6846 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6847 << FromTy << (CVR - 1);
6848 } else {
6849 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6850 << (unsigned) FnKind << FnDesc
6851 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6852 << FromTy << (CVR - 1) << I+1;
6853 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00006854 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00006855 return;
6856 }
6857
John McCall258b2032010-01-23 08:10:49 +00006858 // Diagnose references or pointers to incomplete types differently,
6859 // since it's far from impossible that the incompleteness triggered
6860 // the failure.
6861 QualType TempFromTy = FromTy.getNonReferenceType();
6862 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6863 TempFromTy = PTy->getPointeeType();
6864 if (TempFromTy->isIncompleteType()) {
6865 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6866 << (unsigned) FnKind << FnDesc
6867 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6868 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006869 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00006870 return;
6871 }
6872
Douglas Gregor85789812010-06-30 23:01:39 +00006873 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006874 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00006875 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6876 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6877 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6878 FromPtrTy->getPointeeType()) &&
6879 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6880 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006881 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00006882 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006883 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00006884 }
6885 } else if (const ObjCObjectPointerType *FromPtrTy
6886 = FromTy->getAs<ObjCObjectPointerType>()) {
6887 if (const ObjCObjectPointerType *ToPtrTy
6888 = ToTy->getAs<ObjCObjectPointerType>())
6889 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6890 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6891 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6892 FromPtrTy->getPointeeType()) &&
6893 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006894 BaseToDerivedConversion = 2;
6895 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6896 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6897 !FromTy->isIncompleteType() &&
6898 !ToRefTy->getPointeeType()->isIncompleteType() &&
6899 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6900 BaseToDerivedConversion = 3;
6901 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006902
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006903 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006904 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006905 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00006906 << (unsigned) FnKind << FnDesc
6907 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006908 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006909 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006910 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00006911 return;
6912 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006913
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00006914 if (isa<ObjCObjectPointerType>(CFromTy) &&
6915 isa<PointerType>(CToTy)) {
6916 Qualifiers FromQs = CFromTy.getQualifiers();
6917 Qualifiers ToQs = CToTy.getQualifiers();
6918 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
6919 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
6920 << (unsigned) FnKind << FnDesc
6921 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6922 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6923 MaybeEmitInheritedConstructorNote(S, Fn);
6924 return;
6925 }
6926 }
6927
Anna Zaksb89fe6b2011-07-19 19:49:12 +00006928 // Emit the generic diagnostic and, optionally, add the hints to it.
6929 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
6930 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00006931 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00006932 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
6933 << (unsigned) (Cand->Fix.Kind);
6934
6935 // If we can fix the conversion, suggest the FixIts.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006936 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksb89fe6b2011-07-19 19:49:12 +00006937 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
6938 HI != HE; ++HI)
6939 FDiag << *HI;
6940 S.Diag(Fn->getLocation(), FDiag);
6941
Sebastian Redlf677ea32011-02-05 19:23:19 +00006942 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00006943}
6944
6945void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6946 unsigned NumFormalArgs) {
6947 // TODO: treat calls to a missing default constructor as a special case
6948
6949 FunctionDecl *Fn = Cand->Function;
6950 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6951
6952 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006953
Douglas Gregor439d3c32011-05-05 00:13:13 +00006954 // With invalid overloaded operators, it's possible that we think we
6955 // have an arity mismatch when it fact it looks like we have the
6956 // right number of arguments, because only overloaded operators have
6957 // the weird behavior of overloading member and non-member functions.
6958 // Just don't report anything.
6959 if (Fn->isInvalidDecl() &&
6960 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
6961 return;
6962
John McCalladbb8f82010-01-13 09:16:55 +00006963 // at least / at most / exactly
6964 unsigned mode, modeCount;
6965 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00006966 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6967 (Cand->FailureKind == ovl_fail_bad_deduction &&
6968 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006969 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00006970 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00006971 mode = 0; // "at least"
6972 else
6973 mode = 2; // "exactly"
6974 modeCount = MinParams;
6975 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00006976 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6977 (Cand->FailureKind == ovl_fail_bad_deduction &&
6978 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00006979 if (MinParams != FnTy->getNumArgs())
6980 mode = 1; // "at most"
6981 else
6982 mode = 2; // "exactly"
6983 modeCount = FnTy->getNumArgs();
6984 }
6985
6986 std::string Description;
6987 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6988
6989 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006990 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregora18592e2010-05-08 18:13:28 +00006991 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006992 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006993}
6994
John McCall342fec42010-02-01 18:53:26 +00006995/// Diagnose a failed template-argument deduction.
6996void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6997 Expr **Args, unsigned NumArgs) {
6998 FunctionDecl *Fn = Cand->Function; // pattern
6999
Douglas Gregora9333192010-05-08 17:41:32 +00007000 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00007001 NamedDecl *ParamD;
7002 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7003 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7004 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00007005 switch (Cand->DeductionFailure.Result) {
7006 case Sema::TDK_Success:
7007 llvm_unreachable("TDK_success while diagnosing bad deduction");
7008
7009 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00007010 assert(ParamD && "no parameter found for incomplete deduction result");
7011 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7012 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007013 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00007014 return;
7015 }
7016
John McCall57e97782010-08-05 09:05:08 +00007017 case Sema::TDK_Underqualified: {
7018 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7019 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7020
7021 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7022
7023 // Param will have been canonicalized, but it should just be a
7024 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00007025 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00007026 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00007027 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00007028 assert(S.Context.hasSameType(Param, NonCanonParam));
7029
7030 // Arg has also been canonicalized, but there's nothing we can do
7031 // about that. It also doesn't matter as much, because it won't
7032 // have any template parameters in it (because deduction isn't
7033 // done on dependent types).
7034 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7035
7036 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7037 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007038 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00007039 return;
7040 }
7041
7042 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00007043 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00007044 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00007045 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00007046 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00007047 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00007048 which = 1;
7049 else {
Douglas Gregora9333192010-05-08 17:41:32 +00007050 which = 2;
7051 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007052
Douglas Gregora9333192010-05-08 17:41:32 +00007053 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007054 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00007055 << *Cand->DeductionFailure.getFirstArg()
7056 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007057 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00007058 return;
7059 }
Douglas Gregora18592e2010-05-08 18:13:28 +00007060
Douglas Gregorf1a84452010-05-08 19:15:54 +00007061 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007062 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00007063 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007064 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00007065 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7066 << ParamD->getDeclName();
7067 else {
7068 int index = 0;
7069 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7070 index = TTP->getIndex();
7071 else if (NonTypeTemplateParmDecl *NTTP
7072 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7073 index = NTTP->getIndex();
7074 else
7075 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007076 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00007077 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7078 << (index + 1);
7079 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00007080 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00007081 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007082
Douglas Gregora18592e2010-05-08 18:13:28 +00007083 case Sema::TDK_TooManyArguments:
7084 case Sema::TDK_TooFewArguments:
7085 DiagnoseArityMismatch(S, Cand, NumArgs);
7086 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00007087
7088 case Sema::TDK_InstantiationDepth:
7089 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007090 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00007091 return;
7092
7093 case Sema::TDK_SubstitutionFailure: {
7094 std::string ArgString;
7095 if (TemplateArgumentList *Args
7096 = Cand->DeductionFailure.getTemplateArgumentList())
7097 ArgString = S.getTemplateArgumentBindingsText(
7098 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7099 *Args);
7100 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7101 << ArgString;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007102 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00007103 return;
7104 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007105
John McCall342fec42010-02-01 18:53:26 +00007106 // TODO: diagnose these individually, then kill off
7107 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00007108 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00007109 case Sema::TDK_FailedOverloadResolution:
7110 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007111 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00007112 return;
7113 }
7114}
7115
7116/// Generates a 'note' diagnostic for an overload candidate. We've
7117/// already generated a primary error at the call site.
7118///
7119/// It really does need to be a single diagnostic with its caret
7120/// pointed at the candidate declaration. Yes, this creates some
7121/// major challenges of technical writing. Yes, this makes pointing
7122/// out problems with specific arguments quite awkward. It's still
7123/// better than generating twenty screens of text for every failed
7124/// overload.
7125///
7126/// It would be great to be able to express per-candidate problems
7127/// more richly for those diagnostic clients that cared, but we'd
7128/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00007129void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7130 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00007131 FunctionDecl *Fn = Cand->Function;
7132
John McCall81201622010-01-08 04:41:39 +00007133 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007134 if (Cand->Viable && (Fn->isDeleted() ||
7135 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00007136 std::string FnDesc;
7137 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00007138
7139 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00007140 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007141 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00007142 return;
John McCall81201622010-01-08 04:41:39 +00007143 }
7144
John McCall220ccbf2010-01-13 00:25:19 +00007145 // We don't really have anything else to say about viable candidates.
7146 if (Cand->Viable) {
7147 S.NoteOverloadCandidate(Fn);
7148 return;
7149 }
John McCall1d318332010-01-12 00:44:57 +00007150
John McCalladbb8f82010-01-13 09:16:55 +00007151 switch (Cand->FailureKind) {
7152 case ovl_fail_too_many_arguments:
7153 case ovl_fail_too_few_arguments:
7154 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00007155
John McCalladbb8f82010-01-13 09:16:55 +00007156 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00007157 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7158
John McCall717e8912010-01-23 05:17:32 +00007159 case ovl_fail_trivial_conversion:
7160 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00007161 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00007162 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00007163
John McCallb1bdc622010-02-25 01:37:24 +00007164 case ovl_fail_bad_conversion: {
7165 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7166 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00007167 if (Cand->Conversions[I].isBad())
7168 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007169
John McCalladbb8f82010-01-13 09:16:55 +00007170 // FIXME: this currently happens when we're called from SemaInit
7171 // when user-conversion overload fails. Figure out how to handle
7172 // those conditions and diagnose them well.
7173 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00007174 }
John McCallb1bdc622010-02-25 01:37:24 +00007175 }
John McCalla1d7d622010-01-08 00:58:21 +00007176}
7177
7178void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7179 // Desugar the type of the surrogate down to a function type,
7180 // retaining as many typedefs as possible while still showing
7181 // the function type (and, therefore, its parameter types).
7182 QualType FnType = Cand->Surrogate->getConversionType();
7183 bool isLValueReference = false;
7184 bool isRValueReference = false;
7185 bool isPointer = false;
7186 if (const LValueReferenceType *FnTypeRef =
7187 FnType->getAs<LValueReferenceType>()) {
7188 FnType = FnTypeRef->getPointeeType();
7189 isLValueReference = true;
7190 } else if (const RValueReferenceType *FnTypeRef =
7191 FnType->getAs<RValueReferenceType>()) {
7192 FnType = FnTypeRef->getPointeeType();
7193 isRValueReference = true;
7194 }
7195 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7196 FnType = FnTypePtr->getPointeeType();
7197 isPointer = true;
7198 }
7199 // Desugar down to a function type.
7200 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7201 // Reconstruct the pointer/reference as appropriate.
7202 if (isPointer) FnType = S.Context.getPointerType(FnType);
7203 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7204 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7205
7206 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7207 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007208 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00007209}
7210
7211void NoteBuiltinOperatorCandidate(Sema &S,
7212 const char *Opc,
7213 SourceLocation OpLoc,
7214 OverloadCandidate *Cand) {
7215 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7216 std::string TypeStr("operator");
7217 TypeStr += Opc;
7218 TypeStr += "(";
7219 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7220 if (Cand->Conversions.size() == 1) {
7221 TypeStr += ")";
7222 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7223 } else {
7224 TypeStr += ", ";
7225 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7226 TypeStr += ")";
7227 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7228 }
7229}
7230
7231void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7232 OverloadCandidate *Cand) {
7233 unsigned NoOperands = Cand->Conversions.size();
7234 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7235 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00007236 if (ICS.isBad()) break; // all meaningless after first invalid
7237 if (!ICS.isAmbiguous()) continue;
7238
John McCall120d63c2010-08-24 20:38:10 +00007239 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007240 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00007241 }
7242}
7243
John McCall1b77e732010-01-15 23:32:50 +00007244SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7245 if (Cand->Function)
7246 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00007247 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00007248 return Cand->Surrogate->getLocation();
7249 return SourceLocation();
7250}
7251
John McCallbf65c0b2010-01-12 00:48:53 +00007252struct CompareOverloadCandidatesForDisplay {
7253 Sema &S;
7254 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00007255
7256 bool operator()(const OverloadCandidate *L,
7257 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00007258 // Fast-path this check.
7259 if (L == R) return false;
7260
John McCall81201622010-01-08 04:41:39 +00007261 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00007262 if (L->Viable) {
7263 if (!R->Viable) return true;
7264
7265 // TODO: introduce a tri-valued comparison for overload
7266 // candidates. Would be more worthwhile if we had a sort
7267 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00007268 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7269 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00007270 } else if (R->Viable)
7271 return false;
John McCall81201622010-01-08 04:41:39 +00007272
John McCall1b77e732010-01-15 23:32:50 +00007273 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00007274
John McCall1b77e732010-01-15 23:32:50 +00007275 // Criteria by which we can sort non-viable candidates:
7276 if (!L->Viable) {
7277 // 1. Arity mismatches come after other candidates.
7278 if (L->FailureKind == ovl_fail_too_many_arguments ||
7279 L->FailureKind == ovl_fail_too_few_arguments)
7280 return false;
7281 if (R->FailureKind == ovl_fail_too_many_arguments ||
7282 R->FailureKind == ovl_fail_too_few_arguments)
7283 return true;
John McCall81201622010-01-08 04:41:39 +00007284
John McCall717e8912010-01-23 05:17:32 +00007285 // 2. Bad conversions come first and are ordered by the number
7286 // of bad conversions and quality of good conversions.
7287 if (L->FailureKind == ovl_fail_bad_conversion) {
7288 if (R->FailureKind != ovl_fail_bad_conversion)
7289 return true;
7290
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007291 // The conversion that can be fixed with a smaller number of changes,
7292 // comes first.
7293 unsigned numLFixes = L->Fix.NumConversionsFixed;
7294 unsigned numRFixes = R->Fix.NumConversionsFixed;
7295 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7296 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00007297 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007298 if (numLFixes < numRFixes)
7299 return true;
7300 else
7301 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00007302 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007303
John McCall717e8912010-01-23 05:17:32 +00007304 // If there's any ordering between the defined conversions...
7305 // FIXME: this might not be transitive.
7306 assert(L->Conversions.size() == R->Conversions.size());
7307
7308 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00007309 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7310 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00007311 switch (CompareImplicitConversionSequences(S,
7312 L->Conversions[I],
7313 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00007314 case ImplicitConversionSequence::Better:
7315 leftBetter++;
7316 break;
7317
7318 case ImplicitConversionSequence::Worse:
7319 leftBetter--;
7320 break;
7321
7322 case ImplicitConversionSequence::Indistinguishable:
7323 break;
7324 }
7325 }
7326 if (leftBetter > 0) return true;
7327 if (leftBetter < 0) return false;
7328
7329 } else if (R->FailureKind == ovl_fail_bad_conversion)
7330 return false;
7331
John McCall1b77e732010-01-15 23:32:50 +00007332 // TODO: others?
7333 }
7334
7335 // Sort everything else by location.
7336 SourceLocation LLoc = GetLocationForCandidate(L);
7337 SourceLocation RLoc = GetLocationForCandidate(R);
7338
7339 // Put candidates without locations (e.g. builtins) at the end.
7340 if (LLoc.isInvalid()) return false;
7341 if (RLoc.isInvalid()) return true;
7342
7343 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00007344 }
7345};
7346
John McCall717e8912010-01-23 05:17:32 +00007347/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007348/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00007349void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7350 Expr **Args, unsigned NumArgs) {
7351 assert(!Cand->Viable);
7352
7353 // Don't do anything on failures other than bad conversion.
7354 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7355
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007356 // We only want the FixIts if all the arguments can be corrected.
7357 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00007358 // Use a implicit copy initialization to check conversion fixes.
7359 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007360
John McCall717e8912010-01-23 05:17:32 +00007361 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00007362 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00007363 unsigned ConvCount = Cand->Conversions.size();
7364 while (true) {
7365 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7366 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007367 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00007368 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00007369 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007370 }
John McCall717e8912010-01-23 05:17:32 +00007371 }
7372
7373 if (ConvIdx == ConvCount)
7374 return;
7375
John McCallb1bdc622010-02-25 01:37:24 +00007376 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7377 "remaining conversion is initialized?");
7378
Douglas Gregor23ef6c02010-04-16 17:45:54 +00007379 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00007380 // operation somehow.
7381 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00007382
7383 const FunctionProtoType* Proto;
7384 unsigned ArgIdx = ConvIdx;
7385
7386 if (Cand->IsSurrogate) {
7387 QualType ConvType
7388 = Cand->Surrogate->getConversionType().getNonReferenceType();
7389 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7390 ConvType = ConvPtrType->getPointeeType();
7391 Proto = ConvType->getAs<FunctionProtoType>();
7392 ArgIdx--;
7393 } else if (Cand->Function) {
7394 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7395 if (isa<CXXMethodDecl>(Cand->Function) &&
7396 !isa<CXXConstructorDecl>(Cand->Function))
7397 ArgIdx--;
7398 } else {
7399 // Builtin binary operator with a bad first conversion.
7400 assert(ConvCount <= 3);
7401 for (; ConvIdx != ConvCount; ++ConvIdx)
7402 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00007403 = TryCopyInitialization(S, Args[ConvIdx],
7404 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007405 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00007406 /*InOverloadResolution*/ true,
7407 /*AllowObjCWritebackConversion=*/
7408 S.getLangOptions().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00007409 return;
7410 }
7411
7412 // Fill in the rest of the conversions.
7413 unsigned NumArgsInProto = Proto->getNumArgs();
7414 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007415 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00007416 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00007417 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007418 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00007419 /*InOverloadResolution=*/true,
7420 /*AllowObjCWritebackConversion=*/
7421 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007422 // Store the FixIt in the candidate if it exists.
7423 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00007424 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007425 }
John McCall717e8912010-01-23 05:17:32 +00007426 else
7427 Cand->Conversions[ConvIdx].setEllipsis();
7428 }
7429}
7430
John McCalla1d7d622010-01-08 00:58:21 +00007431} // end anonymous namespace
7432
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007433/// PrintOverloadCandidates - When overload resolution fails, prints
7434/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00007435/// set.
John McCall120d63c2010-08-24 20:38:10 +00007436void OverloadCandidateSet::NoteCandidates(Sema &S,
7437 OverloadCandidateDisplayKind OCD,
7438 Expr **Args, unsigned NumArgs,
7439 const char *Opc,
7440 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00007441 // Sort the candidates by viability and position. Sorting directly would
7442 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007443 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00007444 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7445 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00007446 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00007447 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00007448 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00007449 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007450 if (Cand->Function || Cand->IsSurrogate)
7451 Cands.push_back(Cand);
7452 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7453 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00007454 }
7455 }
7456
John McCallbf65c0b2010-01-12 00:48:53 +00007457 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00007458 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007459
John McCall1d318332010-01-12 00:44:57 +00007460 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00007461
Chris Lattner5f9e2722011-07-23 10:55:15 +00007462 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall120d63c2010-08-24 20:38:10 +00007463 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007464 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00007465 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7466 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00007467
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007468 // Set an arbitrary limit on the number of candidate functions we'll spam
7469 // the user with. FIXME: This limit should depend on details of the
7470 // candidate list.
7471 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
7472 break;
7473 }
7474 ++CandsShown;
7475
John McCalla1d7d622010-01-08 00:58:21 +00007476 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00007477 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00007478 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00007479 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007480 else {
7481 assert(Cand->Viable &&
7482 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00007483 // Generally we only see ambiguities including viable builtin
7484 // operators if overload resolution got screwed up by an
7485 // ambiguous user-defined conversion.
7486 //
7487 // FIXME: It's quite possible for different conversions to see
7488 // different ambiguities, though.
7489 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00007490 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00007491 ReportedAmbiguousConversions = true;
7492 }
John McCalla1d7d622010-01-08 00:58:21 +00007493
John McCall1d318332010-01-12 00:44:57 +00007494 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00007495 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007496 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007497 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007498
7499 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00007500 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007501}
7502
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007503// [PossiblyAFunctionType] --> [Return]
7504// NonFunctionType --> NonFunctionType
7505// R (A) --> R(A)
7506// R (*)(A) --> R (A)
7507// R (&)(A) --> R (A)
7508// R (S::*)(A) --> R (A)
7509QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7510 QualType Ret = PossiblyAFunctionType;
7511 if (const PointerType *ToTypePtr =
7512 PossiblyAFunctionType->getAs<PointerType>())
7513 Ret = ToTypePtr->getPointeeType();
7514 else if (const ReferenceType *ToTypeRef =
7515 PossiblyAFunctionType->getAs<ReferenceType>())
7516 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00007517 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007518 PossiblyAFunctionType->getAs<MemberPointerType>())
7519 Ret = MemTypePtr->getPointeeType();
7520 Ret =
7521 Context.getCanonicalType(Ret).getUnqualifiedType();
7522 return Ret;
7523}
Douglas Gregor904eed32008-11-10 20:40:00 +00007524
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007525// A helper class to help with address of function resolution
7526// - allows us to avoid passing around all those ugly parameters
7527class AddressOfFunctionResolver
7528{
7529 Sema& S;
7530 Expr* SourceExpr;
7531 const QualType& TargetType;
7532 QualType TargetFunctionType; // Extracted function type from target type
7533
7534 bool Complain;
7535 //DeclAccessPair& ResultFunctionAccessPair;
7536 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007537
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007538 bool TargetTypeIsNonStaticMemberFunction;
7539 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007540
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007541 OverloadExpr::FindResult OvlExprInfo;
7542 OverloadExpr *OvlExpr;
7543 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007544 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007545
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007546public:
7547 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7548 const QualType& TargetType, bool Complain)
7549 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7550 Complain(Complain), Context(S.getASTContext()),
7551 TargetTypeIsNonStaticMemberFunction(
7552 !!TargetType->getAs<MemberPointerType>()),
7553 FoundNonTemplateFunction(false),
7554 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7555 OvlExpr(OvlExprInfo.Expression)
7556 {
7557 ExtractUnqualifiedFunctionTypeFromTargetType();
7558
7559 if (!TargetFunctionType->isFunctionType()) {
7560 if (OvlExpr->hasExplicitTemplateArgs()) {
7561 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00007562 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007563 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00007564
7565 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7566 if (!Method->isStatic()) {
7567 // If the target type is a non-function type and the function
7568 // found is a non-static member function, pretend as if that was
7569 // the target, it's the only possible type to end up with.
7570 TargetTypeIsNonStaticMemberFunction = true;
7571
7572 // And skip adding the function if its not in the proper form.
7573 // We'll diagnose this due to an empty set of functions.
7574 if (!OvlExprInfo.HasFormOfMemberPointer)
7575 return;
7576 }
7577 }
7578
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007579 Matches.push_back(std::make_pair(dap,Fn));
7580 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00007581 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007582 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00007583 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007584
7585 if (OvlExpr->hasExplicitTemplateArgs())
7586 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00007587
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007588 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7589 // C++ [over.over]p4:
7590 // If more than one function is selected, [...]
7591 if (Matches.size() > 1) {
7592 if (FoundNonTemplateFunction)
7593 EliminateAllTemplateMatches();
7594 else
7595 EliminateAllExceptMostSpecializedTemplate();
7596 }
7597 }
7598 }
7599
7600private:
7601 bool isTargetTypeAFunction() const {
7602 return TargetFunctionType->isFunctionType();
7603 }
7604
7605 // [ToType] [Return]
7606
7607 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7608 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7609 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7610 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7611 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7612 }
7613
7614 // return true if any matching specializations were found
7615 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7616 const DeclAccessPair& CurAccessFunPair) {
7617 if (CXXMethodDecl *Method
7618 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7619 // Skip non-static function templates when converting to pointer, and
7620 // static when converting to member pointer.
7621 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7622 return false;
7623 }
7624 else if (TargetTypeIsNonStaticMemberFunction)
7625 return false;
7626
7627 // C++ [over.over]p2:
7628 // If the name is a function template, template argument deduction is
7629 // done (14.8.2.2), and if the argument deduction succeeds, the
7630 // resulting template argument list is used to generate a single
7631 // function template specialization, which is added to the set of
7632 // overloaded functions considered.
7633 FunctionDecl *Specialization = 0;
7634 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7635 if (Sema::TemplateDeductionResult Result
7636 = S.DeduceTemplateArguments(FunctionTemplate,
7637 &OvlExplicitTemplateArgs,
7638 TargetFunctionType, Specialization,
7639 Info)) {
7640 // FIXME: make a note of the failed deduction for diagnostics.
7641 (void)Result;
7642 return false;
7643 }
7644
7645 // Template argument deduction ensures that we have an exact match.
7646 // This function template specicalization works.
7647 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7648 assert(TargetFunctionType
7649 == Context.getCanonicalType(Specialization->getType()));
7650 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7651 return true;
7652 }
7653
7654 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7655 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00007656 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00007657 // Skip non-static functions when converting to pointer, and static
7658 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007659 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7660 return false;
7661 }
7662 else if (TargetTypeIsNonStaticMemberFunction)
7663 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00007664
Chandler Carruthbd647292009-12-29 06:17:27 +00007665 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00007666 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007667 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7668 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00007669 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
7670 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007671 Matches.push_back(std::make_pair(CurAccessFunPair,
7672 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00007673 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007674 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00007675 }
Mike Stump1eb44332009-09-09 15:08:12 +00007676 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007677
7678 return false;
7679 }
7680
7681 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7682 bool Ret = false;
7683
7684 // If the overload expression doesn't have the form of a pointer to
7685 // member, don't try to convert it to a pointer-to-member type.
7686 if (IsInvalidFormOfPointerToMemberFunction())
7687 return false;
7688
7689 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7690 E = OvlExpr->decls_end();
7691 I != E; ++I) {
7692 // Look through any using declarations to find the underlying function.
7693 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7694
7695 // C++ [over.over]p3:
7696 // Non-member functions and static member functions match
7697 // targets of type "pointer-to-function" or "reference-to-function."
7698 // Nonstatic member functions match targets of
7699 // type "pointer-to-member-function."
7700 // Note that according to DR 247, the containing class does not matter.
7701 if (FunctionTemplateDecl *FunctionTemplate
7702 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7703 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7704 Ret = true;
7705 }
7706 // If we have explicit template arguments supplied, skip non-templates.
7707 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7708 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7709 Ret = true;
7710 }
7711 assert(Ret || Matches.empty());
7712 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00007713 }
7714
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007715 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007716 // [...] and any given function template specialization F1 is
7717 // eliminated if the set contains a second function template
7718 // specialization whose function template is more specialized
7719 // than the function template of F1 according to the partial
7720 // ordering rules of 14.5.5.2.
7721
7722 // The algorithm specified above is quadratic. We instead use a
7723 // two-pass algorithm (similar to the one used to identify the
7724 // best viable function in an overload set) that identifies the
7725 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00007726
7727 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7728 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7729 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007730
John McCallc373d482010-01-27 01:50:18 +00007731 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007732 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7733 TPOC_Other, 0, SourceExpr->getLocStart(),
7734 S.PDiag(),
7735 S.PDiag(diag::err_addr_ovl_ambiguous)
7736 << Matches[0].second->getDeclName(),
7737 S.PDiag(diag::note_ovl_candidate)
7738 << (unsigned) oc_function_template,
7739 Complain);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007740
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007741 if (Result != MatchesCopy.end()) {
7742 // Make it the first and only element
7743 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7744 Matches[0].second = cast<FunctionDecl>(*Result);
7745 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00007746 }
7747 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007748
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007749 void EliminateAllTemplateMatches() {
7750 // [...] any function template specializations in the set are
7751 // eliminated if the set also contains a non-template function, [...]
7752 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7753 if (Matches[I].second->getPrimaryTemplate() == 0)
7754 ++I;
7755 else {
7756 Matches[I] = Matches[--N];
7757 Matches.set_size(N);
7758 }
7759 }
7760 }
7761
7762public:
7763 void ComplainNoMatchesFound() const {
7764 assert(Matches.empty());
7765 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7766 << OvlExpr->getName() << TargetFunctionType
7767 << OvlExpr->getSourceRange();
7768 S.NoteAllOverloadCandidates(OvlExpr);
7769 }
7770
7771 bool IsInvalidFormOfPointerToMemberFunction() const {
7772 return TargetTypeIsNonStaticMemberFunction &&
7773 !OvlExprInfo.HasFormOfMemberPointer;
7774 }
7775
7776 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7777 // TODO: Should we condition this on whether any functions might
7778 // have matched, or is it more appropriate to do that in callers?
7779 // TODO: a fixit wouldn't hurt.
7780 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7781 << TargetType << OvlExpr->getSourceRange();
7782 }
7783
7784 void ComplainOfInvalidConversion() const {
7785 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7786 << OvlExpr->getName() << TargetType;
7787 }
7788
7789 void ComplainMultipleMatchesFound() const {
7790 assert(Matches.size() > 1);
7791 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7792 << OvlExpr->getName()
7793 << OvlExpr->getSourceRange();
7794 S.NoteAllOverloadCandidates(OvlExpr);
7795 }
7796
7797 int getNumMatches() const { return Matches.size(); }
7798
7799 FunctionDecl* getMatchingFunctionDecl() const {
7800 if (Matches.size() != 1) return 0;
7801 return Matches[0].second;
7802 }
7803
7804 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7805 if (Matches.size() != 1) return 0;
7806 return &Matches[0].first;
7807 }
7808};
7809
7810/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7811/// an overloaded function (C++ [over.over]), where @p From is an
7812/// expression with overloaded function type and @p ToType is the type
7813/// we're trying to resolve to. For example:
7814///
7815/// @code
7816/// int f(double);
7817/// int f(int);
7818///
7819/// int (*pfd)(double) = f; // selects f(double)
7820/// @endcode
7821///
7822/// This routine returns the resulting FunctionDecl if it could be
7823/// resolved, and NULL otherwise. When @p Complain is true, this
7824/// routine will emit diagnostics if there is an error.
7825FunctionDecl *
7826Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7827 bool Complain,
7828 DeclAccessPair &FoundResult) {
7829
7830 assert(AddressOfExpr->getType() == Context.OverloadTy);
7831
7832 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7833 int NumMatches = Resolver.getNumMatches();
7834 FunctionDecl* Fn = 0;
7835 if ( NumMatches == 0 && Complain) {
7836 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7837 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7838 else
7839 Resolver.ComplainNoMatchesFound();
7840 }
7841 else if (NumMatches > 1 && Complain)
7842 Resolver.ComplainMultipleMatchesFound();
7843 else if (NumMatches == 1) {
7844 Fn = Resolver.getMatchingFunctionDecl();
7845 assert(Fn);
7846 FoundResult = *Resolver.getMatchingFunctionAccessPair();
7847 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00007848 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007849 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00007850 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007851
7852 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00007853}
7854
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007855/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00007856/// resolve that overloaded function expression down to a single function.
7857///
7858/// This routine can only resolve template-ids that refer to a single function
7859/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007860/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00007861/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00007862FunctionDecl *
7863Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
7864 bool Complain,
7865 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00007866 // C++ [over.over]p1:
7867 // [...] [Note: any redundant set of parentheses surrounding the
7868 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00007869 // C++ [over.over]p1:
7870 // [...] The overloaded function name can be preceded by the &
7871 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007872
Douglas Gregor4b52e252009-12-21 23:17:24 +00007873 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00007874 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00007875 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00007876
7877 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00007878 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007879
Douglas Gregor4b52e252009-12-21 23:17:24 +00007880 // Look through all of the overloaded functions, searching for one
7881 // whose type matches exactly.
7882 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00007883 for (UnresolvedSetIterator I = ovl->decls_begin(),
7884 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00007885 // C++0x [temp.arg.explicit]p3:
7886 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007887 // where deduction is not done, if a template argument list is
7888 // specified and it, along with any default template arguments,
7889 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00007890 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00007891 FunctionTemplateDecl *FunctionTemplate
7892 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007893
Douglas Gregor4b52e252009-12-21 23:17:24 +00007894 // C++ [over.over]p2:
7895 // If the name is a function template, template argument deduction is
7896 // done (14.8.2.2), and if the argument deduction succeeds, the
7897 // resulting template argument list is used to generate a single
7898 // function template specialization, which is added to the set of
7899 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00007900 FunctionDecl *Specialization = 0;
John McCall864c0412011-04-26 20:42:42 +00007901 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00007902 if (TemplateDeductionResult Result
7903 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7904 Specialization, Info)) {
7905 // FIXME: make a note of the failed deduction for diagnostics.
7906 (void)Result;
7907 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007908 }
7909
John McCall864c0412011-04-26 20:42:42 +00007910 assert(Specialization && "no specialization and no error?");
7911
Douglas Gregor4b52e252009-12-21 23:17:24 +00007912 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007913 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007914 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00007915 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
7916 << ovl->getName();
7917 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007918 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00007919 return 0;
John McCall864c0412011-04-26 20:42:42 +00007920 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007921
John McCall864c0412011-04-26 20:42:42 +00007922 Matched = Specialization;
7923 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00007924 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007925
Douglas Gregor4b52e252009-12-21 23:17:24 +00007926 return Matched;
7927}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007928
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007929
7930
7931
7932// Resolve and fix an overloaded expression that
7933// can be resolved because it identifies a single function
7934// template specialization
7935// Last three arguments should only be supplied if Complain = true
7936ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
John McCall864c0412011-04-26 20:42:42 +00007937 Expr *SrcExpr, bool doFunctionPointerConverion, bool complain,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007938 const SourceRange& OpRangeForComplaining,
7939 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00007940 unsigned DiagIDForComplaining) {
7941 assert(SrcExpr->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007942
John McCall864c0412011-04-26 20:42:42 +00007943 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007944
John McCall864c0412011-04-26 20:42:42 +00007945 DeclAccessPair found;
7946 ExprResult SingleFunctionExpression;
7947 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
7948 ovl.Expression, /*complain*/ false, &found)) {
7949 if (DiagnoseUseOfDecl(fn, SrcExpr->getSourceRange().getBegin()))
7950 return ExprError();
7951
7952 // It is only correct to resolve to an instance method if we're
7953 // resolving a form that's permitted to be a pointer to member.
7954 // Otherwise we'll end up making a bound member expression, which
7955 // is illegal in all the contexts we resolve like this.
7956 if (!ovl.HasFormOfMemberPointer &&
7957 isa<CXXMethodDecl>(fn) &&
7958 cast<CXXMethodDecl>(fn)->isInstance()) {
7959 if (complain) {
7960 Diag(ovl.Expression->getExprLoc(),
7961 diag::err_invalid_use_of_bound_member_func)
7962 << ovl.Expression->getSourceRange();
7963 // TODO: I believe we only end up here if there's a mix of
7964 // static and non-static candidates (otherwise the expression
7965 // would have 'bound member' type, not 'overload' type).
7966 // Ideally we would note which candidate was chosen and why
7967 // the static candidates were rejected.
7968 }
7969
Douglas Gregordb2eae62011-03-16 19:16:25 +00007970 return ExprError();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007971 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00007972
John McCall864c0412011-04-26 20:42:42 +00007973 // Fix the expresion to refer to 'fn'.
7974 SingleFunctionExpression =
7975 Owned(FixOverloadedFunctionReference(SrcExpr, found, fn));
7976
7977 // If desired, do function-to-pointer decay.
7978 if (doFunctionPointerConverion)
7979 SingleFunctionExpression =
7980 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
7981 }
7982
7983 if (!SingleFunctionExpression.isUsable()) {
7984 if (complain) {
7985 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
7986 << ovl.Expression->getName()
7987 << DestTypeForComplaining
7988 << OpRangeForComplaining
7989 << ovl.Expression->getQualifierLoc().getSourceRange();
7990 NoteAllOverloadCandidates(SrcExpr);
7991 }
7992 return ExprError();
7993 }
7994
7995 return SingleFunctionExpression;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007996}
7997
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007998/// \brief Add a single candidate to the overload set.
7999static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00008000 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00008001 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008002 Expr **Args, unsigned NumArgs,
8003 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00008004 bool PartialOverloading,
8005 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00008006 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00008007 if (isa<UsingShadowDecl>(Callee))
8008 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8009
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008010 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00008011 if (ExplicitTemplateArgs) {
8012 assert(!KnownValid && "Explicit template arguments?");
8013 return;
8014 }
John McCall9aa472c2010-03-19 07:35:19 +00008015 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00008016 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008017 return;
John McCallba135432009-11-21 08:51:07 +00008018 }
8019
8020 if (FunctionTemplateDecl *FuncTemplate
8021 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00008022 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8023 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00008024 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00008025 return;
8026 }
8027
Richard Smith2ced0442011-06-26 22:19:54 +00008028 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008029}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008030
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008031/// \brief Add the overload candidates named by callee and/or found by argument
8032/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00008033void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008034 Expr **Args, unsigned NumArgs,
8035 OverloadCandidateSet &CandidateSet,
8036 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00008037
8038#ifndef NDEBUG
8039 // Verify that ArgumentDependentLookup is consistent with the rules
8040 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008041 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008042 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8043 // and let Y be the lookup set produced by argument dependent
8044 // lookup (defined as follows). If X contains
8045 //
8046 // -- a declaration of a class member, or
8047 //
8048 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00008049 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008050 //
8051 // -- a declaration that is neither a function or a function
8052 // template
8053 //
8054 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00008055
John McCall3b4294e2009-12-16 12:17:52 +00008056 if (ULE->requiresADL()) {
8057 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8058 E = ULE->decls_end(); I != E; ++I) {
8059 assert(!(*I)->getDeclContext()->isRecord());
8060 assert(isa<UsingShadowDecl>(*I) ||
8061 !(*I)->getDeclContext()->isFunctionOrMethod());
8062 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00008063 }
8064 }
8065#endif
8066
John McCall3b4294e2009-12-16 12:17:52 +00008067 // It would be nice to avoid this copy.
8068 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00008069 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00008070 if (ULE->hasExplicitTemplateArgs()) {
8071 ULE->copyTemplateArgumentsInto(TABuffer);
8072 ExplicitTemplateArgs = &TABuffer;
8073 }
8074
8075 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8076 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00008077 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008078 Args, NumArgs, CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00008079 PartialOverloading, /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00008080
John McCall3b4294e2009-12-16 12:17:52 +00008081 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00008082 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8083 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008084 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008085 CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00008086 PartialOverloading,
8087 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008088}
John McCall578b69b2009-12-16 08:11:27 +00008089
Richard Smithf50e88a2011-06-05 22:42:48 +00008090/// Attempt to recover from an ill-formed use of a non-dependent name in a
8091/// template, where the non-dependent name was declared after the template
8092/// was defined. This is common in code written for a compilers which do not
8093/// correctly implement two-stage name lookup.
8094///
8095/// Returns true if a viable candidate was found and a diagnostic was issued.
8096static bool
8097DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8098 const CXXScopeSpec &SS, LookupResult &R,
8099 TemplateArgumentListInfo *ExplicitTemplateArgs,
8100 Expr **Args, unsigned NumArgs) {
8101 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8102 return false;
8103
8104 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8105 SemaRef.LookupQualifiedName(R, DC);
8106
8107 if (!R.empty()) {
8108 R.suppressDiagnostics();
8109
8110 if (isa<CXXRecordDecl>(DC)) {
8111 // Don't diagnose names we find in classes; we get much better
8112 // diagnostics for these from DiagnoseEmptyLookup.
8113 R.clear();
8114 return false;
8115 }
8116
8117 OverloadCandidateSet Candidates(FnLoc);
8118 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8119 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8120 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith2ced0442011-06-26 22:19:54 +00008121 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00008122
8123 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00008124 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008125 // No viable functions. Don't bother the user with notes for functions
8126 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00008127 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00008128 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00008129 }
Richard Smithf50e88a2011-06-05 22:42:48 +00008130
8131 // Find the namespaces where ADL would have looked, and suggest
8132 // declaring the function there instead.
8133 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8134 Sema::AssociatedClassSet AssociatedClasses;
8135 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8136 AssociatedNamespaces,
8137 AssociatedClasses);
8138 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00008139 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00008140 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008141 for (Sema::AssociatedNamespaceSet::iterator
8142 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00008143 end = AssociatedNamespaces.end(); it != end; ++it) {
8144 if (!Std->Encloses(*it))
8145 SuggestedNamespaces.insert(*it);
8146 }
Chandler Carruth45cad4a2011-06-08 10:13:17 +00008147 } else {
8148 // Lacking the 'std::' namespace, use all of the associated namespaces.
8149 SuggestedNamespaces = AssociatedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00008150 }
8151
8152 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8153 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00008154 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008155 SemaRef.Diag(Best->Function->getLocation(),
8156 diag::note_not_found_by_two_phase_lookup)
8157 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00008158 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008159 SemaRef.Diag(Best->Function->getLocation(),
8160 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00008161 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00008162 } else {
8163 // FIXME: It would be useful to list the associated namespaces here,
8164 // but the diagnostics infrastructure doesn't provide a way to produce
8165 // a localized representation of a list of items.
8166 SemaRef.Diag(Best->Function->getLocation(),
8167 diag::note_not_found_by_two_phase_lookup)
8168 << R.getLookupName() << 2;
8169 }
8170
8171 // Try to recover by calling this function.
8172 return true;
8173 }
8174
8175 R.clear();
8176 }
8177
8178 return false;
8179}
8180
8181/// Attempt to recover from ill-formed use of a non-dependent operator in a
8182/// template, where the non-dependent operator was declared after the template
8183/// was defined.
8184///
8185/// Returns true if a viable candidate was found and a diagnostic was issued.
8186static bool
8187DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8188 SourceLocation OpLoc,
8189 Expr **Args, unsigned NumArgs) {
8190 DeclarationName OpName =
8191 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8192 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8193 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8194 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8195}
8196
John McCall578b69b2009-12-16 08:11:27 +00008197/// Attempts to recover from a call where no functions were found.
8198///
8199/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00008200static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00008201BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00008202 UnresolvedLookupExpr *ULE,
8203 SourceLocation LParenLoc,
8204 Expr **Args, unsigned NumArgs,
Richard Smithf50e88a2011-06-05 22:42:48 +00008205 SourceLocation RParenLoc,
8206 bool EmptyLookup) {
John McCall578b69b2009-12-16 08:11:27 +00008207
8208 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00008209 SS.Adopt(ULE->getQualifierLoc());
John McCall578b69b2009-12-16 08:11:27 +00008210
John McCall3b4294e2009-12-16 12:17:52 +00008211 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00008212 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00008213 if (ULE->hasExplicitTemplateArgs()) {
8214 ULE->copyTemplateArgumentsInto(TABuffer);
8215 ExplicitTemplateArgs = &TABuffer;
8216 }
8217
John McCall578b69b2009-12-16 08:11:27 +00008218 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8219 Sema::LookupOrdinaryName);
Richard Smithf50e88a2011-06-05 22:42:48 +00008220 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8221 ExplicitTemplateArgs, Args, NumArgs) &&
8222 (!EmptyLookup ||
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00008223 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00008224 ExplicitTemplateArgs, Args, NumArgs)))
John McCallf312b1e2010-08-26 23:41:50 +00008225 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00008226
John McCall3b4294e2009-12-16 12:17:52 +00008227 assert(!R.empty() && "lookup results empty despite recovery");
8228
8229 // Build an implicit member call if appropriate. Just drop the
8230 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00008231 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00008232 if ((*R.begin())->isCXXClassMember())
Chandler Carruth6df868e2010-12-12 08:17:55 +00008233 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8234 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00008235 else if (ExplicitTemplateArgs)
8236 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8237 else
8238 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8239
8240 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008241 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00008242
8243 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00008244 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00008245 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00008246 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00008247 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00008248}
Douglas Gregord7a95972010-06-08 17:35:15 +00008249
Douglas Gregorf6b89692008-11-26 05:54:23 +00008250/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00008251/// (which eventually refers to the declaration Func) and the call
8252/// arguments Args/NumArgs, attempt to resolve the function call down
8253/// to a specific function. If overload resolution succeeds, returns
8254/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00008255/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00008256/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00008257ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00008258Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00008259 SourceLocation LParenLoc,
8260 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00008261 SourceLocation RParenLoc,
8262 Expr *ExecConfig) {
John McCall3b4294e2009-12-16 12:17:52 +00008263#ifndef NDEBUG
8264 if (ULE->requiresADL()) {
8265 // To do ADL, we must have found an unqualified name.
8266 assert(!ULE->getQualifier() && "qualified name with ADL");
8267
8268 // We don't perform ADL for implicit declarations of builtins.
8269 // Verify that this was correctly set up.
8270 FunctionDecl *F;
8271 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8272 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8273 F->getBuiltinID() && F->isImplicit())
8274 assert(0 && "performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008275
John McCall3b4294e2009-12-16 12:17:52 +00008276 // We don't perform ADL in C.
8277 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00008278 } else
8279 assert(!ULE->isStdAssociatedNamespace() &&
8280 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00008281#endif
8282
John McCall5769d612010-02-08 23:07:23 +00008283 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00008284
John McCall3b4294e2009-12-16 12:17:52 +00008285 // Add the functions denoted by the callee to the set of candidate
8286 // functions, including those from argument-dependent lookup.
8287 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00008288
8289 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00008290 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8291 // out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00008292 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00008293 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smithf50e88a2011-06-05 22:42:48 +00008294 RParenLoc, /*EmptyLookup=*/true);
John McCall578b69b2009-12-16 08:11:27 +00008295
Douglas Gregorf6b89692008-11-26 05:54:23 +00008296 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008297 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00008298 case OR_Success: {
8299 FunctionDecl *FDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00008300 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCall9aa472c2010-03-19 07:35:19 +00008301 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth6df868e2010-12-12 08:17:55 +00008302 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
8303 ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00008304 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00008305 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8306 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00008307 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00008308
Richard Smithf50e88a2011-06-05 22:42:48 +00008309 case OR_No_Viable_Function: {
8310 // Try to recover by looking for viable functions which the user might
8311 // have meant to call.
8312 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8313 Args, NumArgs, RParenLoc,
8314 /*EmptyLookup=*/false);
8315 if (!Recovery.isInvalid())
8316 return Recovery;
8317
Chris Lattner4330d652009-02-17 07:29:20 +00008318 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00008319 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00008320 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008321 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00008322 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00008323 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00008324
8325 case OR_Ambiguous:
8326 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00008327 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008328 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00008329 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008330
8331 case OR_Deleted:
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00008332 {
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00008333 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8334 << Best->Function->isDeleted()
8335 << ULE->getName()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00008336 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00008337 << Fn->getSourceRange();
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00008338 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8339 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008340 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00008341 }
8342
Douglas Gregorff331c12010-07-25 18:17:45 +00008343 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00008344 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00008345}
8346
John McCall6e266892010-01-26 03:27:55 +00008347static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00008348 return Functions.size() > 1 ||
8349 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8350}
8351
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008352/// \brief Create a unary operation that may resolve to an overloaded
8353/// operator.
8354///
8355/// \param OpLoc The location of the operator itself (e.g., '*').
8356///
8357/// \param OpcIn The UnaryOperator::Opcode that describes this
8358/// operator.
8359///
8360/// \param Functions The set of non-member functions that will be
8361/// considered by overload resolution. The caller needs to build this
8362/// set based on the context using, e.g.,
8363/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8364/// set should not contain any member functions; those will be added
8365/// by CreateOverloadedUnaryOp().
8366///
8367/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00008368ExprResult
John McCall6e266892010-01-26 03:27:55 +00008369Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8370 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00008371 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008372 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008373
8374 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8375 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8376 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00008377 // TODO: provide better source location info.
8378 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008379
John Wiegley429bb272011-04-08 18:41:53 +00008380 if (Input->getObjectKind() == OK_ObjCProperty) {
8381 ExprResult Result = ConvertPropertyForRValue(Input);
8382 if (Result.isInvalid())
8383 return ExprError();
8384 Input = Result.take();
8385 }
John McCall0e800c92010-12-04 08:14:53 +00008386
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008387 Expr *Args[2] = { Input, 0 };
8388 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00008389
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008390 // For post-increment and post-decrement, add the implicit '0' as
8391 // the second argument, so that we know this is a post-increment or
8392 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00008393 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008394 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008395 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8396 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008397 NumArgs = 2;
8398 }
8399
8400 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00008401 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00008402 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008403 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00008404 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008405 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00008406 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008407
John McCallc373d482010-01-27 01:50:18 +00008408 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00008409 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00008410 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00008411 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00008412 /*ADL*/ true, IsOverloaded(Fns),
8413 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008414 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor4c9be892011-02-28 20:01:57 +00008415 &Args[0], NumArgs,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008416 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008417 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008418 OpLoc));
8419 }
8420
8421 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00008422 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008423
8424 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00008425 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008426
8427 // Add operator candidates that are member functions.
8428 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8429
John McCall6e266892010-01-26 03:27:55 +00008430 // Add candidates from ADL.
8431 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00008432 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00008433 /*ExplicitTemplateArgs*/ 0,
8434 CandidateSet);
8435
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008436 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00008437 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008438
8439 // Perform overload resolution.
8440 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008441 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008442 case OR_Success: {
8443 // We found a built-in operator or an overloaded operator.
8444 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00008445
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008446 if (FnDecl) {
8447 // We matched an overloaded operator. Build a call to that
8448 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00008449
Chandler Carruth25ca4212011-02-25 19:41:05 +00008450 MarkDeclarationReferenced(OpLoc, FnDecl);
8451
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008452 // Convert the arguments.
8453 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00008454 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00008455
John Wiegley429bb272011-04-08 18:41:53 +00008456 ExprResult InputRes =
8457 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8458 Best->FoundDecl, Method);
8459 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008460 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008461 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008462 } else {
8463 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00008464 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00008465 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00008466 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00008467 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008468 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00008469 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00008470 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008471 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00008472 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008473 }
8474
John McCallb697e082010-05-06 18:15:07 +00008475 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8476
John McCallf89e55a2010-11-18 06:31:45 +00008477 // Determine the result type.
8478 QualType ResultTy = FnDecl->getResultType();
8479 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8480 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00008481
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008482 // Build the actual expression node.
John Wiegley429bb272011-04-08 18:41:53 +00008483 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl);
8484 if (FnExpr.isInvalid())
8485 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00008486
Eli Friedman4c3b8962009-11-18 03:58:17 +00008487 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00008488 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00008489 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00008490 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00008491
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008492 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00008493 FnDecl))
8494 return ExprError();
8495
John McCall9ae2f072010-08-23 23:25:46 +00008496 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008497 } else {
8498 // We matched a built-in operator. Convert the arguments, then
8499 // break out so that we will build the appropriate built-in
8500 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00008501 ExprResult InputRes =
8502 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8503 Best->Conversions[0], AA_Passing);
8504 if (InputRes.isInvalid())
8505 return ExprError();
8506 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008507 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008508 }
John Wiegley429bb272011-04-08 18:41:53 +00008509 }
8510
8511 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +00008512 // This is an erroneous use of an operator which can be overloaded by
8513 // a non-member function. Check for non-member operators which were
8514 // defined too late to be candidates.
8515 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
8516 // FIXME: Recover by calling the found function.
8517 return ExprError();
8518
John Wiegley429bb272011-04-08 18:41:53 +00008519 // No viable function; fall through to handling this as a
8520 // built-in operator, which will produce an error message for us.
8521 break;
8522
8523 case OR_Ambiguous:
8524 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8525 << UnaryOperator::getOpcodeStr(Opc)
8526 << Input->getType()
8527 << Input->getSourceRange();
8528 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
8529 Args, NumArgs,
8530 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8531 return ExprError();
8532
8533 case OR_Deleted:
8534 Diag(OpLoc, diag::err_ovl_deleted_oper)
8535 << Best->Function->isDeleted()
8536 << UnaryOperator::getOpcodeStr(Opc)
8537 << getDeletedOrUnavailableSuffix(Best->Function)
8538 << Input->getSourceRange();
8539 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8540 return ExprError();
8541 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008542
8543 // Either we found no viable overloaded operator or we matched a
8544 // built-in operator. In either case, fall through to trying to
8545 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00008546 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008547}
8548
Douglas Gregor063daf62009-03-13 18:40:31 +00008549/// \brief Create a binary operation that may resolve to an overloaded
8550/// operator.
8551///
8552/// \param OpLoc The location of the operator itself (e.g., '+').
8553///
8554/// \param OpcIn The BinaryOperator::Opcode that describes this
8555/// operator.
8556///
8557/// \param Functions The set of non-member functions that will be
8558/// considered by overload resolution. The caller needs to build this
8559/// set based on the context using, e.g.,
8560/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8561/// set should not contain any member functions; those will be added
8562/// by CreateOverloadedBinOp().
8563///
8564/// \param LHS Left-hand argument.
8565/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00008566ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00008567Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00008568 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00008569 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00008570 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00008571 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008572 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00008573
8574 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8575 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8576 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8577
8578 // If either side is type-dependent, create an appropriate dependent
8579 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008580 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00008581 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008582 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008583 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00008584 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008585 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +00008586 Context.DependentTy,
8587 VK_RValue, OK_Ordinary,
8588 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008589
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008590 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8591 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008592 VK_LValue,
8593 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008594 Context.DependentTy,
8595 Context.DependentTy,
8596 OpLoc));
8597 }
John McCall6e266892010-01-26 03:27:55 +00008598
8599 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00008600 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00008601 // TODO: provide better source location info in DNLoc component.
8602 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00008603 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +00008604 = UnresolvedLookupExpr::Create(Context, NamingClass,
8605 NestedNameSpecifierLoc(), OpNameInfo,
8606 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00008607 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00008608 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00008609 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00008610 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008611 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +00008612 OpLoc));
8613 }
8614
John McCall0e800c92010-12-04 08:14:53 +00008615 // Always do property rvalue conversions on the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00008616 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8617 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8618 if (Result.isInvalid())
8619 return ExprError();
8620 Args[1] = Result.take();
8621 }
John McCall0e800c92010-12-04 08:14:53 +00008622
8623 // The LHS is more complicated.
8624 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8625
8626 // There's a tension for assignment operators between primitive
8627 // property assignment and the overloaded operators.
8628 if (BinaryOperator::isAssignmentOp(Opc)) {
8629 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8630
8631 // Is the property "logically" settable?
8632 bool Settable = (PRE->isExplicitProperty() ||
8633 PRE->getImplicitPropertySetter());
8634
8635 // To avoid gratuitously inventing semantics, use the primitive
8636 // unless it isn't. Thoughts in case we ever really care:
8637 // - If the property isn't logically settable, we have to
8638 // load and hope.
8639 // - If the property is settable and this is simple assignment,
8640 // we really should use the primitive.
8641 // - If the property is settable, then we could try overloading
8642 // on a generic lvalue of the appropriate type; if it works
8643 // out to a builtin candidate, we would do that same operation
8644 // on the property, and otherwise just error.
8645 if (Settable)
8646 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8647 }
8648
John Wiegley429bb272011-04-08 18:41:53 +00008649 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8650 if (Result.isInvalid())
8651 return ExprError();
8652 Args[0] = Result.take();
John McCall0e800c92010-12-04 08:14:53 +00008653 }
Douglas Gregor063daf62009-03-13 18:40:31 +00008654
Sebastian Redl275c2b42009-11-18 23:10:33 +00008655 // If this is the assignment operator, we only perform overload resolution
8656 // if the left-hand side is a class or enumeration type. This is actually
8657 // a hack. The standard requires that we do overload resolution between the
8658 // various built-in candidates, but as DR507 points out, this can lead to
8659 // problems. So we do it this way, which pretty much follows what GCC does.
8660 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00008661 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008662 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00008663
John McCall0e800c92010-12-04 08:14:53 +00008664 // If this is the .* operator, which is not overloadable, just
8665 // create a built-in binary operator.
8666 if (Opc == BO_PtrMemD)
8667 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8668
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008669 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00008670 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00008671
8672 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00008673 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00008674
8675 // Add operator candidates that are member functions.
8676 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8677
John McCall6e266892010-01-26 03:27:55 +00008678 // Add candidates from ADL.
8679 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8680 Args, 2,
8681 /*ExplicitTemplateArgs*/ 0,
8682 CandidateSet);
8683
Douglas Gregor063daf62009-03-13 18:40:31 +00008684 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00008685 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00008686
8687 // Perform overload resolution.
8688 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008689 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00008690 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00008691 // We found a built-in operator or an overloaded operator.
8692 FunctionDecl *FnDecl = Best->Function;
8693
8694 if (FnDecl) {
8695 // We matched an overloaded operator. Build a call to that
8696 // operator.
8697
Chandler Carruth25ca4212011-02-25 19:41:05 +00008698 MarkDeclarationReferenced(OpLoc, FnDecl);
8699
Douglas Gregor063daf62009-03-13 18:40:31 +00008700 // Convert the arguments.
8701 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00008702 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00008703 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00008704
Chandler Carruth6df868e2010-12-12 08:17:55 +00008705 ExprResult Arg1 =
8706 PerformCopyInitialization(
8707 InitializedEntity::InitializeParameter(Context,
8708 FnDecl->getParamDecl(0)),
8709 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008710 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00008711 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008712
John Wiegley429bb272011-04-08 18:41:53 +00008713 ExprResult Arg0 =
8714 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8715 Best->FoundDecl, Method);
8716 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008717 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008718 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008719 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00008720 } else {
8721 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +00008722 ExprResult Arg0 = PerformCopyInitialization(
8723 InitializedEntity::InitializeParameter(Context,
8724 FnDecl->getParamDecl(0)),
8725 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008726 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00008727 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008728
Chandler Carruth6df868e2010-12-12 08:17:55 +00008729 ExprResult Arg1 =
8730 PerformCopyInitialization(
8731 InitializedEntity::InitializeParameter(Context,
8732 FnDecl->getParamDecl(1)),
8733 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008734 if (Arg1.isInvalid())
8735 return ExprError();
8736 Args[0] = LHS = Arg0.takeAs<Expr>();
8737 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00008738 }
8739
John McCallb697e082010-05-06 18:15:07 +00008740 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8741
John McCallf89e55a2010-11-18 06:31:45 +00008742 // Determine the result type.
8743 QualType ResultTy = FnDecl->getResultType();
8744 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8745 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00008746
8747 // Build the actual expression node.
John Wiegley429bb272011-04-08 18:41:53 +00008748 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
8749 if (FnExpr.isInvalid())
8750 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +00008751
John McCall9ae2f072010-08-23 23:25:46 +00008752 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00008753 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00008754 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008755
8756 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00008757 FnDecl))
8758 return ExprError();
8759
John McCall9ae2f072010-08-23 23:25:46 +00008760 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00008761 } else {
8762 // We matched a built-in operator. Convert the arguments, then
8763 // break out so that we will build the appropriate built-in
8764 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00008765 ExprResult ArgsRes0 =
8766 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8767 Best->Conversions[0], AA_Passing);
8768 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00008769 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008770 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00008771
John Wiegley429bb272011-04-08 18:41:53 +00008772 ExprResult ArgsRes1 =
8773 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8774 Best->Conversions[1], AA_Passing);
8775 if (ArgsRes1.isInvalid())
8776 return ExprError();
8777 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00008778 break;
8779 }
8780 }
8781
Douglas Gregor33074752009-09-30 21:46:01 +00008782 case OR_No_Viable_Function: {
8783 // C++ [over.match.oper]p9:
8784 // If the operator is the operator , [...] and there are no
8785 // viable functions, then the operator is assumed to be the
8786 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00008787 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00008788 break;
8789
Chandler Carruth6df868e2010-12-12 08:17:55 +00008790 // For class as left operand for assignment or compound assigment
8791 // operator do not fall through to handling in built-in, but report that
8792 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00008793 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008794 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00008795 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00008796 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8797 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008798 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00008799 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +00008800 // This is an erroneous use of an operator which can be overloaded by
8801 // a non-member function. Check for non-member operators which were
8802 // defined too late to be candidates.
8803 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
8804 // FIXME: Recover by calling the found function.
8805 return ExprError();
8806
Douglas Gregor33074752009-09-30 21:46:01 +00008807 // No viable function; try to create a built-in operation, which will
8808 // produce an error. Then, show the non-viable candidates.
8809 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00008810 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008811 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +00008812 "C++ binary operator overloading is missing candidates!");
8813 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00008814 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8815 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00008816 return move(Result);
8817 }
Douglas Gregor063daf62009-03-13 18:40:31 +00008818
8819 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00008820 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +00008821 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00008822 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008823 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008824 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8825 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00008826 return ExprError();
8827
8828 case OR_Deleted:
8829 Diag(OpLoc, diag::err_ovl_deleted_oper)
8830 << Best->Function->isDeleted()
8831 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00008832 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008833 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008834 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00008835 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00008836 }
Douglas Gregor063daf62009-03-13 18:40:31 +00008837
Douglas Gregor33074752009-09-30 21:46:01 +00008838 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008839 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00008840}
8841
John McCall60d7b3a2010-08-24 06:29:42 +00008842ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +00008843Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8844 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +00008845 Expr *Base, Expr *Idx) {
8846 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +00008847 DeclarationName OpName =
8848 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8849
8850 // If either side is type-dependent, create an appropriate dependent
8851 // expression.
8852 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8853
John McCallc373d482010-01-27 01:50:18 +00008854 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00008855 // CHECKME: no 'operator' keyword?
8856 DeclarationNameInfo OpNameInfo(OpName, LLoc);
8857 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00008858 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00008859 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00008860 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00008861 /*ADL*/ true, /*Overloaded*/ false,
8862 UnresolvedSetIterator(),
8863 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00008864 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00008865
Sebastian Redlf322ed62009-10-29 20:17:01 +00008866 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8867 Args, 2,
8868 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008869 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +00008870 RLoc));
8871 }
8872
John Wiegley429bb272011-04-08 18:41:53 +00008873 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8874 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8875 if (Result.isInvalid())
8876 return ExprError();
8877 Args[0] = Result.take();
8878 }
8879 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8880 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8881 if (Result.isInvalid())
8882 return ExprError();
8883 Args[1] = Result.take();
8884 }
John McCall0e800c92010-12-04 08:14:53 +00008885
Sebastian Redlf322ed62009-10-29 20:17:01 +00008886 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00008887 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008888
8889 // Subscript can only be overloaded as a member function.
8890
8891 // Add operator candidates that are member functions.
8892 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8893
8894 // Add builtin operator candidates.
8895 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8896
8897 // Perform overload resolution.
8898 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008899 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00008900 case OR_Success: {
8901 // We found a built-in operator or an overloaded operator.
8902 FunctionDecl *FnDecl = Best->Function;
8903
8904 if (FnDecl) {
8905 // We matched an overloaded operator. Build a call to that
8906 // operator.
8907
Chandler Carruth25ca4212011-02-25 19:41:05 +00008908 MarkDeclarationReferenced(LLoc, FnDecl);
8909
John McCall9aa472c2010-03-19 07:35:19 +00008910 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008911 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00008912
Sebastian Redlf322ed62009-10-29 20:17:01 +00008913 // Convert the arguments.
8914 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +00008915 ExprResult Arg0 =
8916 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8917 Best->FoundDecl, Method);
8918 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +00008919 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008920 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +00008921
Anders Carlsson38f88ab2010-01-29 18:37:50 +00008922 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00008923 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +00008924 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00008925 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +00008926 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008927 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +00008928 Owned(Args[1]));
8929 if (InputInit.isInvalid())
8930 return ExprError();
8931
8932 Args[1] = InputInit.takeAs<Expr>();
8933
Sebastian Redlf322ed62009-10-29 20:17:01 +00008934 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +00008935 QualType ResultTy = FnDecl->getResultType();
8936 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8937 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008938
8939 // Build the actual expression node.
Douglas Gregor5b8968c2011-07-15 16:25:15 +00008940 DeclarationNameLoc LocInfo;
8941 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
8942 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
8943 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc, LocInfo);
John Wiegley429bb272011-04-08 18:41:53 +00008944 if (FnExpr.isInvalid())
8945 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00008946
John McCall9ae2f072010-08-23 23:25:46 +00008947 CXXOperatorCallExpr *TheCall =
8948 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley429bb272011-04-08 18:41:53 +00008949 FnExpr.take(), Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +00008950 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008951
John McCall9ae2f072010-08-23 23:25:46 +00008952 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +00008953 FnDecl))
8954 return ExprError();
8955
John McCall9ae2f072010-08-23 23:25:46 +00008956 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +00008957 } else {
8958 // We matched a built-in operator. Convert the arguments, then
8959 // break out so that we will build the appropriate built-in
8960 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00008961 ExprResult ArgsRes0 =
8962 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8963 Best->Conversions[0], AA_Passing);
8964 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +00008965 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008966 Args[0] = ArgsRes0.take();
8967
8968 ExprResult ArgsRes1 =
8969 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8970 Best->Conversions[1], AA_Passing);
8971 if (ArgsRes1.isInvalid())
8972 return ExprError();
8973 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +00008974
8975 break;
8976 }
8977 }
8978
8979 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00008980 if (CandidateSet.empty())
8981 Diag(LLoc, diag::err_ovl_no_oper)
8982 << Args[0]->getType() << /*subscript*/ 0
8983 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8984 else
8985 Diag(LLoc, diag::err_ovl_no_viable_subscript)
8986 << Args[0]->getType()
8987 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008988 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8989 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +00008990 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00008991 }
8992
8993 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00008994 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008995 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +00008996 << Args[0]->getType() << Args[1]->getType()
8997 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008998 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8999 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009000 return ExprError();
9001
9002 case OR_Deleted:
9003 Diag(LLoc, diag::err_ovl_deleted_oper)
9004 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009005 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +00009006 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009007 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9008 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009009 return ExprError();
9010 }
9011
9012 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +00009013 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009014}
9015
Douglas Gregor88a35142008-12-22 05:46:06 +00009016/// BuildCallToMemberFunction - Build a call to a member
9017/// function. MemExpr is the expression that refers to the member
9018/// function (and includes the object parameter), Args/NumArgs are the
9019/// arguments to the function call (not including the object
9020/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +00009021/// expression refers to a non-static member function or an overloaded
9022/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +00009023ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00009024Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9025 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +00009026 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +00009027 assert(MemExprE->getType() == Context.BoundMemberTy ||
9028 MemExprE->getType() == Context.OverloadTy);
9029
Douglas Gregor88a35142008-12-22 05:46:06 +00009030 // Dig out the member expression. This holds both the object
9031 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00009032 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009033
John McCall864c0412011-04-26 20:42:42 +00009034 // Determine whether this is a call to a pointer-to-member function.
9035 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9036 assert(op->getType() == Context.BoundMemberTy);
9037 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9038
9039 QualType fnType =
9040 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9041
9042 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9043 QualType resultType = proto->getCallResultType(Context);
9044 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9045
9046 // Check that the object type isn't more qualified than the
9047 // member function we're calling.
9048 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9049
9050 QualType objectType = op->getLHS()->getType();
9051 if (op->getOpcode() == BO_PtrMemI)
9052 objectType = objectType->castAs<PointerType>()->getPointeeType();
9053 Qualifiers objectQuals = objectType.getQualifiers();
9054
9055 Qualifiers difference = objectQuals - funcQuals;
9056 difference.removeObjCGCAttr();
9057 difference.removeAddressSpace();
9058 if (difference) {
9059 std::string qualsString = difference.getAsString();
9060 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9061 << fnType.getUnqualifiedType()
9062 << qualsString
9063 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9064 }
9065
9066 CXXMemberCallExpr *call
9067 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9068 resultType, valueKind, RParenLoc);
9069
9070 if (CheckCallReturnType(proto->getResultType(),
9071 op->getRHS()->getSourceRange().getBegin(),
9072 call, 0))
9073 return ExprError();
9074
9075 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9076 return ExprError();
9077
9078 return MaybeBindToTemporary(call);
9079 }
9080
John McCall129e2df2009-11-30 22:42:35 +00009081 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00009082 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00009083 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00009084 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00009085 if (isa<MemberExpr>(NakedMemExpr)) {
9086 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00009087 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00009088 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00009089 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00009090 } else {
9091 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00009092 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009093
John McCall701c89e2009-12-03 04:06:58 +00009094 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009095 Expr::Classification ObjectClassification
9096 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9097 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +00009098
Douglas Gregor88a35142008-12-22 05:46:06 +00009099 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00009100 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00009101
John McCallaa81e162009-12-01 22:10:20 +00009102 // FIXME: avoid copy.
9103 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9104 if (UnresExpr->hasExplicitTemplateArgs()) {
9105 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9106 TemplateArgs = &TemplateArgsBuffer;
9107 }
9108
John McCall129e2df2009-11-30 22:42:35 +00009109 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9110 E = UnresExpr->decls_end(); I != E; ++I) {
9111
John McCall701c89e2009-12-03 04:06:58 +00009112 NamedDecl *Func = *I;
9113 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9114 if (isa<UsingShadowDecl>(Func))
9115 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9116
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009117
Francois Pichetdbee3412011-01-18 05:04:39 +00009118 // Microsoft supports direct constructor calls.
9119 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
9120 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9121 CandidateSet);
9122 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00009123 // If explicit template arguments were provided, we can't call a
9124 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00009125 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00009126 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009127
John McCall9aa472c2010-03-19 07:35:19 +00009128 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009129 ObjectClassification,
9130 Args, NumArgs, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009131 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00009132 } else {
John McCall129e2df2009-11-30 22:42:35 +00009133 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00009134 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009135 ObjectType, ObjectClassification,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009136 Args, NumArgs, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +00009137 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00009138 }
Douglas Gregordec06662009-08-21 18:42:58 +00009139 }
Mike Stump1eb44332009-09-09 15:08:12 +00009140
John McCall129e2df2009-11-30 22:42:35 +00009141 DeclarationName DeclName = UnresExpr->getMemberName();
9142
Douglas Gregor88a35142008-12-22 05:46:06 +00009143 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009144 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +00009145 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00009146 case OR_Success:
9147 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009148 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +00009149 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00009150 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009151 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00009152 break;
9153
9154 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00009155 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00009156 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00009157 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009158 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00009159 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00009160 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00009161
9162 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00009163 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00009164 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009165 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00009166 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00009167 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009168
9169 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00009170 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009171 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009172 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009173 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009174 << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009175 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009176 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00009177 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00009178 }
9179
John McCall6bb80172010-03-30 21:47:33 +00009180 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00009181
John McCallaa81e162009-12-01 22:10:20 +00009182 // If overload resolution picked a static member, build a
9183 // non-member call based on that function.
9184 if (Method->isStatic()) {
9185 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9186 Args, NumArgs, RParenLoc);
9187 }
9188
John McCall129e2df2009-11-30 22:42:35 +00009189 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00009190 }
9191
John McCallf89e55a2010-11-18 06:31:45 +00009192 QualType ResultType = Method->getResultType();
9193 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9194 ResultType = ResultType.getNonLValueExprType(Context);
9195
Douglas Gregor88a35142008-12-22 05:46:06 +00009196 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009197 CXXMemberCallExpr *TheCall =
John McCall9ae2f072010-08-23 23:25:46 +00009198 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +00009199 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +00009200
Anders Carlssoneed3e692009-10-10 00:06:20 +00009201 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009202 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +00009203 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +00009204 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009205
Douglas Gregor88a35142008-12-22 05:46:06 +00009206 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00009207 // We only need to do this if there was actually an overload; otherwise
9208 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +00009209 if (!Method->isStatic()) {
9210 ExprResult ObjectArg =
9211 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9212 FoundDecl, Method);
9213 if (ObjectArg.isInvalid())
9214 return ExprError();
9215 MemExpr->setBase(ObjectArg.take());
9216 }
Douglas Gregor88a35142008-12-22 05:46:06 +00009217
9218 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +00009219 const FunctionProtoType *Proto =
9220 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +00009221 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00009222 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00009223 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00009224
John McCall9ae2f072010-08-23 23:25:46 +00009225 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +00009226 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00009227
Anders Carlsson2174d4c2011-05-06 14:25:31 +00009228 if ((isa<CXXConstructorDecl>(CurContext) ||
9229 isa<CXXDestructorDecl>(CurContext)) &&
9230 TheCall->getMethodDecl()->isPure()) {
9231 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9232
Chandler Carruthae198062011-06-27 08:31:58 +00009233 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +00009234 Diag(MemExpr->getLocStart(),
9235 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9236 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9237 << MD->getParent()->getDeclName();
9238
9239 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +00009240 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +00009241 }
John McCall9ae2f072010-08-23 23:25:46 +00009242 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +00009243}
9244
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009245/// BuildCallToObjectOfClassType - Build a call to an object of class
9246/// type (C++ [over.call.object]), which can end up invoking an
9247/// overloaded function call operator (@c operator()) or performing a
9248/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +00009249ExprResult
John Wiegley429bb272011-04-08 18:41:53 +00009250Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +00009251 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009252 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009253 SourceLocation RParenLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00009254 ExprResult Object = Owned(Obj);
9255 if (Object.get()->getObjectKind() == OK_ObjCProperty) {
9256 Object = ConvertPropertyForRValue(Object.take());
9257 if (Object.isInvalid())
9258 return ExprError();
9259 }
John McCall0e800c92010-12-04 08:14:53 +00009260
John Wiegley429bb272011-04-08 18:41:53 +00009261 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9262 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00009263
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009264 // C++ [over.call.object]p1:
9265 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00009266 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009267 // candidate functions includes at least the function call
9268 // operators of T. The function call operators of T are obtained by
9269 // ordinary lookup of the name operator() in the context of
9270 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00009271 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00009272 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00009273
John Wiegley429bb272011-04-08 18:41:53 +00009274 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00009275 PDiag(diag::err_incomplete_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00009276 << Object.get()->getSourceRange()))
Douglas Gregor593564b2009-11-15 07:48:03 +00009277 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009278
John McCalla24dc2e2009-11-17 02:14:36 +00009279 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9280 LookupQualifiedName(R, Record->getDecl());
9281 R.suppressDiagnostics();
9282
Douglas Gregor593564b2009-11-15 07:48:03 +00009283 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00009284 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +00009285 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9286 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00009287 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00009288 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009289
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009290 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +00009291 // In addition, for each (non-explicit in C++0x) conversion function
9292 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009293 //
9294 // operator conversion-type-id () cv-qualifier;
9295 //
9296 // where cv-qualifier is the same cv-qualification as, or a
9297 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00009298 // denotes the type "pointer to function of (P1,...,Pn) returning
9299 // R", or the type "reference to pointer to function of
9300 // (P1,...,Pn) returning R", or the type "reference to function
9301 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009302 // is also considered as a candidate function. Similarly,
9303 // surrogate call functions are added to the set of candidate
9304 // functions for each conversion function declared in an
9305 // accessible base class provided the function is not hidden
9306 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00009307 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00009308 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00009309 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00009310 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00009311 NamedDecl *D = *I;
9312 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9313 if (isa<UsingShadowDecl>(D))
9314 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009315
Douglas Gregor4a27d702009-10-21 06:18:39 +00009316 // Skip over templated conversion functions; they aren't
9317 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00009318 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00009319 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009320
John McCall701c89e2009-12-03 04:06:58 +00009321 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +00009322 if (!Conv->isExplicit()) {
9323 // Strip the reference type (if any) and then the pointer type (if
9324 // any) to get down to what might be a function type.
9325 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9326 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9327 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +00009328
Douglas Gregorbf6e3172011-07-23 18:59:35 +00009329 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9330 {
9331 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9332 Object.get(), Args, NumArgs, CandidateSet);
9333 }
9334 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009335 }
Mike Stump1eb44332009-09-09 15:08:12 +00009336
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009337 // Perform overload resolution.
9338 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +00009339 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +00009340 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009341 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009342 // Overload resolution succeeded; we'll build the appropriate call
9343 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009344 break;
9345
9346 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00009347 if (CandidateSet.empty())
John Wiegley429bb272011-04-08 18:41:53 +00009348 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9349 << Object.get()->getType() << /*call*/ 1
9350 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +00009351 else
John Wiegley429bb272011-04-08 18:41:53 +00009352 Diag(Object.get()->getSourceRange().getBegin(),
John McCall1eb3e102010-01-07 02:04:15 +00009353 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00009354 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009355 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009356 break;
9357
9358 case OR_Ambiguous:
John Wiegley429bb272011-04-08 18:41:53 +00009359 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009360 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00009361 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009362 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009363 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009364
9365 case OR_Deleted:
John Wiegley429bb272011-04-08 18:41:53 +00009366 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009367 diag::err_ovl_deleted_object_call)
9368 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +00009369 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009370 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +00009371 << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009372 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009373 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009374 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009375
Douglas Gregorff331c12010-07-25 18:17:45 +00009376 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009377 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009378
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009379 if (Best->Function == 0) {
9380 // Since there is no function declaration, this is one of the
9381 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00009382 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009383 = cast<CXXConversionDecl>(
9384 Best->Conversions[0].UserDefined.ConversionFunction);
9385
John Wiegley429bb272011-04-08 18:41:53 +00009386 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009387 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00009388
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009389 // We selected one of the surrogate functions that converts the
9390 // object parameter to a function pointer. Perform the conversion
9391 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009392
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00009393 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00009394 // and then call it.
John Wiegley429bb272011-04-08 18:41:53 +00009395 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00009396 if (Call.isInvalid())
9397 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009398
Douglas Gregorf2ae5262011-01-20 00:18:04 +00009399 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00009400 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009401 }
9402
Chandler Carruth25ca4212011-02-25 19:41:05 +00009403 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +00009404 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009405 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00009406
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009407 // We found an overloaded operator(). Build a CXXOperatorCallExpr
9408 // that calls this method, using Object for the implicit object
9409 // parameter and passing along the remaining arguments.
9410 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +00009411 const FunctionProtoType *Proto =
9412 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009413
9414 unsigned NumArgsInProto = Proto->getNumArgs();
9415 unsigned NumArgsToCheck = NumArgs;
9416
9417 // Build the full argument list for the method call (the
9418 // implicit object parameter is placed at the beginning of the
9419 // list).
9420 Expr **MethodArgs;
9421 if (NumArgs < NumArgsInProto) {
9422 NumArgsToCheck = NumArgsInProto;
9423 MethodArgs = new Expr*[NumArgsInProto + 1];
9424 } else {
9425 MethodArgs = new Expr*[NumArgs + 1];
9426 }
John Wiegley429bb272011-04-08 18:41:53 +00009427 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009428 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9429 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00009430
John Wiegley429bb272011-04-08 18:41:53 +00009431 ExprResult NewFn = CreateFunctionRefExpr(*this, Method);
9432 if (NewFn.isInvalid())
9433 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009434
9435 // Once we've built TheCall, all of the expressions are properly
9436 // owned.
John McCallf89e55a2010-11-18 06:31:45 +00009437 QualType ResultTy = Method->getResultType();
9438 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9439 ResultTy = ResultTy.getNonLValueExprType(Context);
9440
John McCall9ae2f072010-08-23 23:25:46 +00009441 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009442 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCall9ae2f072010-08-23 23:25:46 +00009443 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +00009444 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009445 delete [] MethodArgs;
9446
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009447 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +00009448 Method))
9449 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009450
Douglas Gregor518fda12009-01-13 05:10:00 +00009451 // We may have default arguments. If so, we need to allocate more
9452 // slots in the call for them.
9453 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00009454 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00009455 else if (NumArgs > NumArgsInProto)
9456 NumArgsToCheck = NumArgsInProto;
9457
Chris Lattner312531a2009-04-12 08:11:20 +00009458 bool IsError = false;
9459
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009460 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +00009461 ExprResult ObjRes =
9462 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9463 Best->FoundDecl, Method);
9464 if (ObjRes.isInvalid())
9465 IsError = true;
9466 else
9467 Object = move(ObjRes);
9468 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +00009469
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009470 // Check the argument types.
9471 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009472 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00009473 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009474 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00009475
Douglas Gregor518fda12009-01-13 05:10:00 +00009476 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00009477
John McCall60d7b3a2010-08-24 06:29:42 +00009478 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +00009479 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009480 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +00009481 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +00009482 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009483
Anders Carlsson3faa4862010-01-29 18:43:53 +00009484 IsError |= InputInit.isInvalid();
9485 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00009486 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00009487 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +00009488 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9489 if (DefArg.isInvalid()) {
9490 IsError = true;
9491 break;
9492 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009493
Douglas Gregord47c47d2009-11-09 19:27:57 +00009494 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00009495 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009496
9497 TheCall->setArg(i + 1, Arg);
9498 }
9499
9500 // If this is a variadic call, handle args passed through "...".
9501 if (Proto->isVariadic()) {
9502 // Promote the arguments (C99 6.5.2.2p7).
9503 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +00009504 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9505 IsError |= Arg.isInvalid();
9506 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009507 }
9508 }
9509
Chris Lattner312531a2009-04-12 08:11:20 +00009510 if (IsError) return true;
9511
John McCall9ae2f072010-08-23 23:25:46 +00009512 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00009513 return true;
9514
John McCall182f7092010-08-24 06:09:16 +00009515 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009516}
9517
Douglas Gregor8ba10742008-11-20 16:27:02 +00009518/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00009519/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00009520/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +00009521ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009522Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +00009523 assert(Base->getType()->isRecordType() &&
9524 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00009525
John Wiegley429bb272011-04-08 18:41:53 +00009526 if (Base->getObjectKind() == OK_ObjCProperty) {
9527 ExprResult Result = ConvertPropertyForRValue(Base);
9528 if (Result.isInvalid())
9529 return ExprError();
9530 Base = Result.take();
9531 }
John McCall0e800c92010-12-04 08:14:53 +00009532
John McCall5769d612010-02-08 23:07:23 +00009533 SourceLocation Loc = Base->getExprLoc();
9534
Douglas Gregor8ba10742008-11-20 16:27:02 +00009535 // C++ [over.ref]p1:
9536 //
9537 // [...] An expression x->m is interpreted as (x.operator->())->m
9538 // for a class object x of type T if T::operator->() exists and if
9539 // the operator is selected as the best match function by the
9540 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +00009541 DeclarationName OpName =
9542 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00009543 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00009544 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009545
John McCall5769d612010-02-08 23:07:23 +00009546 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00009547 PDiag(diag::err_typecheck_incomplete_tag)
9548 << Base->getSourceRange()))
9549 return ExprError();
9550
John McCalla24dc2e2009-11-17 02:14:36 +00009551 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9552 LookupQualifiedName(R, BaseRecord->getDecl());
9553 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00009554
9555 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00009556 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009557 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9558 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00009559 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00009560
9561 // Perform overload resolution.
9562 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009563 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00009564 case OR_Success:
9565 // Overload resolution succeeded; we'll build the call below.
9566 break;
9567
9568 case OR_No_Viable_Function:
9569 if (CandidateSet.empty())
9570 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009571 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00009572 else
9573 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009574 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009575 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009576 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00009577
9578 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00009579 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9580 << "->" << Base->getType() << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009581 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009582 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009583
9584 case OR_Deleted:
9585 Diag(OpLoc, diag::err_ovl_deleted_oper)
9586 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009587 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009588 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009589 << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009590 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009591 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00009592 }
9593
Chandler Carruth25ca4212011-02-25 19:41:05 +00009594 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +00009595 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009596 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00009597
Douglas Gregor8ba10742008-11-20 16:27:02 +00009598 // Convert the object parameter.
9599 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +00009600 ExprResult BaseResult =
9601 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9602 Best->FoundDecl, Method);
9603 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009604 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009605 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00009606
Douglas Gregor8ba10742008-11-20 16:27:02 +00009607 // Build the operator call.
John Wiegley429bb272011-04-08 18:41:53 +00009608 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method);
9609 if (FnExpr.isInvalid())
9610 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009611
John McCallf89e55a2010-11-18 06:31:45 +00009612 QualType ResultTy = Method->getResultType();
9613 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9614 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +00009615 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009616 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009617 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00009618
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009619 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00009620 Method))
9621 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +00009622
9623 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00009624}
9625
Douglas Gregor904eed32008-11-10 20:40:00 +00009626/// FixOverloadedFunctionReference - E is an expression that refers to
9627/// a C++ overloaded function (possibly with some parentheses and
9628/// perhaps a '&' around it). We have resolved the overloaded function
9629/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00009630/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00009631Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00009632 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00009633 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00009634 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9635 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00009636 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00009637 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009638
Douglas Gregor699ee522009-11-20 19:42:02 +00009639 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009640 }
9641
Douglas Gregor699ee522009-11-20 19:42:02 +00009642 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00009643 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9644 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009645 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00009646 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00009647 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +00009648 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +00009649 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00009650 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009651
9652 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +00009653 ICE->getCastKind(),
9654 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00009655 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009656 }
9657
Douglas Gregor699ee522009-11-20 19:42:02 +00009658 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00009659 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00009660 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00009661 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9662 if (Method->isStatic()) {
9663 // Do nothing: static member functions aren't any different
9664 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00009665 } else {
John McCallf7a1a742009-11-24 19:00:30 +00009666 // Fix the sub expression, which really has to be an
9667 // UnresolvedLookupExpr holding an overloaded member function
9668 // or template.
John McCall6bb80172010-03-30 21:47:33 +00009669 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9670 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00009671 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00009672 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +00009673
John McCallba135432009-11-21 08:51:07 +00009674 assert(isa<DeclRefExpr>(SubExpr)
9675 && "fixed to something other than a decl ref");
9676 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
9677 && "fixed to a member ref with no nested name qualifier");
9678
9679 // We have taken the address of a pointer to member
9680 // function. Perform the computation here so that we get the
9681 // appropriate pointer to member type.
9682 QualType ClassType
9683 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
9684 QualType MemPtrType
9685 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9686
John McCallf89e55a2010-11-18 06:31:45 +00009687 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9688 VK_RValue, OK_Ordinary,
9689 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00009690 }
9691 }
John McCall6bb80172010-03-30 21:47:33 +00009692 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9693 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00009694 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00009695 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009696
John McCall2de56d12010-08-25 11:45:40 +00009697 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +00009698 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00009699 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +00009700 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009701 }
John McCallba135432009-11-21 08:51:07 +00009702
9703 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00009704 // FIXME: avoid copy.
9705 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00009706 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00009707 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9708 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00009709 }
9710
John McCallba135432009-11-21 08:51:07 +00009711 return DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00009712 ULE->getQualifierLoc(),
John McCallba135432009-11-21 08:51:07 +00009713 Fn,
9714 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00009715 Fn->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00009716 VK_LValue,
Chandler Carruth3aa81402011-05-01 23:48:14 +00009717 Found.getDecl(),
John McCallaa81e162009-12-01 22:10:20 +00009718 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00009719 }
9720
John McCall129e2df2009-11-30 22:42:35 +00009721 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00009722 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00009723 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9724 if (MemExpr->hasExplicitTemplateArgs()) {
9725 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9726 TemplateArgs = &TemplateArgsBuffer;
9727 }
John McCalld5532b62009-11-23 01:53:49 +00009728
John McCallaa81e162009-12-01 22:10:20 +00009729 Expr *Base;
9730
John McCallf89e55a2010-11-18 06:31:45 +00009731 // If we're filling in a static method where we used to have an
9732 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +00009733 if (MemExpr->isImplicitAccess()) {
9734 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9735 return DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00009736 MemExpr->getQualifierLoc(),
John McCallaa81e162009-12-01 22:10:20 +00009737 Fn,
9738 MemExpr->getMemberLoc(),
9739 Fn->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00009740 VK_LValue,
Chandler Carruth3aa81402011-05-01 23:48:14 +00009741 Found.getDecl(),
John McCallaa81e162009-12-01 22:10:20 +00009742 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00009743 } else {
9744 SourceLocation Loc = MemExpr->getMemberLoc();
9745 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +00009746 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregor828a1972010-01-07 23:12:05 +00009747 Base = new (Context) CXXThisExpr(Loc,
9748 MemExpr->getBaseType(),
9749 /*isImplicit=*/true);
9750 }
John McCallaa81e162009-12-01 22:10:20 +00009751 } else
John McCall3fa5cae2010-10-26 07:05:15 +00009752 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +00009753
John McCallf5307512011-04-27 00:36:17 +00009754 ExprValueKind valueKind;
9755 QualType type;
9756 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9757 valueKind = VK_LValue;
9758 type = Fn->getType();
9759 } else {
9760 valueKind = VK_RValue;
9761 type = Context.BoundMemberTy;
9762 }
9763
John McCallaa81e162009-12-01 22:10:20 +00009764 return MemberExpr::Create(Context, Base,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009765 MemExpr->isArrow(),
Douglas Gregor40d96a62011-02-28 21:54:11 +00009766 MemExpr->getQualifierLoc(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009767 Fn,
John McCall6bb80172010-03-30 21:47:33 +00009768 Found,
Abramo Bagnara25777432010-08-11 22:01:17 +00009769 MemExpr->getMemberNameInfo(),
John McCallaa81e162009-12-01 22:10:20 +00009770 TemplateArgs,
John McCallf5307512011-04-27 00:36:17 +00009771 type, valueKind, OK_Ordinary);
Douglas Gregor699ee522009-11-20 19:42:02 +00009772 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009773
John McCall3fa5cae2010-10-26 07:05:15 +00009774 llvm_unreachable("Invalid reference to overloaded function");
9775 return E;
Douglas Gregor904eed32008-11-10 20:40:00 +00009776}
9777
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009778ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +00009779 DeclAccessPair Found,
9780 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00009781 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00009782}
9783
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009784} // end namespace clang