blob: f316cfbe8c254327f8a9fee1949d8109c29c4d7b [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
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000041 SourceLocation Loc = SourceLocation(),
42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000043 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, Fn->getType(),
44 VK_LValue, Loc, LocInfo);
45 if (HadMultipleCandidates)
46 DRE->setHadMultipleCandidates(true);
47 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000048 E = S.DefaultFunctionArrayConversion(E.take());
49 if (E.isInvalid())
50 return ExprError();
51 return move(E);
John McCallf89e55a2010-11-18 06:31:45 +000052}
53
John McCall120d63c2010-08-24 20:38:10 +000054static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
55 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000056 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000057 bool CStyle,
58 bool AllowObjCWritebackConversion);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000059
60static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
61 QualType &ToType,
62 bool InOverloadResolution,
63 StandardConversionSequence &SCS,
64 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000065static OverloadingResult
66IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
67 UserDefinedConversionSequence& User,
68 OverloadCandidateSet& Conversions,
69 bool AllowExplicit);
70
71
72static ImplicitConversionSequence::CompareKind
73CompareStandardConversionSequences(Sema &S,
74 const StandardConversionSequence& SCS1,
75 const StandardConversionSequence& SCS2);
76
77static ImplicitConversionSequence::CompareKind
78CompareQualificationConversions(Sema &S,
79 const StandardConversionSequence& SCS1,
80 const StandardConversionSequence& SCS2);
81
82static ImplicitConversionSequence::CompareKind
83CompareDerivedToBaseConversions(Sema &S,
84 const StandardConversionSequence& SCS1,
85 const StandardConversionSequence& SCS2);
86
87
88
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000089/// GetConversionCategory - Retrieve the implicit conversion
90/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000091ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000092GetConversionCategory(ImplicitConversionKind Kind) {
93 static const ImplicitConversionCategory
94 Category[(int)ICK_Num_Conversion_Kinds] = {
95 ICC_Identity,
96 ICC_Lvalue_Transformation,
97 ICC_Lvalue_Transformation,
98 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000099 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000100 ICC_Qualification_Adjustment,
101 ICC_Promotion,
102 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000103 ICC_Promotion,
104 ICC_Conversion,
105 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 ICC_Conversion,
107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000111 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000112 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000113 ICC_Conversion,
114 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000115 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000116 ICC_Conversion
117 };
118 return Category[(int)Kind];
119}
120
121/// GetConversionRank - Retrieve the implicit conversion rank
122/// corresponding to the given implicit conversion kind.
123ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
124 static const ImplicitConversionRank
125 Rank[(int)ICK_Num_Conversion_Kinds] = {
126 ICR_Exact_Match,
127 ICR_Exact_Match,
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000131 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000132 ICR_Promotion,
133 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000134 ICR_Promotion,
135 ICR_Conversion,
136 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000142 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000143 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000144 ICR_Conversion,
145 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000146 ICR_Complex_Real_Conversion,
147 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000148 ICR_Conversion,
149 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000150 };
151 return Rank[(int)Kind];
152}
153
154/// GetImplicitConversionName - Return the name of this kind of
155/// implicit conversion.
156const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000158 "No conversion",
159 "Lvalue-to-rvalue",
160 "Array-to-pointer",
161 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000162 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000163 "Qualification",
164 "Integral promotion",
165 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000166 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000167 "Integral conversion",
168 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000169 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000170 "Floating-integral conversion",
171 "Pointer conversion",
172 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000173 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000174 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000175 "Derived-to-base conversion",
176 "Vector conversion",
177 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000178 "Complex-real conversion",
179 "Block Pointer conversion",
180 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000181 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182 };
183 return Name[Kind];
184}
185
Douglas Gregor60d62c22008-10-31 16:23:19 +0000186/// StandardConversionSequence - Set the standard conversion
187/// sequence to the identity conversion.
188void StandardConversionSequence::setAsIdentityConversion() {
189 First = ICK_Identity;
190 Second = ICK_Identity;
191 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000192 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000193 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000194 ReferenceBinding = false;
195 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000196 IsLvalueReference = true;
197 BindsToFunctionLvalue = false;
198 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000199 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000200 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000201 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000202}
203
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000204/// getRank - Retrieve the rank of this standard conversion sequence
205/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206/// implicit conversions.
207ImplicitConversionRank StandardConversionSequence::getRank() const {
208 ImplicitConversionRank Rank = ICR_Exact_Match;
209 if (GetConversionRank(First) > Rank)
210 Rank = GetConversionRank(First);
211 if (GetConversionRank(Second) > Rank)
212 Rank = GetConversionRank(Second);
213 if (GetConversionRank(Third) > Rank)
214 Rank = GetConversionRank(Third);
215 return Rank;
216}
217
218/// isPointerConversionToBool - Determines whether this conversion is
219/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000220/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000221/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000222bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000223 // Note that FromType has not necessarily been transformed by the
224 // array-to-pointer or function-to-pointer implicit conversions, so
225 // check for their presence as well as checking whether FromType is
226 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000227 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000228 (getFromType()->isPointerType() ||
229 getFromType()->isObjCObjectPointerType() ||
230 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000231 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000232 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
233 return true;
234
235 return false;
236}
237
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000238/// isPointerConversionToVoidPointer - Determines whether this
239/// conversion is a conversion of a pointer to a void pointer. This is
240/// used as part of the ranking of standard conversion sequences (C++
241/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000242bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000243StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000244isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000245 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000246 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000247
248 // Note that FromType has not necessarily been transformed by the
249 // array-to-pointer implicit conversion, so check for its presence
250 // and redo the conversion to get a pointer.
251 if (First == ICK_Array_To_Pointer)
252 FromType = Context.getArrayDecayedType(FromType);
253
Douglas Gregorf9af5242011-04-15 20:45:44 +0000254 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000255 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000256 return ToPtrType->getPointeeType()->isVoidType();
257
258 return false;
259}
260
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000261/// DebugPrint - Print this standard conversion sequence to standard
262/// error. Useful for debugging overloading issues.
263void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000264 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000265 bool PrintedSomething = false;
266 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000267 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000268 PrintedSomething = true;
269 }
270
271 if (Second != ICK_Identity) {
272 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000273 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000274 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000275 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000276
277 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000278 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000279 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000280 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000281 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000282 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000283 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000284 PrintedSomething = true;
285 }
286
287 if (Third != ICK_Identity) {
288 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000289 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000290 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000291 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000292 PrintedSomething = true;
293 }
294
295 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000296 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000297 }
298}
299
300/// DebugPrint - Print this user-defined conversion sequence to standard
301/// error. Useful for debugging overloading issues.
302void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000303 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000304 if (Before.First || Before.Second || Before.Third) {
305 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000306 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000307 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000308 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000309 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000310 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000311 After.DebugPrint();
312 }
313}
314
315/// DebugPrint - Print this implicit conversion sequence to standard
316/// error. Useful for debugging overloading issues.
317void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000318 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000319 switch (ConversionKind) {
320 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000321 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000322 Standard.DebugPrint();
323 break;
324 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000325 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000326 UserDefined.DebugPrint();
327 break;
328 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000329 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000330 break;
John McCall1d318332010-01-12 00:44:57 +0000331 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000332 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000333 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000334 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000335 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000336 break;
337 }
338
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000339 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000340}
341
John McCall1d318332010-01-12 00:44:57 +0000342void AmbiguousConversionSequence::construct() {
343 new (&conversions()) ConversionSet();
344}
345
346void AmbiguousConversionSequence::destruct() {
347 conversions().~ConversionSet();
348}
349
350void
351AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
352 FromTypePtr = O.FromTypePtr;
353 ToTypePtr = O.ToTypePtr;
354 new (&conversions()) ConversionSet(O.conversions());
355}
356
Douglas Gregora9333192010-05-08 17:41:32 +0000357namespace {
358 // Structure used by OverloadCandidate::DeductionFailureInfo to store
359 // template parameter and template argument information.
360 struct DFIParamWithArguments {
361 TemplateParameter Param;
362 TemplateArgument FirstArg;
363 TemplateArgument SecondArg;
364 };
365}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000366
Douglas Gregora9333192010-05-08 17:41:32 +0000367/// \brief Convert from Sema's representation of template deduction information
368/// to the form used in overload-candidate information.
369OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000370static MakeDeductionFailureInfo(ASTContext &Context,
371 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000372 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000373 OverloadCandidate::DeductionFailureInfo Result;
374 Result.Result = static_cast<unsigned>(TDK);
375 Result.Data = 0;
376 switch (TDK) {
377 case Sema::TDK_Success:
378 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000379 case Sema::TDK_TooManyArguments:
380 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000381 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000382
Douglas Gregora9333192010-05-08 17:41:32 +0000383 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000384 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000385 Result.Data = Info.Param.getOpaqueValue();
386 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000387
Douglas Gregora9333192010-05-08 17:41:32 +0000388 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000389 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000390 // FIXME: Should allocate from normal heap so that we can free this later.
391 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000392 Saved->Param = Info.Param;
393 Saved->FirstArg = Info.FirstArg;
394 Saved->SecondArg = Info.SecondArg;
395 Result.Data = Saved;
396 break;
397 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000398
Douglas Gregora9333192010-05-08 17:41:32 +0000399 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000400 Result.Data = Info.take();
401 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000402
Douglas Gregora9333192010-05-08 17:41:32 +0000403 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000404 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000405 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000406 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000407
Douglas Gregora9333192010-05-08 17:41:32 +0000408 return Result;
409}
John McCall1d318332010-01-12 00:44:57 +0000410
Douglas Gregora9333192010-05-08 17:41:32 +0000411void OverloadCandidate::DeductionFailureInfo::Destroy() {
412 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
413 case Sema::TDK_Success:
414 case Sema::TDK_InstantiationDepth:
415 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000416 case Sema::TDK_TooManyArguments:
417 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000418 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000419 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000420
Douglas Gregora9333192010-05-08 17:41:32 +0000421 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000422 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000423 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000424 Data = 0;
425 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000426
427 case Sema::TDK_SubstitutionFailure:
428 // FIXME: Destroy the template arugment list?
429 Data = 0;
430 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000431
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000432 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000433 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000434 case Sema::TDK_FailedOverloadResolution:
435 break;
436 }
437}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000438
439TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000440OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
441 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
442 case Sema::TDK_Success:
443 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000444 case Sema::TDK_TooManyArguments:
445 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000446 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000447 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000448
Douglas Gregora9333192010-05-08 17:41:32 +0000449 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000450 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000451 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000452
453 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000454 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000455 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000456
Douglas Gregora9333192010-05-08 17:41:32 +0000457 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000458 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000459 case Sema::TDK_FailedOverloadResolution:
460 break;
461 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000462
Douglas Gregora9333192010-05-08 17:41:32 +0000463 return TemplateParameter();
464}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000465
Douglas Gregorec20f462010-05-08 20:07:26 +0000466TemplateArgumentList *
467OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
468 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
469 case Sema::TDK_Success:
470 case Sema::TDK_InstantiationDepth:
471 case Sema::TDK_TooManyArguments:
472 case Sema::TDK_TooFewArguments:
473 case Sema::TDK_Incomplete:
474 case Sema::TDK_InvalidExplicitArguments:
475 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000476 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000477 return 0;
478
479 case Sema::TDK_SubstitutionFailure:
480 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000481
Douglas Gregorec20f462010-05-08 20:07:26 +0000482 // Unhandled
483 case Sema::TDK_NonDeducedMismatch:
484 case Sema::TDK_FailedOverloadResolution:
485 break;
486 }
487
488 return 0;
489}
490
Douglas Gregora9333192010-05-08 17:41:32 +0000491const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
492 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
493 case Sema::TDK_Success:
494 case Sema::TDK_InstantiationDepth:
495 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000496 case Sema::TDK_TooManyArguments:
497 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000498 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000499 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000500 return 0;
501
Douglas Gregora9333192010-05-08 17:41:32 +0000502 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000503 case Sema::TDK_Underqualified:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000504 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000505
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000506 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000507 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000508 case Sema::TDK_FailedOverloadResolution:
509 break;
510 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000511
Douglas Gregora9333192010-05-08 17:41:32 +0000512 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000513}
Douglas Gregora9333192010-05-08 17:41:32 +0000514
515const TemplateArgument *
516OverloadCandidate::DeductionFailureInfo::getSecondArg() {
517 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
518 case Sema::TDK_Success:
519 case Sema::TDK_InstantiationDepth:
520 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000521 case Sema::TDK_TooManyArguments:
522 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000523 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000524 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000525 return 0;
526
Douglas Gregora9333192010-05-08 17:41:32 +0000527 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000528 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000529 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
530
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000531 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000532 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000533 case Sema::TDK_FailedOverloadResolution:
534 break;
535 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000536
Douglas Gregora9333192010-05-08 17:41:32 +0000537 return 0;
538}
539
540void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000541 inherited::clear();
542 Functions.clear();
543}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000544
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000545// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000546// overload of the declarations in Old. This routine returns false if
547// New and Old cannot be overloaded, e.g., if New has the same
548// signature as some function in Old (C++ 1.3.10) or if the Old
549// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000550// it does return false, MatchedDecl will point to the decl that New
551// cannot be overloaded with. This decl may be a UsingShadowDecl on
552// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000553//
554// Example: Given the following input:
555//
556// void f(int, float); // #1
557// void f(int, int); // #2
558// int f(int, int); // #3
559//
560// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000561// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000562//
John McCall51fa86f2009-12-02 08:47:38 +0000563// When we process #2, Old contains only the FunctionDecl for #1. By
564// comparing the parameter types, we see that #1 and #2 are overloaded
565// (since they have different signatures), so this routine returns
566// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000567//
John McCall51fa86f2009-12-02 08:47:38 +0000568// When we process #3, Old is an overload set containing #1 and #2. We
569// compare the signatures of #3 to #1 (they're overloaded, so we do
570// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
571// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000572// signature), IsOverload returns false and MatchedDecl will be set to
573// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000574//
575// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
576// into a class by a using declaration. The rules for whether to hide
577// shadow declarations ignore some properties which otherwise figure
578// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000579Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000580Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
581 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000582 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000583 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000584 NamedDecl *OldD = *I;
585
586 bool OldIsUsingDecl = false;
587 if (isa<UsingShadowDecl>(OldD)) {
588 OldIsUsingDecl = true;
589
590 // We can always introduce two using declarations into the same
591 // context, even if they have identical signatures.
592 if (NewIsUsingDecl) continue;
593
594 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
595 }
596
597 // If either declaration was introduced by a using declaration,
598 // we'll need to use slightly different rules for matching.
599 // Essentially, these rules are the normal rules, except that
600 // function templates hide function templates with different
601 // return types or template parameter lists.
602 bool UseMemberUsingDeclRules =
603 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
604
John McCall51fa86f2009-12-02 08:47:38 +0000605 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000606 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
607 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
608 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
609 continue;
610 }
611
John McCall871b2e72009-12-09 03:35:25 +0000612 Match = *I;
613 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000614 }
John McCall51fa86f2009-12-02 08:47:38 +0000615 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000616 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
617 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
618 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
619 continue;
620 }
621
John McCall871b2e72009-12-09 03:35:25 +0000622 Match = *I;
623 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000624 }
John McCalld7945c62010-11-10 03:01:53 +0000625 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000626 // We can overload with these, which can show up when doing
627 // redeclaration checks for UsingDecls.
628 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000629 } else if (isa<TagDecl>(OldD)) {
630 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000631 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
632 // Optimistically assume that an unresolved using decl will
633 // overload; if it doesn't, we'll have to diagnose during
634 // template instantiation.
635 } else {
John McCall68263142009-11-18 22:49:29 +0000636 // (C++ 13p1):
637 // Only function declarations can be overloaded; object and type
638 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000639 Match = *I;
640 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000641 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000642 }
John McCall68263142009-11-18 22:49:29 +0000643
John McCall871b2e72009-12-09 03:35:25 +0000644 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000645}
646
John McCallad00b772010-06-16 08:42:20 +0000647bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
648 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000649 // If both of the functions are extern "C", then they are not
650 // overloads.
651 if (Old->isExternC() && New->isExternC())
652 return false;
653
John McCall68263142009-11-18 22:49:29 +0000654 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
655 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
656
657 // C++ [temp.fct]p2:
658 // A function template can be overloaded with other function templates
659 // and with normal (non-template) functions.
660 if ((OldTemplate == 0) != (NewTemplate == 0))
661 return true;
662
663 // Is the function New an overload of the function Old?
664 QualType OldQType = Context.getCanonicalType(Old->getType());
665 QualType NewQType = Context.getCanonicalType(New->getType());
666
667 // Compare the signatures (C++ 1.3.10) of the two functions to
668 // determine whether they are overloads. If we find any mismatch
669 // in the signature, they are overloads.
670
671 // If either of these functions is a K&R-style function (no
672 // prototype), then we consider them to have matching signatures.
673 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
674 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
675 return false;
676
John McCallf4c73712011-01-19 06:33:43 +0000677 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
678 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000679
680 // The signature of a function includes the types of its
681 // parameters (C++ 1.3.10), which includes the presence or absence
682 // of the ellipsis; see C++ DR 357).
683 if (OldQType != NewQType &&
684 (OldType->getNumArgs() != NewType->getNumArgs() ||
685 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000686 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000687 return true;
688
689 // C++ [temp.over.link]p4:
690 // The signature of a function template consists of its function
691 // signature, its return type and its template parameter list. The names
692 // of the template parameters are significant only for establishing the
693 // relationship between the template parameters and the rest of the
694 // signature.
695 //
696 // We check the return type and template parameter lists for function
697 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000698 //
699 // However, we don't consider either of these when deciding whether
700 // a member introduced by a shadow declaration is hidden.
701 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000702 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
703 OldTemplate->getTemplateParameters(),
704 false, TPL_TemplateMatch) ||
705 OldType->getResultType() != NewType->getResultType()))
706 return true;
707
708 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000709 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +0000710 //
711 // As part of this, also check whether one of the member functions
712 // is static, in which case they are not overloads (C++
713 // 13.1p2). While not part of the definition of the signature,
714 // this check is important to determine whether these functions
715 // can be overloaded.
716 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
717 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
718 if (OldMethod && NewMethod &&
719 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000720 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-01-26 21:20:37 +0000721 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
722 if (!UseUsingDeclRules &&
723 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
724 (OldMethod->getRefQualifier() == RQ_None ||
725 NewMethod->getRefQualifier() == RQ_None)) {
726 // C++0x [over.load]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000727 // - Member function declarations with the same name and the same
728 // parameter-type-list as well as member function template
729 // declarations with the same name, the same parameter-type-list, and
730 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorb145ee62011-01-26 21:20:37 +0000731 // them, but not all, have a ref-qualifier (8.3.5).
732 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
733 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
734 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
735 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000736
John McCall68263142009-11-18 22:49:29 +0000737 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +0000738 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000739
John McCall68263142009-11-18 22:49:29 +0000740 // The signatures match; this is not an overload.
741 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000742}
743
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +0000744/// \brief Checks availability of the function depending on the current
745/// function context. Inside an unavailable function, unavailability is ignored.
746///
747/// \returns true if \arg FD is unavailable and current context is inside
748/// an available function, false otherwise.
749bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
750 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
751}
752
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000753/// TryImplicitConversion - Attempt to perform an implicit conversion
754/// from the given expression (Expr) to the given type (ToType). This
755/// function returns an implicit conversion sequence that can be used
756/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000757///
758/// void f(float f);
759/// void g(int i) { f(i); }
760///
761/// this routine would produce an implicit conversion sequence to
762/// describe the initialization of f from i, which will be a standard
763/// conversion sequence containing an lvalue-to-rvalue conversion (C++
764/// 4.1) followed by a floating-integral conversion (C++ 4.9).
765//
766/// Note that this routine only determines how the conversion can be
767/// performed; it does not actually perform the conversion. As such,
768/// it will not produce any diagnostics if no conversion is available,
769/// but will instead return an implicit conversion sequence of kind
770/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000771///
772/// If @p SuppressUserConversions, then user-defined conversions are
773/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000774/// If @p AllowExplicit, then explicit user-defined conversions are
775/// permitted.
John McCallf85e1932011-06-15 23:02:42 +0000776///
777/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
778/// writeback conversion, which allows __autoreleasing id* parameters to
779/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +0000780static ImplicitConversionSequence
781TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
782 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000783 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000784 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +0000785 bool CStyle,
786 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000787 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +0000788 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +0000789 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +0000790 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000791 return ICS;
792 }
793
John McCall120d63c2010-08-24 20:38:10 +0000794 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000795 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000796 return ICS;
797 }
798
Douglas Gregor604eb652010-08-11 02:15:33 +0000799 // C++ [over.ics.user]p4:
800 // A conversion of an expression of class type to the same class
801 // type is given Exact Match rank, and a conversion of an
802 // expression of class type to a base class of that type is
803 // given Conversion rank, in spite of the fact that a copy/move
804 // constructor (i.e., a user-defined conversion function) is
805 // called for those cases.
806 QualType FromType = From->getType();
807 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +0000808 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
809 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000810 ICS.setStandard();
811 ICS.Standard.setAsIdentityConversion();
812 ICS.Standard.setFromType(FromType);
813 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000814
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000815 // We don't actually check at this point whether there is a valid
816 // copy/move constructor, since overloading just assumes that it
817 // exists. When we actually perform initialization, we'll find the
818 // appropriate constructor to copy the returned object, if needed.
819 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000820
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000821 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +0000822 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000823 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000824
Douglas Gregor604eb652010-08-11 02:15:33 +0000825 return ICS;
826 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000827
Douglas Gregor604eb652010-08-11 02:15:33 +0000828 if (SuppressUserConversions) {
829 // We're not in the case above, so there is no conversion that
830 // we can perform.
831 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000832 return ICS;
833 }
834
835 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000836 OverloadCandidateSet Conversions(From->getExprLoc());
837 OverloadingResult UserDefResult
John McCall120d63c2010-08-24 20:38:10 +0000838 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000839 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000840
841 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000842 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000843 // C++ [over.ics.user]p4:
844 // A conversion of an expression of class type to the same class
845 // type is given Exact Match rank, and a conversion of an
846 // expression of class type to a base class of that type is
847 // given Conversion rank, in spite of the fact that a copy
848 // constructor (i.e., a user-defined conversion function) is
849 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000850 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000851 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000852 QualType FromCanon
John McCall120d63c2010-08-24 20:38:10 +0000853 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
854 QualType ToCanon
855 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000856 if (Constructor->isCopyConstructor() &&
John McCall120d63c2010-08-24 20:38:10 +0000857 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000858 // Turn this into a "standard" conversion sequence, so that it
859 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000860 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000861 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000862 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000863 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000864 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000865 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000866 ICS.Standard.Second = ICK_Derived_To_Base;
867 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000868 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000869
870 // C++ [over.best.ics]p4:
871 // However, when considering the argument of a user-defined
872 // conversion function that is a candidate by 13.3.1.3 when
873 // invoked for the copying of the temporary in the second step
874 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
875 // 13.3.1.6 in all cases, only standard conversion sequences and
876 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000877 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000878 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000879 }
John McCallcefd3ad2010-01-13 22:30:33 +0000880 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000881 ICS.setAmbiguous();
882 ICS.Ambiguous.setFromType(From->getType());
883 ICS.Ambiguous.setToType(ToType);
884 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
885 Cand != Conversions.end(); ++Cand)
886 if (Cand->Viable)
887 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000888 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000889 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000890 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000891
892 return ICS;
893}
894
John McCallf85e1932011-06-15 23:02:42 +0000895ImplicitConversionSequence
896Sema::TryImplicitConversion(Expr *From, QualType ToType,
897 bool SuppressUserConversions,
898 bool AllowExplicit,
899 bool InOverloadResolution,
900 bool CStyle,
901 bool AllowObjCWritebackConversion) {
902 return clang::TryImplicitConversion(*this, From, ToType,
903 SuppressUserConversions, AllowExplicit,
904 InOverloadResolution, CStyle,
905 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +0000906}
907
Douglas Gregor575c63a2010-04-16 22:27:05 +0000908/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +0000909/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +0000910/// converted expression. Flavor is the kind of conversion we're
911/// performing, used in the error message. If @p AllowExplicit,
912/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +0000913ExprResult
914Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000915 AssignmentAction Action, bool AllowExplicit,
916 bool Diagnose) {
Douglas Gregor575c63a2010-04-16 22:27:05 +0000917 ImplicitConversionSequence ICS;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000918 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS,
919 Diagnose);
Douglas Gregor575c63a2010-04-16 22:27:05 +0000920}
921
John Wiegley429bb272011-04-08 18:41:53 +0000922ExprResult
923Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +0000924 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000925 ImplicitConversionSequence& ICS,
926 bool Diagnose) {
John McCallf85e1932011-06-15 23:02:42 +0000927 // Objective-C ARC: Determine whether we will allow the writeback conversion.
928 bool AllowObjCWritebackConversion
929 = getLangOptions().ObjCAutoRefCount &&
930 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +0000931
John McCall120d63c2010-08-24 20:38:10 +0000932 ICS = clang::TryImplicitConversion(*this, From, ToType,
933 /*SuppressUserConversions=*/false,
934 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000935 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +0000936 /*CStyle=*/false,
937 AllowObjCWritebackConversion);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000938 if (!Diagnose && ICS.isFailure())
939 return ExprError();
Douglas Gregor575c63a2010-04-16 22:27:05 +0000940 return PerformImplicitConversion(From, ToType, ICS, Action);
941}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000942
943/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +0000944/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +0000945bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
946 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +0000947 if (Context.hasSameUnqualifiedType(FromType, ToType))
948 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000949
John McCall00ccbef2010-12-21 00:44:39 +0000950 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
951 // where F adds one of the following at most once:
952 // - a pointer
953 // - a member pointer
954 // - a block pointer
955 CanQualType CanTo = Context.getCanonicalType(ToType);
956 CanQualType CanFrom = Context.getCanonicalType(FromType);
957 Type::TypeClass TyClass = CanTo->getTypeClass();
958 if (TyClass != CanFrom->getTypeClass()) return false;
959 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
960 if (TyClass == Type::Pointer) {
961 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
962 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
963 } else if (TyClass == Type::BlockPointer) {
964 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
965 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
966 } else if (TyClass == Type::MemberPointer) {
967 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
968 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
969 } else {
970 return false;
971 }
Douglas Gregor43c79c22009-12-09 00:47:37 +0000972
John McCall00ccbef2010-12-21 00:44:39 +0000973 TyClass = CanTo->getTypeClass();
974 if (TyClass != CanFrom->getTypeClass()) return false;
975 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
976 return false;
977 }
978
979 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
980 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
981 if (!EInfo.getNoReturn()) return false;
982
983 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
984 assert(QualType(FromFn, 0).isCanonical());
985 if (QualType(FromFn, 0) != CanTo) return false;
986
987 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +0000988 return true;
989}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000990
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000991/// \brief Determine whether the conversion from FromType to ToType is a valid
992/// vector conversion.
993///
994/// \param ICK Will be set to the vector conversion kind, if this is a vector
995/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000996static bool IsVectorConversion(ASTContext &Context, QualType FromType,
997 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000998 // We need at least one of these types to be a vector type to have a vector
999 // conversion.
1000 if (!ToType->isVectorType() && !FromType->isVectorType())
1001 return false;
1002
1003 // Identical types require no conversions.
1004 if (Context.hasSameUnqualifiedType(FromType, ToType))
1005 return false;
1006
1007 // There are no conversions between extended vector types, only identity.
1008 if (ToType->isExtVectorType()) {
1009 // There are no conversions between extended vector types other than the
1010 // identity conversion.
1011 if (FromType->isExtVectorType())
1012 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001013
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001014 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001015 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001016 ICK = ICK_Vector_Splat;
1017 return true;
1018 }
1019 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001020
1021 // We can perform the conversion between vector types in the following cases:
1022 // 1)vector types are equivalent AltiVec and GCC vector types
1023 // 2)lax vector conversions are permitted and the vector types are of the
1024 // same size
1025 if (ToType->isVectorType() && FromType->isVectorType()) {
1026 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001027 (Context.getLangOptions().LaxVectorConversions &&
1028 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001029 ICK = ICK_Vector_Conversion;
1030 return true;
1031 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001032 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001033
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001034 return false;
1035}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001036
Douglas Gregor60d62c22008-10-31 16:23:19 +00001037/// IsStandardConversion - Determines whether there is a standard
1038/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1039/// expression From to the type ToType. Standard conversion sequences
1040/// only consider non-class types; for conversions that involve class
1041/// types, use TryImplicitConversion. If a conversion exists, SCS will
1042/// contain the standard conversion sequence required to perform this
1043/// conversion and this routine will return true. Otherwise, this
1044/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001045static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1046 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001047 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001048 bool CStyle,
1049 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001050 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001051
Douglas Gregor60d62c22008-10-31 16:23:19 +00001052 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001053 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001054 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001055 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001056 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001057 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001058
Douglas Gregorf9201e02009-02-11 23:02:49 +00001059 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001060 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001061 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +00001062 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001063 return false;
1064
Mike Stump1eb44332009-09-09 15:08:12 +00001065 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001066 }
1067
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001068 // The first conversion can be an lvalue-to-rvalue conversion,
1069 // array-to-pointer conversion, or function-to-pointer conversion
1070 // (C++ 4p1).
1071
John McCall120d63c2010-08-24 20:38:10 +00001072 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001073 DeclAccessPair AccessPair;
1074 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001075 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001076 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001077 // We were able to resolve the address of the overloaded function,
1078 // so we can convert to the type of that function.
1079 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001080
1081 // we can sometimes resolve &foo<int> regardless of ToType, so check
1082 // if the type matches (identity) or we are converting to bool
1083 if (!S.Context.hasSameUnqualifiedType(
1084 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1085 QualType resultTy;
1086 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001087 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001088 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1089 // otherwise, only a boolean conversion is standard
1090 if (!ToType->isBooleanType())
1091 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001092 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001093
Chandler Carruth90434232011-03-29 08:08:18 +00001094 // Check if the "from" expression is taking the address of an overloaded
1095 // function and recompute the FromType accordingly. Take advantage of the
1096 // fact that non-static member functions *must* have such an address-of
1097 // expression.
1098 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1099 if (Method && !Method->isStatic()) {
1100 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1101 "Non-unary operator on non-static member address");
1102 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1103 == UO_AddrOf &&
1104 "Non-address-of operator on non-static member address");
1105 const Type *ClassType
1106 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1107 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001108 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1109 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1110 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001111 "Non-address-of operator for overloaded function expression");
1112 FromType = S.Context.getPointerType(FromType);
1113 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001114
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001115 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001116 assert(S.Context.hasSameType(
1117 FromType,
1118 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001119 } else {
1120 return false;
1121 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001122 }
John McCall21480112011-08-30 00:57:29 +00001123 // Lvalue-to-rvalue conversion (C++11 4.1):
1124 // A glvalue (3.10) of a non-function, non-array type T can
1125 // be converted to a prvalue.
1126 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001127 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001128 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001129 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001130 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001131
1132 // If T is a non-class type, the type of the rvalue is the
1133 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001134 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1135 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001136 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001137 } else if (FromType->isArrayType()) {
1138 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001139 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001140
1141 // An lvalue or rvalue of type "array of N T" or "array of unknown
1142 // bound of T" can be converted to an rvalue of type "pointer to
1143 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001144 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001145
John McCall120d63c2010-08-24 20:38:10 +00001146 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001147 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001148 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001149
1150 // For the purpose of ranking in overload resolution
1151 // (13.3.3.1.1), this conversion is considered an
1152 // array-to-pointer conversion followed by a qualification
1153 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001154 SCS.Second = ICK_Identity;
1155 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001156 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001157 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001158 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001159 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001160 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001161 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001162 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001163
1164 // An lvalue of function type T can be converted to an rvalue of
1165 // type "pointer to T." The result is a pointer to the
1166 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001167 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001168 } else {
1169 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001170 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001171 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001172 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001173
1174 // The second conversion can be an integral promotion, floating
1175 // point promotion, integral conversion, floating point conversion,
1176 // floating-integral conversion, pointer conversion,
1177 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001178 // For overloading in C, this can also be a "compatible-type"
1179 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001180 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001181 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001182 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001183 // The unqualified versions of the types are the same: there's no
1184 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001185 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001186 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001187 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001188 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001189 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001190 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001191 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001192 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001193 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001194 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001195 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001196 SCS.Second = ICK_Complex_Promotion;
1197 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001198 } else if (ToType->isBooleanType() &&
1199 (FromType->isArithmeticType() ||
1200 FromType->isAnyPointerType() ||
1201 FromType->isBlockPointerType() ||
1202 FromType->isMemberPointerType() ||
1203 FromType->isNullPtrType())) {
1204 // Boolean conversions (C++ 4.12).
1205 SCS.Second = ICK_Boolean_Conversion;
1206 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001207 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001208 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001209 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001210 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001211 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001212 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001213 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001214 SCS.Second = ICK_Complex_Conversion;
1215 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001216 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1217 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001218 // Complex-real conversions (C99 6.3.1.7)
1219 SCS.Second = ICK_Complex_Real;
1220 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001221 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001222 // Floating point conversions (C++ 4.8).
1223 SCS.Second = ICK_Floating_Conversion;
1224 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001225 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001226 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001227 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001228 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001229 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001230 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001231 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001232 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001233 SCS.Second = ICK_Block_Pointer_Conversion;
1234 } else if (AllowObjCWritebackConversion &&
1235 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1236 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001237 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1238 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001239 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001240 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001241 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001242 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001243 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001244 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001245 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001246 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001247 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001248 SCS.Second = SecondICK;
1249 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001250 } else if (!S.getLangOptions().CPlusPlus &&
1251 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001252 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001253 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001254 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001255 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001256 // Treat a conversion that strips "noreturn" as an identity conversion.
1257 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001258 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1259 InOverloadResolution,
1260 SCS, CStyle)) {
1261 SCS.Second = ICK_TransparentUnionConversion;
1262 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001263 } else {
1264 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001265 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001266 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001267 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001268
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001269 QualType CanonFrom;
1270 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001271 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001272 bool ObjCLifetimeConversion;
1273 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1274 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001275 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001276 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001277 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001278 CanonFrom = S.Context.getCanonicalType(FromType);
1279 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001280 } else {
1281 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001282 SCS.Third = ICK_Identity;
1283
Mike Stump1eb44332009-09-09 15:08:12 +00001284 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001285 // [...] Any difference in top-level cv-qualification is
1286 // subsumed by the initialization itself and does not constitute
1287 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001288 CanonFrom = S.Context.getCanonicalType(FromType);
1289 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001290 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001291 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001292 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001293 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1294 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001295 FromType = ToType;
1296 CanonFrom = CanonTo;
1297 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001298 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001299 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001300
1301 // If we have not converted the argument type to the parameter type,
1302 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001303 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001304 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001305
Douglas Gregor60d62c22008-10-31 16:23:19 +00001306 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001307}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001308
1309static bool
1310IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1311 QualType &ToType,
1312 bool InOverloadResolution,
1313 StandardConversionSequence &SCS,
1314 bool CStyle) {
1315
1316 const RecordType *UT = ToType->getAsUnionType();
1317 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1318 return false;
1319 // The field to initialize within the transparent union.
1320 RecordDecl *UD = UT->getDecl();
1321 // It's compatible if the expression matches any of the fields.
1322 for (RecordDecl::field_iterator it = UD->field_begin(),
1323 itend = UD->field_end();
1324 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001325 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1326 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001327 ToType = it->getType();
1328 return true;
1329 }
1330 }
1331 return false;
1332}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001333
1334/// IsIntegralPromotion - Determines whether the conversion from the
1335/// expression From (whose potentially-adjusted type is FromType) to
1336/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1337/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001338bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001339 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001340 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001341 if (!To) {
1342 return false;
1343 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001344
1345 // An rvalue of type char, signed char, unsigned char, short int, or
1346 // unsigned short int can be converted to an rvalue of type int if
1347 // int can represent all the values of the source type; otherwise,
1348 // the source rvalue can be converted to an rvalue of type unsigned
1349 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001350 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1351 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001352 if (// We can promote any signed, promotable integer type to an int
1353 (FromType->isSignedIntegerType() ||
1354 // We can promote any unsigned integer type whose size is
1355 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001356 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001357 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001358 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001359 }
1360
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001361 return To->getKind() == BuiltinType::UInt;
1362 }
1363
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001364 // C++0x [conv.prom]p3:
1365 // A prvalue of an unscoped enumeration type whose underlying type is not
1366 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1367 // following types that can represent all the values of the enumeration
1368 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1369 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001370 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001371 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001372 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001373 // with lowest integer conversion rank (4.13) greater than the rank of long
1374 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001375 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001376 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1377 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1378 // provided for a scoped enumeration.
1379 if (FromEnumType->getDecl()->isScoped())
1380 return false;
1381
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001382 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001383 if (ToType->isIntegerType() &&
Douglas Gregor5dde1602010-09-12 03:38:25 +00001384 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001385 return Context.hasSameUnqualifiedType(ToType,
1386 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001387 }
John McCall842aef82009-12-09 09:09:27 +00001388
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001389 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001390 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1391 // to an rvalue a prvalue of the first of the following types that can
1392 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001393 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001394 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001395 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001396 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001397 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001398 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001399 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001400 // Determine whether the type we're converting from is signed or
1401 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001402 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001403 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001404
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001405 // The types we'll try to promote to, in the appropriate
1406 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001407 QualType PromoteTypes[6] = {
1408 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001409 Context.LongTy, Context.UnsignedLongTy ,
1410 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001411 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001412 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001413 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1414 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001415 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001416 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1417 // We found the type that we can promote to. If this is the
1418 // type we wanted, we have a promotion. Otherwise, no
1419 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001420 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001421 }
1422 }
1423 }
1424
1425 // An rvalue for an integral bit-field (9.6) can be converted to an
1426 // rvalue of type int if int can represent all the values of the
1427 // bit-field; otherwise, it can be converted to unsigned int if
1428 // unsigned int can represent all the values of the bit-field. If
1429 // the bit-field is larger yet, no integral promotion applies to
1430 // it. If the bit-field has an enumerated type, it is treated as any
1431 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001432 // FIXME: We should delay checking of bit-fields until we actually perform the
1433 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001434 using llvm::APSInt;
1435 if (From)
1436 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001437 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001438 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001439 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1440 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1441 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Douglas Gregor86f19402008-12-20 23:49:58 +00001443 // Are we promoting to an int from a bitfield that fits in an int?
1444 if (BitWidth < ToSize ||
1445 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1446 return To->getKind() == BuiltinType::Int;
1447 }
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Douglas Gregor86f19402008-12-20 23:49:58 +00001449 // Are we promoting to an unsigned int from an unsigned bitfield
1450 // that fits into an unsigned int?
1451 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1452 return To->getKind() == BuiltinType::UInt;
1453 }
Mike Stump1eb44332009-09-09 15:08:12 +00001454
Douglas Gregor86f19402008-12-20 23:49:58 +00001455 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001456 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001457 }
Mike Stump1eb44332009-09-09 15:08:12 +00001458
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001459 // An rvalue of type bool can be converted to an rvalue of type int,
1460 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001461 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001462 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001463 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001464
1465 return false;
1466}
1467
1468/// IsFloatingPointPromotion - Determines whether the conversion from
1469/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1470/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001471bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001472 /// An rvalue of type float can be converted to an rvalue of type
1473 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001474 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1475 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001476 if (FromBuiltin->getKind() == BuiltinType::Float &&
1477 ToBuiltin->getKind() == BuiltinType::Double)
1478 return true;
1479
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001480 // C99 6.3.1.5p1:
1481 // When a float is promoted to double or long double, or a
1482 // double is promoted to long double [...].
1483 if (!getLangOptions().CPlusPlus &&
1484 (FromBuiltin->getKind() == BuiltinType::Float ||
1485 FromBuiltin->getKind() == BuiltinType::Double) &&
1486 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1487 return true;
1488 }
1489
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001490 return false;
1491}
1492
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001493/// \brief Determine if a conversion is a complex promotion.
1494///
1495/// A complex promotion is defined as a complex -> complex conversion
1496/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001497/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001498bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001499 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001500 if (!FromComplex)
1501 return false;
1502
John McCall183700f2009-09-21 23:43:11 +00001503 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001504 if (!ToComplex)
1505 return false;
1506
1507 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001508 ToComplex->getElementType()) ||
1509 IsIntegralPromotion(0, FromComplex->getElementType(),
1510 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001511}
1512
Douglas Gregorcb7de522008-11-26 23:31:11 +00001513/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1514/// the pointer type FromPtr to a pointer to type ToPointee, with the
1515/// same type qualifiers as FromPtr has on its pointee type. ToType,
1516/// if non-empty, will be a pointer to ToType that may or may not have
1517/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001518///
Mike Stump1eb44332009-09-09 15:08:12 +00001519static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001520BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001521 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001522 ASTContext &Context,
1523 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001524 assert((FromPtr->getTypeClass() == Type::Pointer ||
1525 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1526 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001527
John McCallf85e1932011-06-15 23:02:42 +00001528 /// Conversions to 'id' subsume cv-qualifier conversions.
1529 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001530 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001531
1532 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001533 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001534 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001535 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001536
John McCallf85e1932011-06-15 23:02:42 +00001537 if (StripObjCLifetime)
1538 Quals.removeObjCLifetime();
1539
Mike Stump1eb44332009-09-09 15:08:12 +00001540 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001541 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001542 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001543 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001544 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001545
1546 // Build a pointer to ToPointee. It has the right qualifiers
1547 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001548 if (isa<ObjCObjectPointerType>(ToType))
1549 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001550 return Context.getPointerType(ToPointee);
1551 }
1552
1553 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001554 QualType QualifiedCanonToPointee
1555 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001556
Douglas Gregorda80f742010-12-01 21:43:58 +00001557 if (isa<ObjCObjectPointerType>(ToType))
1558 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1559 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001560}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001561
Mike Stump1eb44332009-09-09 15:08:12 +00001562static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001563 bool InOverloadResolution,
1564 ASTContext &Context) {
1565 // Handle value-dependent integral null pointer constants correctly.
1566 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1567 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001568 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001569 return !InOverloadResolution;
1570
Douglas Gregorce940492009-09-25 04:25:58 +00001571 return Expr->isNullPointerConstant(Context,
1572 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1573 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001574}
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001576/// IsPointerConversion - Determines whether the conversion of the
1577/// expression From, which has the (possibly adjusted) type FromType,
1578/// can be converted to the type ToType via a pointer conversion (C++
1579/// 4.10). If so, returns true and places the converted type (that
1580/// might differ from ToType in its cv-qualifiers at some level) into
1581/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001582///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001583/// This routine also supports conversions to and from block pointers
1584/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1585/// pointers to interfaces. FIXME: Once we've determined the
1586/// appropriate overloading rules for Objective-C, we may want to
1587/// split the Objective-C checks into a different routine; however,
1588/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001589/// conversions, so for now they live here. IncompatibleObjC will be
1590/// set if the conversion is an allowed Objective-C conversion that
1591/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001592bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001593 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001594 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001595 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001596 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001597 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1598 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001599 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001600
Mike Stump1eb44332009-09-09 15:08:12 +00001601 // Conversion from a null pointer constant to any Objective-C pointer type.
1602 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001603 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001604 ConvertedType = ToType;
1605 return true;
1606 }
1607
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001608 // Blocks: Block pointers can be converted to void*.
1609 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001610 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001611 ConvertedType = ToType;
1612 return true;
1613 }
1614 // Blocks: A null pointer constant can be converted to a block
1615 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001616 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001617 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001618 ConvertedType = ToType;
1619 return true;
1620 }
1621
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001622 // If the left-hand-side is nullptr_t, the right side can be a null
1623 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001624 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001625 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001626 ConvertedType = ToType;
1627 return true;
1628 }
1629
Ted Kremenek6217b802009-07-29 21:53:49 +00001630 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001631 if (!ToTypePtr)
1632 return false;
1633
1634 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001635 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001636 ConvertedType = ToType;
1637 return true;
1638 }
Sebastian Redl07779722008-10-31 14:43:28 +00001639
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001640 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001641 // , including objective-c pointers.
1642 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001643 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1644 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001645 ConvertedType = BuildSimilarlyQualifiedPointerType(
1646 FromType->getAs<ObjCObjectPointerType>(),
1647 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001648 ToType, Context);
1649 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001650 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001651 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001652 if (!FromTypePtr)
1653 return false;
1654
1655 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001656
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001657 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001658 // pointer conversion, so don't do all of the work below.
1659 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1660 return false;
1661
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001662 // An rvalue of type "pointer to cv T," where T is an object type,
1663 // can be converted to an rvalue of type "pointer to cv void" (C++
1664 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001665 if (FromPointeeType->isIncompleteOrObjectType() &&
1666 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001667 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001668 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00001669 ToType, Context,
1670 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001671 return true;
1672 }
1673
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001674 // MSVC allows implicit function to void* type conversion.
Francois Pichet62ec1f22011-09-17 17:15:52 +00001675 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001676 ToPointeeType->isVoidType()) {
1677 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1678 ToPointeeType,
1679 ToType, Context);
1680 return true;
1681 }
1682
Douglas Gregorf9201e02009-02-11 23:02:49 +00001683 // When we're overloading in C, we allow a special kind of pointer
1684 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001685 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001686 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001687 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001688 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001689 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001690 return true;
1691 }
1692
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001693 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001694 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001695 // An rvalue of type "pointer to cv D," where D is a class type,
1696 // can be converted to an rvalue of type "pointer to cv B," where
1697 // B is a base class (clause 10) of D. If B is an inaccessible
1698 // (clause 11) or ambiguous (10.2) base class of D, a program that
1699 // necessitates this conversion is ill-formed. The result of the
1700 // conversion is a pointer to the base class sub-object of the
1701 // derived class object. The null pointer value is converted to
1702 // the null pointer value of the destination type.
1703 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001704 // Note that we do not check for ambiguity or inaccessibility
1705 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001706 if (getLangOptions().CPlusPlus &&
1707 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001708 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001709 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001710 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001711 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001712 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001713 ToType, Context);
1714 return true;
1715 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001716
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00001717 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1718 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1719 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1720 ToPointeeType,
1721 ToType, Context);
1722 return true;
1723 }
1724
Douglas Gregorc7887512008-12-19 19:13:09 +00001725 return false;
1726}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001727
1728/// \brief Adopt the given qualifiers for the given type.
1729static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1730 Qualifiers TQs = T.getQualifiers();
1731
1732 // Check whether qualifiers already match.
1733 if (TQs == Qs)
1734 return T;
1735
1736 if (Qs.compatiblyIncludes(TQs))
1737 return Context.getQualifiedType(T, Qs);
1738
1739 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1740}
Douglas Gregorc7887512008-12-19 19:13:09 +00001741
1742/// isObjCPointerConversion - Determines whether this is an
1743/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1744/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001745bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001746 QualType& ConvertedType,
1747 bool &IncompatibleObjC) {
1748 if (!getLangOptions().ObjC1)
1749 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001750
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001751 // The set of qualifiers on the type we're converting from.
1752 Qualifiers FromQualifiers = FromType.getQualifiers();
1753
Steve Naroff14108da2009-07-10 23:34:53 +00001754 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00001755 const ObjCObjectPointerType* ToObjCPtr =
1756 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001757 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001758 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001759
Steve Naroff14108da2009-07-10 23:34:53 +00001760 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001761 // If the pointee types are the same (ignoring qualifications),
1762 // then this is not a pointer conversion.
1763 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1764 FromObjCPtr->getPointeeType()))
1765 return false;
1766
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001767 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00001768 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001769 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001770 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001771 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001772 return true;
1773 }
1774 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001775 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001776 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001777 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001778 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001779 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001780 return true;
1781 }
1782 // Objective C++: We're able to convert from a pointer to an
1783 // interface to a pointer to a different interface.
1784 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001785 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1786 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1787 if (getLangOptions().CPlusPlus && LHS && RHS &&
1788 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1789 FromObjCPtr->getPointeeType()))
1790 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001791 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00001792 ToObjCPtr->getPointeeType(),
1793 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001794 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001795 return true;
1796 }
1797
1798 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1799 // Okay: this is some kind of implicit downcast of Objective-C
1800 // interfaces, which is permitted. However, we're going to
1801 // complain about it.
1802 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001803 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00001804 ToObjCPtr->getPointeeType(),
1805 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001806 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001807 return true;
1808 }
Mike Stump1eb44332009-09-09 15:08:12 +00001809 }
Steve Naroff14108da2009-07-10 23:34:53 +00001810 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001811 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001812 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001813 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001814 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001815 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001816 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001817 // to a block pointer type.
1818 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001819 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001820 return true;
1821 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001822 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001823 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001824 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001825 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001826 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001827 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001828 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001829 return true;
1830 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001831 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001832 return false;
1833
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001834 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001835 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001836 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00001837 else if (const BlockPointerType *FromBlockPtr =
1838 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001839 FromPointeeType = FromBlockPtr->getPointeeType();
1840 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001841 return false;
1842
Douglas Gregorc7887512008-12-19 19:13:09 +00001843 // If we have pointers to pointers, recursively check whether this
1844 // is an Objective-C conversion.
1845 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1846 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1847 IncompatibleObjC)) {
1848 // We always complain about this conversion.
1849 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00001850 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001851 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00001852 return true;
1853 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001854 // Allow conversion of pointee being objective-c pointer to another one;
1855 // as in I* to id.
1856 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1857 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1858 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1859 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00001860
Douglas Gregorda80f742010-12-01 21:43:58 +00001861 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001862 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001863 return true;
1864 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001865
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001866 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001867 // differences in the argument and result types are in Objective-C
1868 // pointer conversions. If so, we permit the conversion (but
1869 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001870 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001871 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001872 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001873 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001874 if (FromFunctionType && ToFunctionType) {
1875 // If the function types are exactly the same, this isn't an
1876 // Objective-C pointer conversion.
1877 if (Context.getCanonicalType(FromPointeeType)
1878 == Context.getCanonicalType(ToPointeeType))
1879 return false;
1880
1881 // Perform the quick checks that will tell us whether these
1882 // function types are obviously different.
1883 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1884 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1885 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1886 return false;
1887
1888 bool HasObjCConversion = false;
1889 if (Context.getCanonicalType(FromFunctionType->getResultType())
1890 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1891 // Okay, the types match exactly. Nothing to do.
1892 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1893 ToFunctionType->getResultType(),
1894 ConvertedType, IncompatibleObjC)) {
1895 // Okay, we have an Objective-C pointer conversion.
1896 HasObjCConversion = true;
1897 } else {
1898 // Function types are too different. Abort.
1899 return false;
1900 }
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Douglas Gregorc7887512008-12-19 19:13:09 +00001902 // Check argument types.
1903 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1904 ArgIdx != NumArgs; ++ArgIdx) {
1905 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1906 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1907 if (Context.getCanonicalType(FromArgType)
1908 == Context.getCanonicalType(ToArgType)) {
1909 // Okay, the types match exactly. Nothing to do.
1910 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1911 ConvertedType, IncompatibleObjC)) {
1912 // Okay, we have an Objective-C pointer conversion.
1913 HasObjCConversion = true;
1914 } else {
1915 // Argument types are too different. Abort.
1916 return false;
1917 }
1918 }
1919
1920 if (HasObjCConversion) {
1921 // We had an Objective-C conversion. Allow this pointer
1922 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001923 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00001924 IncompatibleObjC = true;
1925 return true;
1926 }
1927 }
1928
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001929 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001930}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001931
John McCallf85e1932011-06-15 23:02:42 +00001932/// \brief Determine whether this is an Objective-C writeback conversion,
1933/// used for parameter passing when performing automatic reference counting.
1934///
1935/// \param FromType The type we're converting form.
1936///
1937/// \param ToType The type we're converting to.
1938///
1939/// \param ConvertedType The type that will be produced after applying
1940/// this conversion.
1941bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
1942 QualType &ConvertedType) {
1943 if (!getLangOptions().ObjCAutoRefCount ||
1944 Context.hasSameUnqualifiedType(FromType, ToType))
1945 return false;
1946
1947 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
1948 QualType ToPointee;
1949 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
1950 ToPointee = ToPointer->getPointeeType();
1951 else
1952 return false;
1953
1954 Qualifiers ToQuals = ToPointee.getQualifiers();
1955 if (!ToPointee->isObjCLifetimeType() ||
1956 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
1957 !ToQuals.withoutObjCGLifetime().empty())
1958 return false;
1959
1960 // Argument must be a pointer to __strong to __weak.
1961 QualType FromPointee;
1962 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
1963 FromPointee = FromPointer->getPointeeType();
1964 else
1965 return false;
1966
1967 Qualifiers FromQuals = FromPointee.getQualifiers();
1968 if (!FromPointee->isObjCLifetimeType() ||
1969 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
1970 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
1971 return false;
1972
1973 // Make sure that we have compatible qualifiers.
1974 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
1975 if (!ToQuals.compatiblyIncludes(FromQuals))
1976 return false;
1977
1978 // Remove qualifiers from the pointee type we're converting from; they
1979 // aren't used in the compatibility check belong, and we'll be adding back
1980 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
1981 FromPointee = FromPointee.getUnqualifiedType();
1982
1983 // The unqualified form of the pointee types must be compatible.
1984 ToPointee = ToPointee.getUnqualifiedType();
1985 bool IncompatibleObjC;
1986 if (Context.typesAreCompatible(FromPointee, ToPointee))
1987 FromPointee = ToPointee;
1988 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
1989 IncompatibleObjC))
1990 return false;
1991
1992 /// \brief Construct the type we're converting to, which is a pointer to
1993 /// __autoreleasing pointee.
1994 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
1995 ConvertedType = Context.getPointerType(FromPointee);
1996 return true;
1997}
1998
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001999bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2000 QualType& ConvertedType) {
2001 QualType ToPointeeType;
2002 if (const BlockPointerType *ToBlockPtr =
2003 ToType->getAs<BlockPointerType>())
2004 ToPointeeType = ToBlockPtr->getPointeeType();
2005 else
2006 return false;
2007
2008 QualType FromPointeeType;
2009 if (const BlockPointerType *FromBlockPtr =
2010 FromType->getAs<BlockPointerType>())
2011 FromPointeeType = FromBlockPtr->getPointeeType();
2012 else
2013 return false;
2014 // We have pointer to blocks, check whether the only
2015 // differences in the argument and result types are in Objective-C
2016 // pointer conversions. If so, we permit the conversion.
2017
2018 const FunctionProtoType *FromFunctionType
2019 = FromPointeeType->getAs<FunctionProtoType>();
2020 const FunctionProtoType *ToFunctionType
2021 = ToPointeeType->getAs<FunctionProtoType>();
2022
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002023 if (!FromFunctionType || !ToFunctionType)
2024 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002025
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002026 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002027 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002028
2029 // Perform the quick checks that will tell us whether these
2030 // function types are obviously different.
2031 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2032 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2033 return false;
2034
2035 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2036 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2037 if (FromEInfo != ToEInfo)
2038 return false;
2039
2040 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002041 if (Context.hasSameType(FromFunctionType->getResultType(),
2042 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002043 // Okay, the types match exactly. Nothing to do.
2044 } else {
2045 QualType RHS = FromFunctionType->getResultType();
2046 QualType LHS = ToFunctionType->getResultType();
2047 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2048 !RHS.hasQualifiers() && LHS.hasQualifiers())
2049 LHS = LHS.getUnqualifiedType();
2050
2051 if (Context.hasSameType(RHS,LHS)) {
2052 // OK exact match.
2053 } else if (isObjCPointerConversion(RHS, LHS,
2054 ConvertedType, IncompatibleObjC)) {
2055 if (IncompatibleObjC)
2056 return false;
2057 // Okay, we have an Objective-C pointer conversion.
2058 }
2059 else
2060 return false;
2061 }
2062
2063 // Check argument types.
2064 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2065 ArgIdx != NumArgs; ++ArgIdx) {
2066 IncompatibleObjC = false;
2067 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2068 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2069 if (Context.hasSameType(FromArgType, ToArgType)) {
2070 // Okay, the types match exactly. Nothing to do.
2071 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2072 ConvertedType, IncompatibleObjC)) {
2073 if (IncompatibleObjC)
2074 return false;
2075 // Okay, we have an Objective-C pointer conversion.
2076 } else
2077 // Argument types are too different. Abort.
2078 return false;
2079 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002080 if (LangOpts.ObjCAutoRefCount &&
2081 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2082 ToFunctionType))
2083 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002084
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002085 ConvertedType = ToType;
2086 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002087}
2088
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002089/// FunctionArgTypesAreEqual - This routine checks two function proto types
2090/// for equlity of their argument types. Caller has already checked that
2091/// they have same number of arguments. This routine assumes that Objective-C
2092/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002093bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCallf4c73712011-01-19 06:33:43 +00002094 const FunctionProtoType *NewType) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002095 if (!getLangOptions().ObjC1)
2096 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
2097 NewType->arg_type_begin());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002098
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002099 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2100 N = NewType->arg_type_begin(),
2101 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2102 QualType ToType = (*O);
2103 QualType FromType = (*N);
2104 if (ToType != FromType) {
2105 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2106 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002107 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2108 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2109 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2110 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002111 continue;
2112 }
John McCallc12c5bb2010-05-15 11:32:37 +00002113 else if (const ObjCObjectPointerType *PTTo =
2114 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002115 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002116 FromType->getAs<ObjCObjectPointerType>())
2117 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2118 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002119 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002120 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002121 }
2122 }
2123 return true;
2124}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002125
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002126/// CheckPointerConversion - Check the pointer conversion from the
2127/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002128/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002129/// conversions for which IsPointerConversion has already returned
2130/// true. It returns true and produces a diagnostic if there was an
2131/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002132bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002133 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002134 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002135 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002136 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002137 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002138
John McCalldaa8e4e2010-11-15 09:13:47 +00002139 Kind = CK_BitCast;
2140
Chandler Carruth88f0aed2011-04-09 07:32:05 +00002141 if (!IsCStyleOrFunctionalCast &&
2142 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2143 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2144 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruthb6006692011-04-09 07:48:17 +00002145 PDiag(diag::warn_impcast_bool_to_null_pointer)
2146 << ToType << From->getSourceRange());
Douglas Gregord7a95972010-06-08 17:35:15 +00002147
John McCall1d9b3b22011-09-09 05:25:32 +00002148 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2149 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002150 QualType FromPointeeType = FromPtrType->getPointeeType(),
2151 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002152
Douglas Gregor5fccd362010-03-03 23:55:11 +00002153 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2154 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002155 // We must have a derived-to-base conversion. Check an
2156 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002157 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2158 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002159 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002160 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002161 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002162
Anders Carlsson61faec12009-09-12 04:46:44 +00002163 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002164 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002165 }
2166 }
John McCall1d9b3b22011-09-09 05:25:32 +00002167 } else if (const ObjCObjectPointerType *ToPtrType =
2168 ToType->getAs<ObjCObjectPointerType>()) {
2169 if (const ObjCObjectPointerType *FromPtrType =
2170 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002171 // Objective-C++ conversions are always okay.
2172 // FIXME: We should have a different class of conversions for the
2173 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002174 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002175 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002176 } else if (FromType->isBlockPointerType()) {
2177 Kind = CK_BlockPointerToObjCPointerCast;
2178 } else {
2179 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002180 }
John McCall1d9b3b22011-09-09 05:25:32 +00002181 } else if (ToType->isBlockPointerType()) {
2182 if (!FromType->isBlockPointerType())
2183 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002184 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002185
2186 // We shouldn't fall into this case unless it's valid for other
2187 // reasons.
2188 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2189 Kind = CK_NullToPointer;
2190
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002191 return false;
2192}
2193
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002194/// IsMemberPointerConversion - Determines whether the conversion of the
2195/// expression From, which has the (possibly adjusted) type FromType, can be
2196/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2197/// If so, returns true and places the converted type (that might differ from
2198/// ToType in its cv-qualifiers at some level) into ConvertedType.
2199bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002200 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002201 bool InOverloadResolution,
2202 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002203 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002204 if (!ToTypePtr)
2205 return false;
2206
2207 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002208 if (From->isNullPointerConstant(Context,
2209 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2210 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002211 ConvertedType = ToType;
2212 return true;
2213 }
2214
2215 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002216 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002217 if (!FromTypePtr)
2218 return false;
2219
2220 // A pointer to member of B can be converted to a pointer to member of D,
2221 // where D is derived from B (C++ 4.11p2).
2222 QualType FromClass(FromTypePtr->getClass(), 0);
2223 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002224
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002225 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2226 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2227 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002228 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2229 ToClass.getTypePtr());
2230 return true;
2231 }
2232
2233 return false;
2234}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002235
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002236/// CheckMemberPointerConversion - Check the member pointer conversion from the
2237/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002238/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002239/// for which IsMemberPointerConversion has already returned true. It returns
2240/// true and produces a diagnostic if there was an error, or returns false
2241/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002242bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002243 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002244 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002245 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002246 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002247 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002248 if (!FromPtrType) {
2249 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002250 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002251 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002252 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002253 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002254 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002255 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002256
Ted Kremenek6217b802009-07-29 21:53:49 +00002257 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002258 assert(ToPtrType && "No member pointer cast has a target type "
2259 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002260
Sebastian Redl21593ac2009-01-28 18:33:18 +00002261 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2262 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002263
Sebastian Redl21593ac2009-01-28 18:33:18 +00002264 // FIXME: What about dependent types?
2265 assert(FromClass->isRecordType() && "Pointer into non-class.");
2266 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002267
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002268 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002269 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002270 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2271 assert(DerivationOkay &&
2272 "Should not have been called if derivation isn't OK.");
2273 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002274
Sebastian Redl21593ac2009-01-28 18:33:18 +00002275 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2276 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002277 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2278 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2279 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2280 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002281 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002282
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002283 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002284 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2285 << FromClass << ToClass << QualType(VBase, 0)
2286 << From->getSourceRange();
2287 return true;
2288 }
2289
John McCall6b2accb2010-02-10 09:31:12 +00002290 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002291 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2292 Paths.front(),
2293 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002294
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002295 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002296 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002297 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002298 return false;
2299}
2300
Douglas Gregor98cd5992008-10-21 23:43:52 +00002301/// IsQualificationConversion - Determines whether the conversion from
2302/// an rvalue of type FromType to ToType is a qualification conversion
2303/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002304///
2305/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2306/// when the qualification conversion involves a change in the Objective-C
2307/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002308bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002309Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002310 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002311 FromType = Context.getCanonicalType(FromType);
2312 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002313 ObjCLifetimeConversion = false;
2314
Douglas Gregor98cd5992008-10-21 23:43:52 +00002315 // If FromType and ToType are the same type, this is not a
2316 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002317 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002318 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002319
Douglas Gregor98cd5992008-10-21 23:43:52 +00002320 // (C++ 4.4p4):
2321 // A conversion can add cv-qualifiers at levels other than the first
2322 // in multi-level pointers, subject to the following rules: [...]
2323 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002324 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002325 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002326 // Within each iteration of the loop, we check the qualifiers to
2327 // determine if this still looks like a qualification
2328 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002329 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002330 // until there are no more pointers or pointers-to-members left to
2331 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002332 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002333
Douglas Gregor621c92a2011-04-25 18:40:17 +00002334 Qualifiers FromQuals = FromType.getQualifiers();
2335 Qualifiers ToQuals = ToType.getQualifiers();
2336
John McCallf85e1932011-06-15 23:02:42 +00002337 // Objective-C ARC:
2338 // Check Objective-C lifetime conversions.
2339 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2340 UnwrappedAnyPointer) {
2341 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2342 ObjCLifetimeConversion = true;
2343 FromQuals.removeObjCLifetime();
2344 ToQuals.removeObjCLifetime();
2345 } else {
2346 // Qualification conversions cannot cast between different
2347 // Objective-C lifetime qualifiers.
2348 return false;
2349 }
2350 }
2351
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002352 // Allow addition/removal of GC attributes but not changing GC attributes.
2353 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2354 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2355 FromQuals.removeObjCGCAttr();
2356 ToQuals.removeObjCGCAttr();
2357 }
2358
Douglas Gregor98cd5992008-10-21 23:43:52 +00002359 // -- for every j > 0, if const is in cv 1,j then const is in cv
2360 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002361 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002362 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Douglas Gregor98cd5992008-10-21 23:43:52 +00002364 // -- if the cv 1,j and cv 2,j are different, then const is in
2365 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002366 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002367 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002368 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002369
Douglas Gregor98cd5992008-10-21 23:43:52 +00002370 // Keep track of whether all prior cv-qualifiers in the "to" type
2371 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002372 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002373 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002374 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002375
2376 // We are left with FromType and ToType being the pointee types
2377 // after unwrapping the original FromType and ToType the same number
2378 // of types. If we unwrapped any pointers, and if FromType and
2379 // ToType have the same unqualified type (since we checked
2380 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002381 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002382}
2383
Douglas Gregor734d9862009-01-30 23:27:23 +00002384/// Determines whether there is a user-defined conversion sequence
2385/// (C++ [over.ics.user]) that converts expression From to the type
2386/// ToType. If such a conversion exists, User will contain the
2387/// user-defined conversion sequence that performs such a conversion
2388/// and this routine will return true. Otherwise, this routine returns
2389/// false and User is unspecified.
2390///
Douglas Gregor734d9862009-01-30 23:27:23 +00002391/// \param AllowExplicit true if the conversion should consider C++0x
2392/// "explicit" conversion functions as well as non-explicit conversion
2393/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002394static OverloadingResult
2395IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2396 UserDefinedConversionSequence& User,
2397 OverloadCandidateSet& CandidateSet,
2398 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002399 // Whether we will only visit constructors.
2400 bool ConstructorsOnly = false;
2401
2402 // If the type we are conversion to is a class type, enumerate its
2403 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002404 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002405 // C++ [over.match.ctor]p1:
2406 // When objects of class type are direct-initialized (8.5), or
2407 // copy-initialized from an expression of the same or a
2408 // derived class type (8.5), overload resolution selects the
2409 // constructor. [...] For copy-initialization, the candidate
2410 // functions are all the converting constructors (12.3.1) of
2411 // that class. The argument list is the expression-list within
2412 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002413 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002414 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002415 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002416 ConstructorsOnly = true;
2417
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002418 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2419 // RequireCompleteType may have returned true due to some invalid decl
2420 // during template instantiation, but ToType may be complete enough now
2421 // to try to recover.
2422 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002423 // We're not going to find any constructors.
2424 } else if (CXXRecordDecl *ToRecordDecl
2425 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002426 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002427 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002428 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002429 NamedDecl *D = *Con;
2430 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2431
Douglas Gregordec06662009-08-21 18:42:58 +00002432 // Find the constructor (which may be a template).
2433 CXXConstructorDecl *Constructor = 0;
2434 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002435 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002436 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002437 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002438 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2439 else
John McCall9aa472c2010-03-19 07:35:19 +00002440 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002441
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00002442 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00002443 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00002444 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002445 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2446 /*ExplicitArgs*/ 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002447 &From, 1, CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002448 /*SuppressUserConversions=*/
2449 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002450 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002451 // Allow one user-defined conversion when user specifies a
2452 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002453 S.AddOverloadCandidate(Constructor, FoundDecl,
2454 &From, 1, CandidateSet,
2455 /*SuppressUserConversions=*/
2456 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002457 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002458 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002459 }
2460 }
2461
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002462 // Enumerate conversion functions, if we're allowed to.
2463 if (ConstructorsOnly) {
John McCall120d63c2010-08-24 20:38:10 +00002464 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2465 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002466 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002467 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002468 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002469 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002470 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2471 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002472 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002473 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002474 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002475 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002476 DeclAccessPair FoundDecl = I.getPair();
2477 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002478 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2479 if (isa<UsingShadowDecl>(D))
2480 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2481
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002482 CXXConversionDecl *Conv;
2483 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002484 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2485 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002486 else
John McCall32daa422010-03-31 01:36:47 +00002487 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002488
2489 if (AllowExplicit || !Conv->isExplicit()) {
2490 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002491 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2492 ActingContext, From, ToType,
2493 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002494 else
John McCall120d63c2010-08-24 20:38:10 +00002495 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2496 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002497 }
2498 }
2499 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002500 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002501
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002502 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2503
Douglas Gregor60d62c22008-10-31 16:23:19 +00002504 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002505 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002506 case OR_Success:
2507 // Record the standard conversion we used and the conversion function.
2508 if (CXXConstructorDecl *Constructor
2509 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth25ca4212011-02-25 19:41:05 +00002510 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2511
John McCall120d63c2010-08-24 20:38:10 +00002512 // C++ [over.ics.user]p1:
2513 // If the user-defined conversion is specified by a
2514 // constructor (12.3.1), the initial standard conversion
2515 // sequence converts the source type to the type required by
2516 // the argument of the constructor.
2517 //
2518 QualType ThisType = Constructor->getThisType(S.Context);
2519 if (Best->Conversions[0].isEllipsis())
2520 User.EllipsisConversion = true;
2521 else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002522 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002523 User.EllipsisConversion = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002524 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002525 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00002526 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00002527 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00002528 User.After.setAsIdentityConversion();
2529 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2530 User.After.setAllToTypes(ToType);
2531 return OR_Success;
2532 } else if (CXXConversionDecl *Conversion
2533 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth25ca4212011-02-25 19:41:05 +00002534 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2535
John McCall120d63c2010-08-24 20:38:10 +00002536 // C++ [over.ics.user]p1:
2537 //
2538 // [...] If the user-defined conversion is specified by a
2539 // conversion function (12.3.2), the initial standard
2540 // conversion sequence converts the source type to the
2541 // implicit object parameter of the conversion function.
2542 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002543 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00002544 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00002545 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00002546 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002547
John McCall120d63c2010-08-24 20:38:10 +00002548 // C++ [over.ics.user]p2:
2549 // The second standard conversion sequence converts the
2550 // result of the user-defined conversion to the target type
2551 // for the sequence. Since an implicit conversion sequence
2552 // is an initialization, the special rules for
2553 // initialization by user-defined conversion apply when
2554 // selecting the best user-defined conversion for a
2555 // user-defined conversion sequence (see 13.3.3 and
2556 // 13.3.3.1).
2557 User.After = Best->FinalConversion;
2558 return OR_Success;
2559 } else {
2560 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002561 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002562 }
2563
John McCall120d63c2010-08-24 20:38:10 +00002564 case OR_No_Viable_Function:
2565 return OR_No_Viable_Function;
2566 case OR_Deleted:
2567 // No conversion here! We're done.
2568 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002569
John McCall120d63c2010-08-24 20:38:10 +00002570 case OR_Ambiguous:
2571 return OR_Ambiguous;
2572 }
2573
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002574 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002575}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002576
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002577bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002578Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002579 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002580 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002581 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00002582 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002583 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002584 if (OvResult == OR_Ambiguous)
2585 Diag(From->getSourceRange().getBegin(),
2586 diag::err_typecheck_ambiguous_condition)
2587 << From->getType() << ToType << From->getSourceRange();
2588 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2589 Diag(From->getSourceRange().getBegin(),
2590 diag::err_typecheck_nonviable_condition)
2591 << From->getType() << ToType << From->getSourceRange();
2592 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002593 return false;
John McCall120d63c2010-08-24 20:38:10 +00002594 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002595 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002596}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002597
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002598/// CompareImplicitConversionSequences - Compare two implicit
2599/// conversion sequences to determine whether one is better than the
2600/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00002601static ImplicitConversionSequence::CompareKind
2602CompareImplicitConversionSequences(Sema &S,
2603 const ImplicitConversionSequence& ICS1,
2604 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002605{
2606 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2607 // conversion sequences (as defined in 13.3.3.1)
2608 // -- a standard conversion sequence (13.3.3.1.1) is a better
2609 // conversion sequence than a user-defined conversion sequence or
2610 // an ellipsis conversion sequence, and
2611 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2612 // conversion sequence than an ellipsis conversion sequence
2613 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002614 //
John McCall1d318332010-01-12 00:44:57 +00002615 // C++0x [over.best.ics]p10:
2616 // For the purpose of ranking implicit conversion sequences as
2617 // described in 13.3.3.2, the ambiguous conversion sequence is
2618 // treated as a user-defined sequence that is indistinguishable
2619 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002620 if (ICS1.getKindRank() < ICS2.getKindRank())
2621 return ImplicitConversionSequence::Better;
2622 else if (ICS2.getKindRank() < ICS1.getKindRank())
2623 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002624
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002625 // The following checks require both conversion sequences to be of
2626 // the same kind.
2627 if (ICS1.getKind() != ICS2.getKind())
2628 return ImplicitConversionSequence::Indistinguishable;
2629
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002630 // Two implicit conversion sequences of the same form are
2631 // indistinguishable conversion sequences unless one of the
2632 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002633 if (ICS1.isStandard())
John McCall120d63c2010-08-24 20:38:10 +00002634 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002635 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002636 // User-defined conversion sequence U1 is a better conversion
2637 // sequence than another user-defined conversion sequence U2 if
2638 // they contain the same user-defined conversion function or
2639 // constructor and if the second standard conversion sequence of
2640 // U1 is better than the second standard conversion sequence of
2641 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002642 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002643 ICS2.UserDefined.ConversionFunction)
John McCall120d63c2010-08-24 20:38:10 +00002644 return CompareStandardConversionSequences(S,
2645 ICS1.UserDefined.After,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002646 ICS2.UserDefined.After);
2647 }
2648
2649 return ImplicitConversionSequence::Indistinguishable;
2650}
2651
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002652static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2653 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2654 Qualifiers Quals;
2655 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002656 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002657 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002658
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002659 return Context.hasSameUnqualifiedType(T1, T2);
2660}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002661
Douglas Gregorad323a82010-01-27 03:51:04 +00002662// Per 13.3.3.2p3, compare the given standard conversion sequences to
2663// determine if one is a proper subset of the other.
2664static ImplicitConversionSequence::CompareKind
2665compareStandardConversionSubsets(ASTContext &Context,
2666 const StandardConversionSequence& SCS1,
2667 const StandardConversionSequence& SCS2) {
2668 ImplicitConversionSequence::CompareKind Result
2669 = ImplicitConversionSequence::Indistinguishable;
2670
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002671 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002672 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00002673 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2674 return ImplicitConversionSequence::Better;
2675 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2676 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002677
Douglas Gregorad323a82010-01-27 03:51:04 +00002678 if (SCS1.Second != SCS2.Second) {
2679 if (SCS1.Second == ICK_Identity)
2680 Result = ImplicitConversionSequence::Better;
2681 else if (SCS2.Second == ICK_Identity)
2682 Result = ImplicitConversionSequence::Worse;
2683 else
2684 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002685 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002686 return ImplicitConversionSequence::Indistinguishable;
2687
2688 if (SCS1.Third == SCS2.Third) {
2689 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2690 : ImplicitConversionSequence::Indistinguishable;
2691 }
2692
2693 if (SCS1.Third == ICK_Identity)
2694 return Result == ImplicitConversionSequence::Worse
2695 ? ImplicitConversionSequence::Indistinguishable
2696 : ImplicitConversionSequence::Better;
2697
2698 if (SCS2.Third == ICK_Identity)
2699 return Result == ImplicitConversionSequence::Better
2700 ? ImplicitConversionSequence::Indistinguishable
2701 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002702
Douglas Gregorad323a82010-01-27 03:51:04 +00002703 return ImplicitConversionSequence::Indistinguishable;
2704}
2705
Douglas Gregor440a4832011-01-26 14:52:12 +00002706/// \brief Determine whether one of the given reference bindings is better
2707/// than the other based on what kind of bindings they are.
2708static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2709 const StandardConversionSequence &SCS2) {
2710 // C++0x [over.ics.rank]p3b4:
2711 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2712 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002713 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00002714 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002715 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00002716 // reference*.
2717 //
2718 // FIXME: Rvalue references. We're going rogue with the above edits,
2719 // because the semantics in the current C++0x working paper (N3225 at the
2720 // time of this writing) break the standard definition of std::forward
2721 // and std::reference_wrapper when dealing with references to functions.
2722 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00002723 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2724 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2725 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002726
Douglas Gregor440a4832011-01-26 14:52:12 +00002727 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2728 SCS2.IsLvalueReference) ||
2729 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2730 !SCS2.IsLvalueReference);
2731}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002732
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002733/// CompareStandardConversionSequences - Compare two standard
2734/// conversion sequences to determine whether one is better than the
2735/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00002736static ImplicitConversionSequence::CompareKind
2737CompareStandardConversionSequences(Sema &S,
2738 const StandardConversionSequence& SCS1,
2739 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002740{
2741 // Standard conversion sequence S1 is a better conversion sequence
2742 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2743
2744 // -- S1 is a proper subsequence of S2 (comparing the conversion
2745 // sequences in the canonical form defined by 13.3.3.1.1,
2746 // excluding any Lvalue Transformation; the identity conversion
2747 // sequence is considered to be a subsequence of any
2748 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002749 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00002750 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00002751 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002752
2753 // -- the rank of S1 is better than the rank of S2 (by the rules
2754 // defined below), or, if not that,
2755 ImplicitConversionRank Rank1 = SCS1.getRank();
2756 ImplicitConversionRank Rank2 = SCS2.getRank();
2757 if (Rank1 < Rank2)
2758 return ImplicitConversionSequence::Better;
2759 else if (Rank2 < Rank1)
2760 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002761
Douglas Gregor57373262008-10-22 14:17:15 +00002762 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2763 // are indistinguishable unless one of the following rules
2764 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002765
Douglas Gregor57373262008-10-22 14:17:15 +00002766 // A conversion that is not a conversion of a pointer, or
2767 // pointer to member, to bool is better than another conversion
2768 // that is such a conversion.
2769 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2770 return SCS2.isPointerConversionToBool()
2771 ? ImplicitConversionSequence::Better
2772 : ImplicitConversionSequence::Worse;
2773
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002774 // C++ [over.ics.rank]p4b2:
2775 //
2776 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002777 // conversion of B* to A* is better than conversion of B* to
2778 // void*, and conversion of A* to void* is better than conversion
2779 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002780 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002781 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002782 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002783 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002784 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2785 // Exactly one of the conversion sequences is a conversion to
2786 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002787 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2788 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002789 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2790 // Neither conversion sequence converts to a void pointer; compare
2791 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002792 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00002793 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002794 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00002795 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2796 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002797 // Both conversion sequences are conversions to void
2798 // pointers. Compare the source types to determine if there's an
2799 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002800 QualType FromType1 = SCS1.getFromType();
2801 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002802
2803 // Adjust the types we're converting from via the array-to-pointer
2804 // conversion, if we need to.
2805 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002806 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002807 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002808 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002809
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00002810 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2811 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002812
John McCall120d63c2010-08-24 20:38:10 +00002813 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00002814 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002815 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00002816 return ImplicitConversionSequence::Worse;
2817
2818 // Objective-C++: If one interface is more specific than the
2819 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00002820 const ObjCObjectPointerType* FromObjCPtr1
2821 = FromType1->getAs<ObjCObjectPointerType>();
2822 const ObjCObjectPointerType* FromObjCPtr2
2823 = FromType2->getAs<ObjCObjectPointerType>();
2824 if (FromObjCPtr1 && FromObjCPtr2) {
2825 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2826 FromObjCPtr2);
2827 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2828 FromObjCPtr1);
2829 if (AssignLeft != AssignRight) {
2830 return AssignLeft? ImplicitConversionSequence::Better
2831 : ImplicitConversionSequence::Worse;
2832 }
Douglas Gregor01919692009-12-13 21:37:05 +00002833 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002834 }
Douglas Gregor57373262008-10-22 14:17:15 +00002835
2836 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2837 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002838 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00002839 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002840 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002841
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002842 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00002843 // Check for a better reference binding based on the kind of bindings.
2844 if (isBetterReferenceBindingKind(SCS1, SCS2))
2845 return ImplicitConversionSequence::Better;
2846 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2847 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002848
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002849 // C++ [over.ics.rank]p3b4:
2850 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2851 // which the references refer are the same type except for
2852 // top-level cv-qualifiers, and the type to which the reference
2853 // initialized by S2 refers is more cv-qualified than the type
2854 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002855 QualType T1 = SCS1.getToType(2);
2856 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002857 T1 = S.Context.getCanonicalType(T1);
2858 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002859 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002860 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2861 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002862 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00002863 // Objective-C++ ARC: If the references refer to objects with different
2864 // lifetimes, prefer bindings that don't change lifetime.
2865 if (SCS1.ObjCLifetimeConversionBinding !=
2866 SCS2.ObjCLifetimeConversionBinding) {
2867 return SCS1.ObjCLifetimeConversionBinding
2868 ? ImplicitConversionSequence::Worse
2869 : ImplicitConversionSequence::Better;
2870 }
2871
Chandler Carruth6df868e2010-12-12 08:17:55 +00002872 // If the type is an array type, promote the element qualifiers to the
2873 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002874 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002875 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002876 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002877 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002878 if (T2.isMoreQualifiedThan(T1))
2879 return ImplicitConversionSequence::Better;
2880 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00002881 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002882 }
2883 }
Douglas Gregor57373262008-10-22 14:17:15 +00002884
Francois Pichet1c98d622011-09-18 21:37:37 +00002885 // In Microsoft mode, prefer an integral conversion to a
2886 // floating-to-integral conversion if the integral conversion
2887 // is between types of the same size.
2888 // For example:
2889 // void f(float);
2890 // void f(int);
2891 // int main {
2892 // long a;
2893 // f(a);
2894 // }
2895 // Here, MSVC will call f(int) instead of generating a compile error
2896 // as clang will do in standard mode.
2897 if (S.getLangOptions().MicrosoftMode &&
2898 SCS1.Second == ICK_Integral_Conversion &&
2899 SCS2.Second == ICK_Floating_Integral &&
2900 S.Context.getTypeSize(SCS1.getFromType()) ==
2901 S.Context.getTypeSize(SCS1.getToType(2)))
2902 return ImplicitConversionSequence::Better;
2903
Douglas Gregor57373262008-10-22 14:17:15 +00002904 return ImplicitConversionSequence::Indistinguishable;
2905}
2906
2907/// CompareQualificationConversions - Compares two standard conversion
2908/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002909/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2910ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002911CompareQualificationConversions(Sema &S,
2912 const StandardConversionSequence& SCS1,
2913 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002914 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002915 // -- S1 and S2 differ only in their qualification conversion and
2916 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2917 // cv-qualification signature of type T1 is a proper subset of
2918 // the cv-qualification signature of type T2, and S1 is not the
2919 // deprecated string literal array-to-pointer conversion (4.2).
2920 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2921 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2922 return ImplicitConversionSequence::Indistinguishable;
2923
2924 // FIXME: the example in the standard doesn't use a qualification
2925 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002926 QualType T1 = SCS1.getToType(2);
2927 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002928 T1 = S.Context.getCanonicalType(T1);
2929 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002930 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002931 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2932 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002933
2934 // If the types are the same, we won't learn anything by unwrapped
2935 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002936 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002937 return ImplicitConversionSequence::Indistinguishable;
2938
Chandler Carruth28e318c2009-12-29 07:16:59 +00002939 // If the type is an array type, promote the element qualifiers to the type
2940 // for comparison.
2941 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002942 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002943 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002944 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002945
Mike Stump1eb44332009-09-09 15:08:12 +00002946 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002947 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00002948
2949 // Objective-C++ ARC:
2950 // Prefer qualification conversions not involving a change in lifetime
2951 // to qualification conversions that do not change lifetime.
2952 if (SCS1.QualificationIncludesObjCLifetime !=
2953 SCS2.QualificationIncludesObjCLifetime) {
2954 Result = SCS1.QualificationIncludesObjCLifetime
2955 ? ImplicitConversionSequence::Worse
2956 : ImplicitConversionSequence::Better;
2957 }
2958
John McCall120d63c2010-08-24 20:38:10 +00002959 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002960 // Within each iteration of the loop, we check the qualifiers to
2961 // determine if this still looks like a qualification
2962 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002963 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002964 // until there are no more pointers or pointers-to-members left
2965 // to unwrap. This essentially mimics what
2966 // IsQualificationConversion does, but here we're checking for a
2967 // strict subset of qualifiers.
2968 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2969 // The qualifiers are the same, so this doesn't tell us anything
2970 // about how the sequences rank.
2971 ;
2972 else if (T2.isMoreQualifiedThan(T1)) {
2973 // T1 has fewer qualifiers, so it could be the better sequence.
2974 if (Result == ImplicitConversionSequence::Worse)
2975 // Neither has qualifiers that are a subset of the other's
2976 // qualifiers.
2977 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002978
Douglas Gregor57373262008-10-22 14:17:15 +00002979 Result = ImplicitConversionSequence::Better;
2980 } else if (T1.isMoreQualifiedThan(T2)) {
2981 // T2 has fewer qualifiers, so it could be the better sequence.
2982 if (Result == ImplicitConversionSequence::Better)
2983 // Neither has qualifiers that are a subset of the other's
2984 // qualifiers.
2985 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002986
Douglas Gregor57373262008-10-22 14:17:15 +00002987 Result = ImplicitConversionSequence::Worse;
2988 } else {
2989 // Qualifiers are disjoint.
2990 return ImplicitConversionSequence::Indistinguishable;
2991 }
2992
2993 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00002994 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002995 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002996 }
2997
Douglas Gregor57373262008-10-22 14:17:15 +00002998 // Check that the winning standard conversion sequence isn't using
2999 // the deprecated string literal array to pointer conversion.
3000 switch (Result) {
3001 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003002 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003003 Result = ImplicitConversionSequence::Indistinguishable;
3004 break;
3005
3006 case ImplicitConversionSequence::Indistinguishable:
3007 break;
3008
3009 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003010 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003011 Result = ImplicitConversionSequence::Indistinguishable;
3012 break;
3013 }
3014
3015 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003016}
3017
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003018/// CompareDerivedToBaseConversions - Compares two standard conversion
3019/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003020/// various kinds of derived-to-base conversions (C++
3021/// [over.ics.rank]p4b3). As part of these checks, we also look at
3022/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003023ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003024CompareDerivedToBaseConversions(Sema &S,
3025 const StandardConversionSequence& SCS1,
3026 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003027 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003028 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003029 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003030 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003031
3032 // Adjust the types we're converting from via the array-to-pointer
3033 // conversion, if we need to.
3034 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003035 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003036 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003037 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003038
3039 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003040 FromType1 = S.Context.getCanonicalType(FromType1);
3041 ToType1 = S.Context.getCanonicalType(ToType1);
3042 FromType2 = S.Context.getCanonicalType(FromType2);
3043 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003044
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003045 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003046 //
3047 // If class B is derived directly or indirectly from class A and
3048 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003049 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003050 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003051 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003052 SCS2.Second == ICK_Pointer_Conversion &&
3053 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3054 FromType1->isPointerType() && FromType2->isPointerType() &&
3055 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003056 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003057 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003058 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003059 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003060 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003061 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003062 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003063 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003064
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003065 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003066 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003067 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003068 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003069 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003070 return ImplicitConversionSequence::Worse;
3071 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003072
3073 // -- conversion of B* to A* is better than conversion of C* to A*,
3074 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003075 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003076 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003077 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003078 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003079 }
3080 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3081 SCS2.Second == ICK_Pointer_Conversion) {
3082 const ObjCObjectPointerType *FromPtr1
3083 = FromType1->getAs<ObjCObjectPointerType>();
3084 const ObjCObjectPointerType *FromPtr2
3085 = FromType2->getAs<ObjCObjectPointerType>();
3086 const ObjCObjectPointerType *ToPtr1
3087 = ToType1->getAs<ObjCObjectPointerType>();
3088 const ObjCObjectPointerType *ToPtr2
3089 = ToType2->getAs<ObjCObjectPointerType>();
3090
3091 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3092 // Apply the same conversion ranking rules for Objective-C pointer types
3093 // that we do for C++ pointers to class types. However, we employ the
3094 // Objective-C pseudo-subtyping relationship used for assignment of
3095 // Objective-C pointer types.
3096 bool FromAssignLeft
3097 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3098 bool FromAssignRight
3099 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3100 bool ToAssignLeft
3101 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3102 bool ToAssignRight
3103 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3104
3105 // A conversion to an a non-id object pointer type or qualified 'id'
3106 // type is better than a conversion to 'id'.
3107 if (ToPtr1->isObjCIdType() &&
3108 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3109 return ImplicitConversionSequence::Worse;
3110 if (ToPtr2->isObjCIdType() &&
3111 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3112 return ImplicitConversionSequence::Better;
3113
3114 // A conversion to a non-id object pointer type is better than a
3115 // conversion to a qualified 'id' type
3116 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3117 return ImplicitConversionSequence::Worse;
3118 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3119 return ImplicitConversionSequence::Better;
3120
3121 // A conversion to an a non-Class object pointer type or qualified 'Class'
3122 // type is better than a conversion to 'Class'.
3123 if (ToPtr1->isObjCClassType() &&
3124 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3125 return ImplicitConversionSequence::Worse;
3126 if (ToPtr2->isObjCClassType() &&
3127 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3128 return ImplicitConversionSequence::Better;
3129
3130 // A conversion to a non-Class object pointer type is better than a
3131 // conversion to a qualified 'Class' type.
3132 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3133 return ImplicitConversionSequence::Worse;
3134 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3135 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003136
Douglas Gregor395cc372011-01-31 18:51:41 +00003137 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3138 if (S.Context.hasSameType(FromType1, FromType2) &&
3139 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3140 (ToAssignLeft != ToAssignRight))
3141 return ToAssignLeft? ImplicitConversionSequence::Worse
3142 : ImplicitConversionSequence::Better;
3143
3144 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3145 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3146 (FromAssignLeft != FromAssignRight))
3147 return FromAssignLeft? ImplicitConversionSequence::Better
3148 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003149 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003150 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003151
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003152 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003153 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3154 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3155 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003156 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003157 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003158 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003159 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003160 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003161 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003162 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003163 ToType2->getAs<MemberPointerType>();
3164 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3165 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3166 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3167 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3168 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3169 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3170 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3171 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003172 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003173 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003174 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003175 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003176 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003177 return ImplicitConversionSequence::Better;
3178 }
3179 // conversion of B::* to C::* is better than conversion of A::* to C::*
3180 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003181 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003182 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003183 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003184 return ImplicitConversionSequence::Worse;
3185 }
3186 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003187
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003188 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003189 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003190 // -- binding of an expression of type C to a reference of type
3191 // B& is better than binding an expression of type C to a
3192 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003193 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3194 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3195 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003196 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003197 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003198 return ImplicitConversionSequence::Worse;
3199 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003200
Douglas Gregor225c41e2008-11-03 19:09:14 +00003201 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003202 // -- binding of an expression of type B to a reference of type
3203 // A& is better than binding an expression of type C to a
3204 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003205 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3206 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3207 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003208 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003209 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003210 return ImplicitConversionSequence::Worse;
3211 }
3212 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003213
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003214 return ImplicitConversionSequence::Indistinguishable;
3215}
3216
Douglas Gregorabe183d2010-04-13 16:31:36 +00003217/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3218/// determine whether they are reference-related,
3219/// reference-compatible, reference-compatible with added
3220/// qualification, or incompatible, for use in C++ initialization by
3221/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3222/// type, and the first type (T1) is the pointee type of the reference
3223/// type being initialized.
3224Sema::ReferenceCompareResult
3225Sema::CompareReferenceRelationship(SourceLocation Loc,
3226 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003227 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003228 bool &ObjCConversion,
3229 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003230 assert(!OrigT1->isReferenceType() &&
3231 "T1 must be the pointee type of the reference type");
3232 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3233
3234 QualType T1 = Context.getCanonicalType(OrigT1);
3235 QualType T2 = Context.getCanonicalType(OrigT2);
3236 Qualifiers T1Quals, T2Quals;
3237 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3238 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3239
3240 // C++ [dcl.init.ref]p4:
3241 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3242 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3243 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003244 DerivedToBase = false;
3245 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003246 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003247 if (UnqualT1 == UnqualT2) {
3248 // Nothing to do.
3249 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003250 IsDerivedFrom(UnqualT2, UnqualT1))
3251 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003252 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3253 UnqualT2->isObjCObjectOrInterfaceType() &&
3254 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3255 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003256 else
3257 return Ref_Incompatible;
3258
3259 // At this point, we know that T1 and T2 are reference-related (at
3260 // least).
3261
3262 // If the type is an array type, promote the element qualifiers to the type
3263 // for comparison.
3264 if (isa<ArrayType>(T1) && T1Quals)
3265 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3266 if (isa<ArrayType>(T2) && T2Quals)
3267 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3268
3269 // C++ [dcl.init.ref]p4:
3270 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3271 // reference-related to T2 and cv1 is the same cv-qualification
3272 // as, or greater cv-qualification than, cv2. For purposes of
3273 // overload resolution, cases for which cv1 is greater
3274 // cv-qualification than cv2 are identified as
3275 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003276 //
3277 // Note that we also require equivalence of Objective-C GC and address-space
3278 // qualifiers when performing these computations, so that e.g., an int in
3279 // address space 1 is not reference-compatible with an int in address
3280 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003281 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3282 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3283 T1Quals.removeObjCLifetime();
3284 T2Quals.removeObjCLifetime();
3285 ObjCLifetimeConversion = true;
3286 }
3287
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003288 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003289 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003290 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003291 return Ref_Compatible_With_Added_Qualification;
3292 else
3293 return Ref_Related;
3294}
3295
Douglas Gregor604eb652010-08-11 02:15:33 +00003296/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003297/// with DeclType. Return true if something definite is found.
3298static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003299FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3300 QualType DeclType, SourceLocation DeclLoc,
3301 Expr *Init, QualType T2, bool AllowRvalues,
3302 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003303 assert(T2->isRecordType() && "Can only find conversions of record types.");
3304 CXXRecordDecl *T2RecordDecl
3305 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3306
3307 OverloadCandidateSet CandidateSet(DeclLoc);
3308 const UnresolvedSetImpl *Conversions
3309 = T2RecordDecl->getVisibleConversionFunctions();
3310 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3311 E = Conversions->end(); I != E; ++I) {
3312 NamedDecl *D = *I;
3313 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3314 if (isa<UsingShadowDecl>(D))
3315 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3316
3317 FunctionTemplateDecl *ConvTemplate
3318 = dyn_cast<FunctionTemplateDecl>(D);
3319 CXXConversionDecl *Conv;
3320 if (ConvTemplate)
3321 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3322 else
3323 Conv = cast<CXXConversionDecl>(D);
3324
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003325 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003326 // explicit conversions, skip it.
3327 if (!AllowExplicit && Conv->isExplicit())
3328 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003329
Douglas Gregor604eb652010-08-11 02:15:33 +00003330 if (AllowRvalues) {
3331 bool DerivedToBase = false;
3332 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003333 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00003334
3335 // If we are initializing an rvalue reference, don't permit conversion
3336 // functions that return lvalues.
3337 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3338 const ReferenceType *RefType
3339 = Conv->getConversionType()->getAs<LValueReferenceType>();
3340 if (RefType && !RefType->getPointeeType()->isFunctionType())
3341 continue;
3342 }
3343
Douglas Gregor604eb652010-08-11 02:15:33 +00003344 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00003345 S.CompareReferenceRelationship(
3346 DeclLoc,
3347 Conv->getConversionType().getNonReferenceType()
3348 .getUnqualifiedType(),
3349 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00003350 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00003351 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00003352 continue;
3353 } else {
3354 // If the conversion function doesn't return a reference type,
3355 // it can't be considered for this conversion. An rvalue reference
3356 // is only acceptable if its referencee is a function type.
3357
3358 const ReferenceType *RefType =
3359 Conv->getConversionType()->getAs<ReferenceType>();
3360 if (!RefType ||
3361 (!RefType->isLValueReferenceType() &&
3362 !RefType->getPointeeType()->isFunctionType()))
3363 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003364 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003365
Douglas Gregor604eb652010-08-11 02:15:33 +00003366 if (ConvTemplate)
3367 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003368 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00003369 else
3370 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003371 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003372 }
3373
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003374 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3375
Sebastian Redl4680bf22010-06-30 18:13:39 +00003376 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003377 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003378 case OR_Success:
3379 // C++ [over.ics.ref]p1:
3380 //
3381 // [...] If the parameter binds directly to the result of
3382 // applying a conversion function to the argument
3383 // expression, the implicit conversion sequence is a
3384 // user-defined conversion sequence (13.3.3.1.2), with the
3385 // second standard conversion sequence either an identity
3386 // conversion or, if the conversion function returns an
3387 // entity of a type that is a derived class of the parameter
3388 // type, a derived-to-base Conversion.
3389 if (!Best->FinalConversion.DirectBinding)
3390 return false;
3391
Chandler Carruth25ca4212011-02-25 19:41:05 +00003392 if (Best->Function)
3393 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003394 ICS.setUserDefined();
3395 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3396 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003397 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003398 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00003399 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003400 ICS.UserDefined.EllipsisConversion = false;
3401 assert(ICS.UserDefined.After.ReferenceBinding &&
3402 ICS.UserDefined.After.DirectBinding &&
3403 "Expected a direct reference binding!");
3404 return true;
3405
3406 case OR_Ambiguous:
3407 ICS.setAmbiguous();
3408 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3409 Cand != CandidateSet.end(); ++Cand)
3410 if (Cand->Viable)
3411 ICS.Ambiguous.addConversion(Cand->Function);
3412 return true;
3413
3414 case OR_No_Viable_Function:
3415 case OR_Deleted:
3416 // There was no suitable conversion, or we found a deleted
3417 // conversion; continue with other checks.
3418 return false;
3419 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003420
Eric Christopher1c3d5022010-06-30 18:36:32 +00003421 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003422}
3423
Douglas Gregorabe183d2010-04-13 16:31:36 +00003424/// \brief Compute an implicit conversion sequence for reference
3425/// initialization.
3426static ImplicitConversionSequence
3427TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3428 SourceLocation DeclLoc,
3429 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003430 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003431 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3432
3433 // Most paths end in a failed conversion.
3434 ImplicitConversionSequence ICS;
3435 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3436
3437 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3438 QualType T2 = Init->getType();
3439
3440 // If the initializer is the address of an overloaded function, try
3441 // to resolve the overloaded function. If all goes well, T2 is the
3442 // type of the resulting function.
3443 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3444 DeclAccessPair Found;
3445 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3446 false, Found))
3447 T2 = Fn->getType();
3448 }
3449
3450 // Compute some basic properties of the types and the initializer.
3451 bool isRValRef = DeclType->isRValueReferenceType();
3452 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003453 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003454 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003455 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003456 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003457 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003458 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003459
Douglas Gregorabe183d2010-04-13 16:31:36 +00003460
Sebastian Redl4680bf22010-06-30 18:13:39 +00003461 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00003462 // A reference to type "cv1 T1" is initialized by an expression
3463 // of type "cv2 T2" as follows:
3464
Sebastian Redl4680bf22010-06-30 18:13:39 +00003465 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003466 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003467 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3468 // reference-compatible with "cv2 T2," or
3469 //
3470 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3471 if (InitCategory.isLValue() &&
3472 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003473 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00003474 // When a parameter of reference type binds directly (8.5.3)
3475 // to an argument expression, the implicit conversion sequence
3476 // is the identity conversion, unless the argument expression
3477 // has a type that is a derived class of the parameter type,
3478 // in which case the implicit conversion sequence is a
3479 // derived-to-base Conversion (13.3.3.1).
3480 ICS.setStandard();
3481 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00003482 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3483 : ObjCConversion? ICK_Compatible_Conversion
3484 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003485 ICS.Standard.Third = ICK_Identity;
3486 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3487 ICS.Standard.setToType(0, T2);
3488 ICS.Standard.setToType(1, T1);
3489 ICS.Standard.setToType(2, T1);
3490 ICS.Standard.ReferenceBinding = true;
3491 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003492 ICS.Standard.IsLvalueReference = !isRValRef;
3493 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3494 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003495 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003496 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003497 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003498
Sebastian Redl4680bf22010-06-30 18:13:39 +00003499 // Nothing more to do: the inaccessibility/ambiguity check for
3500 // derived-to-base conversions is suppressed when we're
3501 // computing the implicit conversion sequence (C++
3502 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00003503 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003504 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00003505
Sebastian Redl4680bf22010-06-30 18:13:39 +00003506 // -- has a class type (i.e., T2 is a class type), where T1 is
3507 // not reference-related to T2, and can be implicitly
3508 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3509 // is reference-compatible with "cv3 T3" 92) (this
3510 // conversion is selected by enumerating the applicable
3511 // conversion functions (13.3.1.6) and choosing the best
3512 // one through overload resolution (13.3)),
3513 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003514 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00003515 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00003516 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3517 Init, T2, /*AllowRvalues=*/false,
3518 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00003519 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003520 }
3521 }
3522
Sebastian Redl4680bf22010-06-30 18:13:39 +00003523 // -- Otherwise, the reference shall be an lvalue reference to a
3524 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003525 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003526 //
Douglas Gregor66821b52010-04-18 09:22:00 +00003527 // We actually handle one oddity of C++ [over.ics.ref] at this
3528 // point, which is that, due to p2 (which short-circuits reference
3529 // binding by only attempting a simple conversion for non-direct
3530 // bindings) and p3's strange wording, we allow a const volatile
3531 // reference to bind to an rvalue. Hence the check for the presence
3532 // of "const" rather than checking for "const" being the only
3533 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00003534 // This is also the point where rvalue references and lvalue inits no longer
3535 // go together.
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003536 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00003537 return ICS;
3538
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003539 // -- If the initializer expression
3540 //
3541 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00003542 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003543 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3544 (InitCategory.isXValue() ||
3545 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3546 (InitCategory.isLValue() && T2->isFunctionType()))) {
3547 ICS.setStandard();
3548 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003549 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003550 : ObjCConversion? ICK_Compatible_Conversion
3551 : ICK_Identity;
3552 ICS.Standard.Third = ICK_Identity;
3553 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3554 ICS.Standard.setToType(0, T2);
3555 ICS.Standard.setToType(1, T1);
3556 ICS.Standard.setToType(2, T1);
3557 ICS.Standard.ReferenceBinding = true;
3558 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3559 // binding unless we're binding to a class prvalue.
3560 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3561 // allow the use of rvalue references in C++98/03 for the benefit of
3562 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003563 ICS.Standard.DirectBinding =
3564 S.getLangOptions().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003565 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00003566 ICS.Standard.IsLvalueReference = !isRValRef;
3567 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003568 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003569 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003570 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003571 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003572 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003573 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003574
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003575 // -- has a class type (i.e., T2 is a class type), where T1 is not
3576 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003577 // an xvalue, class prvalue, or function lvalue of type
3578 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003579 // "cv3 T3",
3580 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003581 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003582 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003583 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003584 // class subobject).
3585 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003586 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003587 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3588 Init, T2, /*AllowRvalues=*/true,
3589 AllowExplicit)) {
3590 // In the second case, if the reference is an rvalue reference
3591 // and the second standard conversion sequence of the
3592 // user-defined conversion sequence includes an lvalue-to-rvalue
3593 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003594 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003595 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3596 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3597
Douglas Gregor68ed68b2011-01-21 16:36:05 +00003598 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00003599 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003600
Douglas Gregorabe183d2010-04-13 16:31:36 +00003601 // -- Otherwise, a temporary of type "cv1 T1" is created and
3602 // initialized from the initializer expression using the
3603 // rules for a non-reference copy initialization (8.5). The
3604 // reference is then bound to the temporary. If T1 is
3605 // reference-related to T2, cv1 must be the same
3606 // cv-qualification as, or greater cv-qualification than,
3607 // cv2; otherwise, the program is ill-formed.
3608 if (RefRelationship == Sema::Ref_Related) {
3609 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3610 // we would be reference-compatible or reference-compatible with
3611 // added qualification. But that wasn't the case, so the reference
3612 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00003613 //
3614 // Note that we only want to check address spaces and cvr-qualifiers here.
3615 // ObjC GC and lifetime qualifiers aren't important.
3616 Qualifiers T1Quals = T1.getQualifiers();
3617 Qualifiers T2Quals = T2.getQualifiers();
3618 T1Quals.removeObjCGCAttr();
3619 T1Quals.removeObjCLifetime();
3620 T2Quals.removeObjCGCAttr();
3621 T2Quals.removeObjCLifetime();
3622 if (!T1Quals.compatiblyIncludes(T2Quals))
3623 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003624 }
3625
3626 // If at least one of the types is a class type, the types are not
3627 // related, and we aren't allowed any user conversions, the
3628 // reference binding fails. This case is important for breaking
3629 // recursion, since TryImplicitConversion below will attempt to
3630 // create a temporary through the use of a copy constructor.
3631 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3632 (T1->isRecordType() || T2->isRecordType()))
3633 return ICS;
3634
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003635 // If T1 is reference-related to T2 and the reference is an rvalue
3636 // reference, the initializer expression shall not be an lvalue.
3637 if (RefRelationship >= Sema::Ref_Related &&
3638 isRValRef && Init->Classify(S.Context).isLValue())
3639 return ICS;
3640
Douglas Gregorabe183d2010-04-13 16:31:36 +00003641 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00003642 // When a parameter of reference type is not bound directly to
3643 // an argument expression, the conversion sequence is the one
3644 // required to convert the argument expression to the
3645 // underlying type of the reference according to
3646 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3647 // to copy-initializing a temporary of the underlying type with
3648 // the argument expression. Any difference in top-level
3649 // cv-qualification is subsumed by the initialization itself
3650 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00003651 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3652 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003653 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003654 /*CStyle=*/false,
3655 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003656
3657 // Of course, that's still a reference binding.
3658 if (ICS.isStandard()) {
3659 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003660 ICS.Standard.IsLvalueReference = !isRValRef;
3661 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3662 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003663 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003664 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003665 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00003666 // Don't allow rvalue references to bind to lvalues.
3667 if (DeclType->isRValueReferenceType()) {
3668 if (const ReferenceType *RefType
3669 = ICS.UserDefined.ConversionFunction->getResultType()
3670 ->getAs<LValueReferenceType>()) {
3671 if (!RefType->getPointeeType()->isFunctionType()) {
3672 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
3673 DeclType);
3674 return ICS;
3675 }
3676 }
3677 }
3678
Douglas Gregorabe183d2010-04-13 16:31:36 +00003679 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00003680 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3681 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3682 ICS.UserDefined.After.BindsToRvalue = true;
3683 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3684 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003685 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003686
Douglas Gregorabe183d2010-04-13 16:31:36 +00003687 return ICS;
3688}
3689
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003690/// TryCopyInitialization - Try to copy-initialize a value of type
3691/// ToType from the expression From. Return the implicit conversion
3692/// sequence required to pass this argument, which may be a bad
3693/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00003694/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00003695/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00003696static ImplicitConversionSequence
3697TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003698 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00003699 bool InOverloadResolution,
3700 bool AllowObjCWritebackConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003701 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00003702 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003703 /*FIXME:*/From->getLocStart(),
3704 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003705 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003706
John McCall120d63c2010-08-24 20:38:10 +00003707 return TryImplicitConversion(S, From, ToType,
3708 SuppressUserConversions,
3709 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003710 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00003711 /*CStyle=*/false,
3712 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003713}
3714
Anna Zaksf3546ee2011-07-28 19:46:48 +00003715static bool TryCopyInitialization(const CanQualType FromQTy,
3716 const CanQualType ToQTy,
3717 Sema &S,
3718 SourceLocation Loc,
3719 ExprValueKind FromVK) {
3720 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
3721 ImplicitConversionSequence ICS =
3722 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
3723
3724 return !ICS.isBad();
3725}
3726
Douglas Gregor96176b32008-11-18 23:14:02 +00003727/// TryObjectArgumentInitialization - Try to initialize the object
3728/// parameter of the given member function (@c Method) from the
3729/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00003730static ImplicitConversionSequence
3731TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003732 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00003733 CXXMethodDecl *Method,
3734 CXXRecordDecl *ActingContext) {
3735 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003736 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3737 // const volatile object.
3738 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3739 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00003740 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00003741
3742 // Set up the conversion sequence as a "bad" conversion, to allow us
3743 // to exit early.
3744 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00003745
3746 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00003747 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003748 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003749 FromType = PT->getPointeeType();
3750
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003751 // When we had a pointer, it's implicitly dereferenced, so we
3752 // better have an lvalue.
3753 assert(FromClassification.isLValue());
3754 }
3755
Anders Carlssona552f7c2009-05-01 18:34:30 +00003756 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00003757
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003758 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003759 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003760 // parameter is
3761 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003762 // - "lvalue reference to cv X" for functions declared without a
3763 // ref-qualifier or with the & ref-qualifier
3764 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003765 // ref-qualifier
3766 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003767 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003768 // cv-qualification on the member function declaration.
3769 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003770 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003771 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00003772 // (C++ [over.match.funcs]p5). We perform a simplified version of
3773 // reference binding here, that allows class rvalues to bind to
3774 // non-constant references.
3775
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003776 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00003777 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003778 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00003779 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00003780 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00003781 ICS.setBad(BadConversionSequence::bad_qualifiers,
3782 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003783 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003784 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003785
3786 // Check that we have either the same type or a derived type. It
3787 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00003788 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00003789 ImplicitConversionKind SecondKind;
3790 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3791 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00003792 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00003793 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00003794 else {
John McCallb1bdc622010-02-25 01:37:24 +00003795 ICS.setBad(BadConversionSequence::unrelated_class,
3796 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003797 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003798 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003799
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003800 // Check the ref-qualifier.
3801 switch (Method->getRefQualifier()) {
3802 case RQ_None:
3803 // Do nothing; we don't care about lvalueness or rvalueness.
3804 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003805
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003806 case RQ_LValue:
3807 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3808 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003809 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003810 ImplicitParamType);
3811 return ICS;
3812 }
3813 break;
3814
3815 case RQ_RValue:
3816 if (!FromClassification.isRValue()) {
3817 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003818 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003819 ImplicitParamType);
3820 return ICS;
3821 }
3822 break;
3823 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003824
Douglas Gregor96176b32008-11-18 23:14:02 +00003825 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00003826 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003827 ICS.Standard.setAsIdentityConversion();
3828 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003829 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003830 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003831 ICS.Standard.ReferenceBinding = true;
3832 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003833 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00003834 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003835 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3836 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3837 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00003838 return ICS;
3839}
3840
3841/// PerformObjectArgumentInitialization - Perform initialization of
3842/// the implicit object parameter for the given Method with the given
3843/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00003844ExprResult
3845Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003846 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003847 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003848 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003849 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003850 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003851 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003852
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003853 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00003854 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003855 FromRecordType = PT->getPointeeType();
3856 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003857 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00003858 } else {
3859 FromRecordType = From->getType();
3860 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003861 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00003862 }
3863
John McCall701c89e2009-12-03 04:06:58 +00003864 // Note that we always use the true parent context when performing
3865 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003866 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003867 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3868 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003869 if (ICS.isBad()) {
3870 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3871 Qualifiers FromQs = FromRecordType.getQualifiers();
3872 Qualifiers ToQs = DestType.getQualifiers();
3873 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3874 if (CVR) {
3875 Diag(From->getSourceRange().getBegin(),
3876 diag::err_member_function_call_bad_cvr)
3877 << Method->getDeclName() << FromRecordType << (CVR - 1)
3878 << From->getSourceRange();
3879 Diag(Method->getLocation(), diag::note_previous_decl)
3880 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00003881 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003882 }
3883 }
3884
Douglas Gregor96176b32008-11-18 23:14:02 +00003885 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003886 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003887 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003888 }
Mike Stump1eb44332009-09-09 15:08:12 +00003889
John Wiegley429bb272011-04-08 18:41:53 +00003890 if (ICS.Standard.Second == ICK_Derived_To_Base) {
3891 ExprResult FromRes =
3892 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3893 if (FromRes.isInvalid())
3894 return ExprError();
3895 From = FromRes.take();
3896 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003897
Douglas Gregor5fccd362010-03-03 23:55:11 +00003898 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00003899 From = ImpCastExprToType(From, DestType, CK_NoOp,
3900 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3901 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00003902}
3903
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003904/// TryContextuallyConvertToBool - Attempt to contextually convert the
3905/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00003906static ImplicitConversionSequence
3907TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003908 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00003909 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003910 // FIXME: Are these flags correct?
3911 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003912 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003913 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003914 /*CStyle=*/false,
3915 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003916}
3917
3918/// PerformContextuallyConvertToBool - Perform a contextual conversion
3919/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00003920ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall120d63c2010-08-24 20:38:10 +00003921 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00003922 if (!ICS.isBad())
3923 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003924
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003925 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall864c0412011-04-26 20:42:42 +00003926 return Diag(From->getSourceRange().getBegin(),
3927 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003928 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003929 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003930}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003931
John McCall0bcc9bc2011-09-09 06:11:02 +00003932/// dropPointerConversions - If the given standard conversion sequence
3933/// involves any pointer conversions, remove them. This may change
3934/// the result type of the conversion sequence.
3935static void dropPointerConversion(StandardConversionSequence &SCS) {
3936 if (SCS.Second == ICK_Pointer_Conversion) {
3937 SCS.Second = ICK_Identity;
3938 SCS.Third = ICK_Identity;
3939 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
3940 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003941}
John McCall120d63c2010-08-24 20:38:10 +00003942
John McCall0bcc9bc2011-09-09 06:11:02 +00003943/// TryContextuallyConvertToObjCPointer - Attempt to contextually
3944/// convert the expression From to an Objective-C pointer type.
3945static ImplicitConversionSequence
3946TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
3947 // Do an implicit conversion to 'id'.
3948 QualType Ty = S.Context.getObjCIdType();
3949 ImplicitConversionSequence ICS
3950 = TryImplicitConversion(S, From, Ty,
3951 // FIXME: Are these flags correct?
3952 /*SuppressUserConversions=*/false,
3953 /*AllowExplicit=*/true,
3954 /*InOverloadResolution=*/false,
3955 /*CStyle=*/false,
3956 /*AllowObjCWritebackConversion=*/false);
3957
3958 // Strip off any final conversions to 'id'.
3959 switch (ICS.getKind()) {
3960 case ImplicitConversionSequence::BadConversion:
3961 case ImplicitConversionSequence::AmbiguousConversion:
3962 case ImplicitConversionSequence::EllipsisConversion:
3963 break;
3964
3965 case ImplicitConversionSequence::UserDefinedConversion:
3966 dropPointerConversion(ICS.UserDefined.After);
3967 break;
3968
3969 case ImplicitConversionSequence::StandardConversion:
3970 dropPointerConversion(ICS.Standard);
3971 break;
3972 }
3973
3974 return ICS;
3975}
3976
3977/// PerformContextuallyConvertToObjCPointer - Perform a contextual
3978/// conversion of the expression From to an Objective-C pointer type.
3979ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003980 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00003981 ImplicitConversionSequence ICS =
3982 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003983 if (!ICS.isBad())
3984 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00003985 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003986}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003987
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003988/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00003989/// enumeration type.
3990///
3991/// This routine will attempt to convert an expression of class type to an
3992/// integral or enumeration type, if that class type only has a single
3993/// conversion to an integral or enumeration type.
3994///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003995/// \param Loc The source location of the construct that requires the
3996/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003997///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003998/// \param FromE The expression we're converting from.
3999///
4000/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4001/// have integral or enumeration type.
4002///
4003/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4004/// incomplete class type.
4005///
4006/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4007/// explicit conversion function (because no implicit conversion functions
4008/// were available). This is a recovery mode.
4009///
4010/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4011/// showing which conversion was picked.
4012///
4013/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4014/// conversion function that could convert to integral or enumeration type.
4015///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004016/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004017/// usable conversion function.
4018///
4019/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4020/// function, which may be an extension in this case.
4021///
4022/// \returns The expression, converted to an integral or enumeration type if
4023/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004024ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004025Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00004026 const PartialDiagnostic &NotIntDiag,
4027 const PartialDiagnostic &IncompleteDiag,
4028 const PartialDiagnostic &ExplicitConvDiag,
4029 const PartialDiagnostic &ExplicitConvNote,
4030 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004031 const PartialDiagnostic &AmbigNote,
4032 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00004033 // We can't perform any more checking for type-dependent expressions.
4034 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00004035 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004036
Douglas Gregorc30614b2010-06-29 23:17:37 +00004037 // If the expression already has integral or enumeration type, we're golden.
4038 QualType T = From->getType();
4039 if (T->isIntegralOrEnumerationType())
John McCall9ae2f072010-08-23 23:25:46 +00004040 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004041
4042 // FIXME: Check for missing '()' if T is a function type?
4043
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004044 // 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 +00004045 // expression of integral or enumeration type.
4046 const RecordType *RecordTy = T->getAs<RecordType>();
4047 if (!RecordTy || !getLangOptions().CPlusPlus) {
4048 Diag(Loc, NotIntDiag)
4049 << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00004050 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004051 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004052
Douglas Gregorc30614b2010-06-29 23:17:37 +00004053 // We must have a complete class type.
4054 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00004055 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004056
Douglas Gregorc30614b2010-06-29 23:17:37 +00004057 // Look for a conversion to an integral or enumeration type.
4058 UnresolvedSet<4> ViableConversions;
4059 UnresolvedSet<4> ExplicitConversions;
4060 const UnresolvedSetImpl *Conversions
4061 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004062
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004063 bool HadMultipleCandidates = (Conversions->size() > 1);
4064
Douglas Gregorc30614b2010-06-29 23:17:37 +00004065 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004066 E = Conversions->end();
4067 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00004068 ++I) {
4069 if (CXXConversionDecl *Conversion
4070 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4071 if (Conversion->getConversionType().getNonReferenceType()
4072 ->isIntegralOrEnumerationType()) {
4073 if (Conversion->isExplicit())
4074 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4075 else
4076 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4077 }
4078 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004079
Douglas Gregorc30614b2010-06-29 23:17:37 +00004080 switch (ViableConversions.size()) {
4081 case 0:
4082 if (ExplicitConversions.size() == 1) {
4083 DeclAccessPair Found = ExplicitConversions[0];
4084 CXXConversionDecl *Conversion
4085 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004086
Douglas Gregorc30614b2010-06-29 23:17:37 +00004087 // The user probably meant to invoke the given explicit
4088 // conversion; use it.
4089 QualType ConvTy
4090 = Conversion->getConversionType().getNonReferenceType();
4091 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00004092 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004093
Douglas Gregorc30614b2010-06-29 23:17:37 +00004094 Diag(Loc, ExplicitConvDiag)
4095 << T << ConvTy
4096 << FixItHint::CreateInsertion(From->getLocStart(),
4097 "static_cast<" + TypeStr + ">(")
4098 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4099 ")");
4100 Diag(Conversion->getLocation(), ExplicitConvNote)
4101 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004102
4103 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00004104 // explicit conversion function.
4105 if (isSFINAEContext())
4106 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004107
Douglas Gregorc30614b2010-06-29 23:17:37 +00004108 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004109 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4110 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004111 if (Result.isInvalid())
4112 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004113
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004114 From = Result.get();
Douglas Gregorc30614b2010-06-29 23:17:37 +00004115 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004116
Douglas Gregorc30614b2010-06-29 23:17:37 +00004117 // We'll complain below about a non-integral condition type.
4118 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004119
Douglas Gregorc30614b2010-06-29 23:17:37 +00004120 case 1: {
4121 // Apply this conversion.
4122 DeclAccessPair Found = ViableConversions[0];
4123 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004124
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004125 CXXConversionDecl *Conversion
4126 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4127 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004128 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004129 if (ConvDiag.getDiagID()) {
4130 if (isSFINAEContext())
4131 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004132
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004133 Diag(Loc, ConvDiag)
4134 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4135 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004136
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004137 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4138 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004139 if (Result.isInvalid())
4140 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004141
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004142 From = Result.get();
Douglas Gregorc30614b2010-06-29 23:17:37 +00004143 break;
4144 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004145
Douglas Gregorc30614b2010-06-29 23:17:37 +00004146 default:
4147 Diag(Loc, AmbigDiag)
4148 << T << From->getSourceRange();
4149 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4150 CXXConversionDecl *Conv
4151 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4152 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4153 Diag(Conv->getLocation(), AmbigNote)
4154 << ConvTy->isEnumeralType() << ConvTy;
4155 }
John McCall9ae2f072010-08-23 23:25:46 +00004156 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004157 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004158
Douglas Gregoracb0bd82010-06-29 23:25:20 +00004159 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00004160 Diag(Loc, NotIntDiag)
4161 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00004162
John McCall9ae2f072010-08-23 23:25:46 +00004163 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004164}
4165
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004166/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00004167/// candidate functions, using the given function call arguments. If
4168/// @p SuppressUserConversions, then don't allow user-defined
4169/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004170///
4171/// \para PartialOverloading true if we are performing "partial" overloading
4172/// based on an incomplete set of function arguments. This feature is used by
4173/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00004174void
4175Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00004176 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004177 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00004178 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00004179 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004180 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00004181 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00004182 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004183 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00004184 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004185 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00004186
Douglas Gregor88a35142008-12-22 05:46:06 +00004187 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004188 if (!isa<CXXConstructorDecl>(Method)) {
4189 // If we get here, it's because we're calling a member function
4190 // that is named without a member access expression (e.g.,
4191 // "this->f") that was either written explicitly or created
4192 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00004193 // function, e.g., X::f(). We use an empty type for the implied
4194 // object argument (C++ [over.call.func]p3), and the acting context
4195 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00004196 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004197 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004198 Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004199 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004200 return;
4201 }
4202 // We treat a constructor like a non-member function, since its object
4203 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00004204 }
4205
Douglas Gregorfd476482009-11-13 23:59:09 +00004206 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00004207 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00004208
Douglas Gregor7edfb692009-11-23 12:27:39 +00004209 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004210 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004211
Douglas Gregor66724ea2009-11-14 01:20:54 +00004212 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4213 // C++ [class.copy]p3:
4214 // A member function template is never instantiated to perform the copy
4215 // of a class object to an object of its class type.
4216 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004217 if (NumArgs == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00004218 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00004219 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4220 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00004221 return;
4222 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004223
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004224 // Add this candidate
4225 CandidateSet.push_back(OverloadCandidate());
4226 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004227 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004228 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00004229 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004230 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004231 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004232 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004233
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004234 unsigned NumArgsInProto = Proto->getNumArgs();
4235
4236 // (C++ 13.3.2p2): A candidate function having fewer than m
4237 // parameters is viable only if it has an ellipsis in its parameter
4238 // list (8.3.5).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004239 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00004240 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004241 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004242 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004243 return;
4244 }
4245
4246 // (C++ 13.3.2p2): A candidate function having more than m parameters
4247 // is viable only if the (m+1)st parameter has a default argument
4248 // (8.3.6). For the purposes of overload resolution, the
4249 // parameter list is truncated on the right, so that there are
4250 // exactly m parameters.
4251 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004252 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004253 // Not enough arguments.
4254 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004255 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004256 return;
4257 }
4258
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00004259 // (CUDA B.1): Check for invalid calls between targets.
4260 if (getLangOptions().CUDA)
4261 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
4262 if (CheckCUDATarget(Caller, Function)) {
4263 Candidate.Viable = false;
4264 Candidate.FailureKind = ovl_fail_bad_target;
4265 return;
4266 }
4267
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004268 // Determine the implicit conversion sequences for each of the
4269 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004270 Candidate.Conversions.resize(NumArgs);
4271 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4272 if (ArgIdx < NumArgsInProto) {
4273 // (C++ 13.3.2p3): for F to be a viable function, there shall
4274 // exist for each argument an implicit conversion sequence
4275 // (13.3.3.1) that converts that argument to the corresponding
4276 // parameter of F.
4277 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004278 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004279 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004280 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004281 /*InOverloadResolution=*/true,
4282 /*AllowObjCWritebackConversion=*/
4283 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00004284 if (Candidate.Conversions[ArgIdx].isBad()) {
4285 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004286 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00004287 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00004288 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004289 } else {
4290 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4291 // argument for which there is no corresponding parameter is
4292 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004293 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004294 }
4295 }
4296}
4297
Douglas Gregor063daf62009-03-13 18:40:31 +00004298/// \brief Add all of the function declarations in the given function set to
4299/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00004300void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00004301 Expr **Args, unsigned NumArgs,
4302 OverloadCandidateSet& CandidateSet,
4303 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00004304 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00004305 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4306 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004307 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00004308 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00004309 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004310 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004311 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00004312 CandidateSet, SuppressUserConversions);
4313 else
John McCall9aa472c2010-03-19 07:35:19 +00004314 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00004315 SuppressUserConversions);
4316 } else {
John McCall9aa472c2010-03-19 07:35:19 +00004317 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00004318 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4319 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00004320 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00004321 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00004322 /*FIXME: explicit args */ 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004323 Args[0]->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004324 Args[0]->Classify(Context),
4325 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00004326 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00004327 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00004328 else
John McCall9aa472c2010-03-19 07:35:19 +00004329 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00004330 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00004331 Args, NumArgs, CandidateSet,
4332 SuppressUserConversions);
4333 }
Douglas Gregor364e0212009-06-27 21:05:07 +00004334 }
Douglas Gregor063daf62009-03-13 18:40:31 +00004335}
4336
John McCall314be4e2009-11-17 07:50:12 +00004337/// AddMethodCandidate - Adds a named decl (which is some kind of
4338/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00004339void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004340 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004341 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00004342 Expr **Args, unsigned NumArgs,
4343 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004344 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00004345 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00004346 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00004347
4348 if (isa<UsingShadowDecl>(Decl))
4349 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004350
John McCall314be4e2009-11-17 07:50:12 +00004351 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4352 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4353 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00004354 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4355 /*ExplicitArgs*/ 0,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004356 ObjectType, ObjectClassification, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00004357 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004358 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00004359 } else {
John McCall9aa472c2010-03-19 07:35:19 +00004360 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004361 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004362 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00004363 }
4364}
4365
Douglas Gregor96176b32008-11-18 23:14:02 +00004366/// AddMethodCandidate - Adds the given C++ member function to the set
4367/// of candidate functions, using the given function call arguments
4368/// and the object argument (@c Object). For example, in a call
4369/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4370/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4371/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00004372/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00004373void
John McCall9aa472c2010-03-19 07:35:19 +00004374Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00004375 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004376 Expr::Classification ObjectClassification,
John McCall86820f52010-01-26 01:37:31 +00004377 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00004378 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004379 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00004380 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00004381 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00004382 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004383 assert(!isa<CXXConstructorDecl>(Method) &&
4384 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00004385
Douglas Gregor3f396022009-09-28 04:47:19 +00004386 if (!CandidateSet.isNewCandidate(Method))
4387 return;
4388
Douglas Gregor7edfb692009-11-23 12:27:39 +00004389 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004390 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004391
Douglas Gregor96176b32008-11-18 23:14:02 +00004392 // Add this candidate
4393 CandidateSet.push_back(OverloadCandidate());
4394 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004395 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00004396 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004397 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004398 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004399 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor96176b32008-11-18 23:14:02 +00004400
4401 unsigned NumArgsInProto = Proto->getNumArgs();
4402
4403 // (C++ 13.3.2p2): A candidate function having fewer than m
4404 // parameters is viable only if it has an ellipsis in its parameter
4405 // list (8.3.5).
4406 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4407 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004408 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00004409 return;
4410 }
4411
4412 // (C++ 13.3.2p2): A candidate function having more than m parameters
4413 // is viable only if the (m+1)st parameter has a default argument
4414 // (8.3.6). For the purposes of overload resolution, the
4415 // parameter list is truncated on the right, so that there are
4416 // exactly m parameters.
4417 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4418 if (NumArgs < MinRequiredArgs) {
4419 // Not enough arguments.
4420 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004421 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00004422 return;
4423 }
4424
4425 Candidate.Viable = true;
4426 Candidate.Conversions.resize(NumArgs + 1);
4427
John McCall701c89e2009-12-03 04:06:58 +00004428 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00004429 // The implicit object argument is ignored.
4430 Candidate.IgnoreObjectArgument = true;
4431 else {
4432 // Determine the implicit conversion sequence for the object
4433 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00004434 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004435 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4436 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00004437 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004438 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004439 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00004440 return;
4441 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004442 }
4443
4444 // Determine the implicit conversion sequences for each of the
4445 // arguments.
4446 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4447 if (ArgIdx < NumArgsInProto) {
4448 // (C++ 13.3.2p3): for F to be a viable function, there shall
4449 // exist for each argument an implicit conversion sequence
4450 // (13.3.3.1) that converts that argument to the corresponding
4451 // parameter of F.
4452 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004453 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004454 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004455 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004456 /*InOverloadResolution=*/true,
4457 /*AllowObjCWritebackConversion=*/
4458 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00004459 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004460 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004461 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004462 break;
4463 }
4464 } else {
4465 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4466 // argument for which there is no corresponding parameter is
4467 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004468 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00004469 }
4470 }
4471}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004472
Douglas Gregor6b906862009-08-21 00:16:32 +00004473/// \brief Add a C++ member function template as a candidate to the candidate
4474/// set, using template argument deduction to produce an appropriate member
4475/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004476void
Douglas Gregor6b906862009-08-21 00:16:32 +00004477Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00004478 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004479 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00004480 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00004481 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004482 Expr::Classification ObjectClassification,
John McCall701c89e2009-12-03 04:06:58 +00004483 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00004484 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004485 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004486 if (!CandidateSet.isNewCandidate(MethodTmpl))
4487 return;
4488
Douglas Gregor6b906862009-08-21 00:16:32 +00004489 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00004490 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00004491 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00004492 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00004493 // candidate functions in the usual way.113) A given name can refer to one
4494 // or more function templates and also to a set of overloaded non-template
4495 // functions. In such a case, the candidate functions generated from each
4496 // function template are combined with the set of non-template candidate
4497 // functions.
John McCall5769d612010-02-08 23:07:23 +00004498 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00004499 FunctionDecl *Specialization = 0;
4500 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004501 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00004502 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00004503 CandidateSet.push_back(OverloadCandidate());
4504 OverloadCandidate &Candidate = CandidateSet.back();
4505 Candidate.FoundDecl = FoundDecl;
4506 Candidate.Function = MethodTmpl->getTemplatedDecl();
4507 Candidate.Viable = false;
4508 Candidate.FailureKind = ovl_fail_bad_deduction;
4509 Candidate.IsSurrogate = false;
4510 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004511 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004512 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004513 Info);
4514 return;
4515 }
Mike Stump1eb44332009-09-09 15:08:12 +00004516
Douglas Gregor6b906862009-08-21 00:16:32 +00004517 // Add the function template specialization produced by template argument
4518 // deduction as a candidate.
4519 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00004520 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00004521 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00004522 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004523 ActingContext, ObjectType, ObjectClassification,
4524 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00004525}
4526
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004527/// \brief Add a C++ function template specialization as a candidate
4528/// in the candidate set, using template argument deduction to produce
4529/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004530void
Douglas Gregore53060f2009-06-25 22:08:12 +00004531Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00004532 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00004533 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00004534 Expr **Args, unsigned NumArgs,
4535 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004536 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004537 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4538 return;
4539
Douglas Gregore53060f2009-06-25 22:08:12 +00004540 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00004541 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00004542 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00004543 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00004544 // candidate functions in the usual way.113) A given name can refer to one
4545 // or more function templates and also to a set of overloaded non-template
4546 // functions. In such a case, the candidate functions generated from each
4547 // function template are combined with the set of non-template candidate
4548 // functions.
John McCall5769d612010-02-08 23:07:23 +00004549 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00004550 FunctionDecl *Specialization = 0;
4551 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004552 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004553 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00004554 CandidateSet.push_back(OverloadCandidate());
4555 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004556 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00004557 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4558 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004559 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00004560 Candidate.IsSurrogate = false;
4561 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004562 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004563 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004564 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00004565 return;
4566 }
Mike Stump1eb44332009-09-09 15:08:12 +00004567
Douglas Gregore53060f2009-06-25 22:08:12 +00004568 // Add the function template specialization produced by template argument
4569 // deduction as a candidate.
4570 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00004571 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004572 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00004573}
Mike Stump1eb44332009-09-09 15:08:12 +00004574
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004575/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00004576/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004577/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00004578/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004579/// (which may or may not be the same type as the type that the
4580/// conversion function produces).
4581void
4582Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00004583 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004584 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004585 Expr *From, QualType ToType,
4586 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004587 assert(!Conversion->getDescribedFunctionTemplate() &&
4588 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004589 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00004590 if (!CandidateSet.isNewCandidate(Conversion))
4591 return;
4592
Douglas Gregor7edfb692009-11-23 12:27:39 +00004593 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004594 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004595
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004596 // Add this candidate
4597 CandidateSet.push_back(OverloadCandidate());
4598 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004599 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004600 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004601 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004602 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004603 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004604 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004605 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004606 Candidate.Viable = true;
4607 Candidate.Conversions.resize(1);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004608 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004609
Douglas Gregorbca39322010-08-19 15:37:02 +00004610 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004611 // For conversion functions, the function is considered to be a member of
4612 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00004613 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004614 //
4615 // Determine the implicit conversion sequence for the implicit
4616 // object parameter.
4617 QualType ImplicitParamType = From->getType();
4618 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4619 ImplicitParamType = FromPtrType->getPointeeType();
4620 CXXRecordDecl *ConversionContext
4621 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004622
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004623 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004624 = TryObjectArgumentInitialization(*this, From->getType(),
4625 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004626 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004627
John McCall1d318332010-01-12 00:44:57 +00004628 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004629 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004630 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004631 return;
4632 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004633
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004634 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00004635 // derived to base as such conversions are given Conversion Rank. They only
4636 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4637 QualType FromCanon
4638 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4639 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4640 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4641 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00004642 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00004643 return;
4644 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004645
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004646 // To determine what the conversion from the result of calling the
4647 // conversion function to the type we're eventually trying to
4648 // convert to (ToType), we need to synthesize a call to the
4649 // conversion function and attempt copy initialization from it. This
4650 // makes sure that we get the right semantics with respect to
4651 // lvalues/rvalues and the type. Fortunately, we can allocate this
4652 // call on the stack and we don't need its arguments to be
4653 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00004654 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004655 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00004656 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4657 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00004658 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00004659 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00004660
Richard Smith87c1f1f2011-07-13 22:53:21 +00004661 QualType ConversionType = Conversion->getConversionType();
4662 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00004663 Candidate.Viable = false;
4664 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4665 return;
4666 }
4667
Richard Smith87c1f1f2011-07-13 22:53:21 +00004668 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00004669
Mike Stump1eb44332009-09-09 15:08:12 +00004670 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00004671 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4672 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00004673 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00004674 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00004675 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00004676 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00004677 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004678 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00004679 /*InOverloadResolution=*/false,
4680 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004681
John McCall1d318332010-01-12 00:44:57 +00004682 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004683 case ImplicitConversionSequence::StandardConversion:
4684 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004685
Douglas Gregorc520c842010-04-12 23:42:09 +00004686 // C++ [over.ics.user]p3:
4687 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004688 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00004689 // shall have exact match rank.
4690 if (Conversion->getPrimaryTemplate() &&
4691 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4692 Candidate.Viable = false;
4693 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4694 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004695
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004696 // C++0x [dcl.init.ref]p5:
4697 // In the second case, if the reference is an rvalue reference and
4698 // the second standard conversion sequence of the user-defined
4699 // conversion sequence includes an lvalue-to-rvalue conversion, the
4700 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004701 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004702 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4703 Candidate.Viable = false;
4704 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4705 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004706 break;
4707
4708 case ImplicitConversionSequence::BadConversion:
4709 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00004710 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004711 break;
4712
4713 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004714 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004715 "Can only end up with a standard conversion sequence or failure");
4716 }
4717}
4718
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004719/// \brief Adds a conversion function template specialization
4720/// candidate to the overload set, using template argument deduction
4721/// to deduce the template arguments of the conversion function
4722/// template from the type that we are converting to (C++
4723/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00004724void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004725Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00004726 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004727 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004728 Expr *From, QualType ToType,
4729 OverloadCandidateSet &CandidateSet) {
4730 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4731 "Only conversion function templates permitted here");
4732
Douglas Gregor3f396022009-09-28 04:47:19 +00004733 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4734 return;
4735
John McCall5769d612010-02-08 23:07:23 +00004736 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004737 CXXConversionDecl *Specialization = 0;
4738 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00004739 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004740 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00004741 CandidateSet.push_back(OverloadCandidate());
4742 OverloadCandidate &Candidate = CandidateSet.back();
4743 Candidate.FoundDecl = FoundDecl;
4744 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4745 Candidate.Viable = false;
4746 Candidate.FailureKind = ovl_fail_bad_deduction;
4747 Candidate.IsSurrogate = false;
4748 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004749 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004750 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004751 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004752 return;
4753 }
Mike Stump1eb44332009-09-09 15:08:12 +00004754
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004755 // Add the conversion function template specialization produced by
4756 // template argument deduction as a candidate.
4757 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00004758 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00004759 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004760}
4761
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004762/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4763/// converts the given @c Object to a function pointer via the
4764/// conversion function @c Conversion, and then attempts to call it
4765/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4766/// the type of function that we'll eventually be calling.
4767void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00004768 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004769 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00004770 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004771 Expr *Object,
John McCall701c89e2009-12-03 04:06:58 +00004772 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004773 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004774 if (!CandidateSet.isNewCandidate(Conversion))
4775 return;
4776
Douglas Gregor7edfb692009-11-23 12:27:39 +00004777 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004778 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004779
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004780 CandidateSet.push_back(OverloadCandidate());
4781 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004782 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004783 Candidate.Function = 0;
4784 Candidate.Surrogate = Conversion;
4785 Candidate.Viable = true;
4786 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004787 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004788 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004789 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004790
4791 // Determine the implicit conversion sequence for the implicit
4792 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004793 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004794 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004795 Object->Classify(Context),
4796 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00004797 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004798 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004799 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00004800 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004801 return;
4802 }
4803
4804 // The first conversion is actually a user-defined conversion whose
4805 // first conversion is ObjectInit's standard conversion (which is
4806 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00004807 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004808 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004809 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004810 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004811 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00004812 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00004813 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004814 = Candidate.Conversions[0].UserDefined.Before;
4815 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4816
Mike Stump1eb44332009-09-09 15:08:12 +00004817 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004818 unsigned NumArgsInProto = Proto->getNumArgs();
4819
4820 // (C++ 13.3.2p2): A candidate function having fewer than m
4821 // parameters is viable only if it has an ellipsis in its parameter
4822 // list (8.3.5).
4823 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4824 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004825 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004826 return;
4827 }
4828
4829 // Function types don't have any default arguments, so just check if
4830 // we have enough arguments.
4831 if (NumArgs < NumArgsInProto) {
4832 // Not enough arguments.
4833 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004834 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004835 return;
4836 }
4837
4838 // Determine the implicit conversion sequences for each of the
4839 // arguments.
4840 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4841 if (ArgIdx < NumArgsInProto) {
4842 // (C++ 13.3.2p3): for F to be a viable function, there shall
4843 // exist for each argument an implicit conversion sequence
4844 // (13.3.3.1) that converts that argument to the corresponding
4845 // parameter of F.
4846 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004847 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004848 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004849 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004850 /*InOverloadResolution=*/false,
4851 /*AllowObjCWritebackConversion=*/
4852 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00004853 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004854 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004855 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004856 break;
4857 }
4858 } else {
4859 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4860 // argument for which there is no corresponding parameter is
4861 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004862 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004863 }
4864 }
4865}
4866
Douglas Gregor063daf62009-03-13 18:40:31 +00004867/// \brief Add overload candidates for overloaded operators that are
4868/// member functions.
4869///
4870/// Add the overloaded operator candidates that are member functions
4871/// for the operator Op that was used in an operator expression such
4872/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4873/// CandidateSet will store the added overload candidates. (C++
4874/// [over.match.oper]).
4875void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4876 SourceLocation OpLoc,
4877 Expr **Args, unsigned NumArgs,
4878 OverloadCandidateSet& CandidateSet,
4879 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004880 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4881
4882 // C++ [over.match.oper]p3:
4883 // For a unary operator @ with an operand of a type whose
4884 // cv-unqualified version is T1, and for a binary operator @ with
4885 // a left operand of a type whose cv-unqualified version is T1 and
4886 // a right operand of a type whose cv-unqualified version is T2,
4887 // three sets of candidate functions, designated member
4888 // candidates, non-member candidates and built-in candidates, are
4889 // constructed as follows:
4890 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00004891
4892 // -- If T1 is a class type, the set of member candidates is the
4893 // result of the qualified lookup of T1::operator@
4894 // (13.3.1.1.1); otherwise, the set of member candidates is
4895 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00004896 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004897 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004898 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004899 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004900
John McCalla24dc2e2009-11-17 02:14:36 +00004901 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4902 LookupQualifiedName(Operators, T1Rec->getDecl());
4903 Operators.suppressDiagnostics();
4904
Mike Stump1eb44332009-09-09 15:08:12 +00004905 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004906 OperEnd = Operators.end();
4907 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00004908 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00004909 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004910 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004911 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00004912 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00004913 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004914}
4915
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004916/// AddBuiltinCandidate - Add a candidate for a built-in
4917/// operator. ResultTy and ParamTys are the result and parameter types
4918/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004919/// arguments being passed to the candidate. IsAssignmentOperator
4920/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004921/// operator. NumContextualBoolArguments is the number of arguments
4922/// (at the beginning of the argument list) that will be contextually
4923/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00004924void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004925 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004926 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004927 bool IsAssignmentOperator,
4928 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00004929 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004930 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004931
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004932 // Add this candidate
4933 CandidateSet.push_back(OverloadCandidate());
4934 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004935 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004936 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004937 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004938 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004939 Candidate.BuiltinTypes.ResultTy = ResultTy;
4940 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4941 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4942
4943 // Determine the implicit conversion sequences for each of the
4944 // arguments.
4945 Candidate.Viable = true;
4946 Candidate.Conversions.resize(NumArgs);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004947 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004948 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004949 // C++ [over.match.oper]p4:
4950 // For the built-in assignment operators, conversions of the
4951 // left operand are restricted as follows:
4952 // -- no temporaries are introduced to hold the left operand, and
4953 // -- no user-defined conversions are applied to the left
4954 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00004955 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004956 //
4957 // We block these conversions by turning off user-defined
4958 // conversions, since that is the only way that initialization of
4959 // a reference to a non-class type can occur from something that
4960 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004961 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004962 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004963 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00004964 Candidate.Conversions[ArgIdx]
4965 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004966 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004967 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004968 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004969 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00004970 /*InOverloadResolution=*/false,
4971 /*AllowObjCWritebackConversion=*/
4972 getLangOptions().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004973 }
John McCall1d318332010-01-12 00:44:57 +00004974 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004975 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004976 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004977 break;
4978 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004979 }
4980}
4981
4982/// BuiltinCandidateTypeSet - A set of types that will be used for the
4983/// candidate operator functions for built-in operators (C++
4984/// [over.built]). The types are separated into pointer types and
4985/// enumeration types.
4986class BuiltinCandidateTypeSet {
4987 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004988 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004989
4990 /// PointerTypes - The set of pointer types that will be used in the
4991 /// built-in candidates.
4992 TypeSet PointerTypes;
4993
Sebastian Redl78eb8742009-04-19 21:53:20 +00004994 /// MemberPointerTypes - The set of member pointer types that will be
4995 /// used in the built-in candidates.
4996 TypeSet MemberPointerTypes;
4997
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004998 /// EnumerationTypes - The set of enumeration types that will be
4999 /// used in the built-in candidates.
5000 TypeSet EnumerationTypes;
5001
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005002 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00005003 /// candidates.
5004 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00005005
5006 /// \brief A flag indicating non-record types are viable candidates
5007 bool HasNonRecordTypes;
5008
5009 /// \brief A flag indicating whether either arithmetic or enumeration types
5010 /// were present in the candidate set.
5011 bool HasArithmeticOrEnumeralTypes;
5012
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005013 /// \brief A flag indicating whether the nullptr type was present in the
5014 /// candidate set.
5015 bool HasNullPtrType;
5016
Douglas Gregor5842ba92009-08-24 15:23:48 +00005017 /// Sema - The semantic analysis instance where we are building the
5018 /// candidate type set.
5019 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00005020
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005021 /// Context - The AST context in which we will build the type sets.
5022 ASTContext &Context;
5023
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005024 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5025 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00005026 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005027
5028public:
5029 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005030 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005031
Mike Stump1eb44332009-09-09 15:08:12 +00005032 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00005033 : HasNonRecordTypes(false),
5034 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005035 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00005036 SemaRef(SemaRef),
5037 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005038
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005039 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00005040 SourceLocation Loc,
5041 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005042 bool AllowExplicitConversions,
5043 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005044
5045 /// pointer_begin - First pointer type found;
5046 iterator pointer_begin() { return PointerTypes.begin(); }
5047
Sebastian Redl78eb8742009-04-19 21:53:20 +00005048 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005049 iterator pointer_end() { return PointerTypes.end(); }
5050
Sebastian Redl78eb8742009-04-19 21:53:20 +00005051 /// member_pointer_begin - First member pointer type found;
5052 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5053
5054 /// member_pointer_end - Past the last member pointer type found;
5055 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5056
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005057 /// enumeration_begin - First enumeration type found;
5058 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5059
Sebastian Redl78eb8742009-04-19 21:53:20 +00005060 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005061 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005062
Douglas Gregor26bcf672010-05-19 03:21:00 +00005063 iterator vector_begin() { return VectorTypes.begin(); }
5064 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00005065
5066 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5067 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005068 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005069};
5070
Sebastian Redl78eb8742009-04-19 21:53:20 +00005071/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005072/// the set of pointer types along with any more-qualified variants of
5073/// that type. For example, if @p Ty is "int const *", this routine
5074/// will add "int const *", "int const volatile *", "int const
5075/// restrict *", and "int const volatile restrict *" to the set of
5076/// pointer types. Returns true if the add of @p Ty itself succeeded,
5077/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00005078///
5079/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00005080bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00005081BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5082 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00005083
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005084 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005085 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005086 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005087
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005088 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00005089 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005090 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005091 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005092 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005093 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005094 buildObjCPtr = true;
5095 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005096 else
David Blaikieb219cfc2011-09-23 05:06:16 +00005097 llvm_unreachable("type was not a pointer type!");
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005098 }
5099 else
5100 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005101
Sebastian Redla9efada2009-11-18 20:39:26 +00005102 // Don't add qualified variants of arrays. For one, they're not allowed
5103 // (the qualifier would sink to the element type), and for another, the
5104 // only overload situation where it matters is subscript or pointer +- int,
5105 // and those shouldn't have qualifier variants anyway.
5106 if (PointeeTy->isArrayType())
5107 return true;
John McCall0953e762009-09-24 19:53:00 +00005108 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00005109 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00005110 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005111 bool hasVolatile = VisibleQuals.hasVolatile();
5112 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005113
John McCall0953e762009-09-24 19:53:00 +00005114 // Iterate through all strict supersets of BaseCVR.
5115 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5116 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005117 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5118 // in the types.
5119 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5120 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00005121 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005122 if (!buildObjCPtr)
5123 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5124 else
5125 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005126 }
5127
5128 return true;
5129}
5130
Sebastian Redl78eb8742009-04-19 21:53:20 +00005131/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5132/// to the set of pointer types along with any more-qualified variants of
5133/// that type. For example, if @p Ty is "int const *", this routine
5134/// will add "int const *", "int const volatile *", "int const
5135/// restrict *", and "int const volatile restrict *" to the set of
5136/// pointer types. Returns true if the add of @p Ty itself succeeded,
5137/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00005138///
5139/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00005140bool
5141BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5142 QualType Ty) {
5143 // Insert this type.
5144 if (!MemberPointerTypes.insert(Ty))
5145 return false;
5146
John McCall0953e762009-09-24 19:53:00 +00005147 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5148 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00005149
John McCall0953e762009-09-24 19:53:00 +00005150 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00005151 // Don't add qualified variants of arrays. For one, they're not allowed
5152 // (the qualifier would sink to the element type), and for another, the
5153 // only overload situation where it matters is subscript or pointer +- int,
5154 // and those shouldn't have qualifier variants anyway.
5155 if (PointeeTy->isArrayType())
5156 return true;
John McCall0953e762009-09-24 19:53:00 +00005157 const Type *ClassTy = PointerTy->getClass();
5158
5159 // Iterate through all strict supersets of the pointee type's CVR
5160 // qualifiers.
5161 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5162 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5163 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005164
John McCall0953e762009-09-24 19:53:00 +00005165 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00005166 MemberPointerTypes.insert(
5167 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00005168 }
5169
5170 return true;
5171}
5172
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005173/// AddTypesConvertedFrom - Add each of the types to which the type @p
5174/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00005175/// primarily interested in pointer types and enumeration types. We also
5176/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005177/// AllowUserConversions is true if we should look at the conversion
5178/// functions of a class type, and AllowExplicitConversions if we
5179/// should also include the explicit conversion functions of a class
5180/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00005181void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005182BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00005183 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005184 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005185 bool AllowExplicitConversions,
5186 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005187 // Only deal with canonical types.
5188 Ty = Context.getCanonicalType(Ty);
5189
5190 // Look through reference types; they aren't part of the type of an
5191 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00005192 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005193 Ty = RefTy->getPointeeType();
5194
John McCall3b657512011-01-19 10:06:00 +00005195 // If we're dealing with an array type, decay to the pointer.
5196 if (Ty->isArrayType())
5197 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5198
5199 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005200 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005201
Chandler Carruth6a577462010-12-13 01:44:01 +00005202 // Flag if we ever add a non-record type.
5203 const RecordType *TyRec = Ty->getAs<RecordType>();
5204 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5205
Chandler Carruth6a577462010-12-13 01:44:01 +00005206 // Flag if we encounter an arithmetic type.
5207 HasArithmeticOrEnumeralTypes =
5208 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5209
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005210 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5211 PointerTypes.insert(Ty);
5212 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005213 // Insert our type, and its more-qualified variants, into the set
5214 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005215 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005216 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00005217 } else if (Ty->isMemberPointerType()) {
5218 // Member pointers are far easier, since the pointee can't be converted.
5219 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5220 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005221 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005222 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00005223 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00005224 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005225 // We treat vector types as arithmetic types in many contexts as an
5226 // extension.
5227 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00005228 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005229 } else if (Ty->isNullPtrType()) {
5230 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00005231 } else if (AllowUserConversions && TyRec) {
5232 // No conversion functions in incomplete types.
5233 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5234 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005235
Chandler Carruth6a577462010-12-13 01:44:01 +00005236 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5237 const UnresolvedSetImpl *Conversions
5238 = ClassDecl->getVisibleConversionFunctions();
5239 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5240 E = Conversions->end(); I != E; ++I) {
5241 NamedDecl *D = I.getDecl();
5242 if (isa<UsingShadowDecl>(D))
5243 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005244
Chandler Carruth6a577462010-12-13 01:44:01 +00005245 // Skip conversion function templates; they don't tell us anything
5246 // about which builtin types we can convert to.
5247 if (isa<FunctionTemplateDecl>(D))
5248 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005249
Chandler Carruth6a577462010-12-13 01:44:01 +00005250 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5251 if (AllowExplicitConversions || !Conv->isExplicit()) {
5252 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5253 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005254 }
5255 }
5256 }
5257}
5258
Douglas Gregor19b7b152009-08-24 13:43:27 +00005259/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5260/// the volatile- and non-volatile-qualified assignment operators for the
5261/// given type to the candidate set.
5262static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5263 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00005264 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00005265 unsigned NumArgs,
5266 OverloadCandidateSet &CandidateSet) {
5267 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00005268
Douglas Gregor19b7b152009-08-24 13:43:27 +00005269 // T& operator=(T&, T)
5270 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5271 ParamTypes[1] = T;
5272 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5273 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00005274
Douglas Gregor19b7b152009-08-24 13:43:27 +00005275 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5276 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00005277 ParamTypes[0]
5278 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00005279 ParamTypes[1] = T;
5280 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00005281 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00005282 }
5283}
Mike Stump1eb44332009-09-09 15:08:12 +00005284
Sebastian Redl9994a342009-10-25 17:03:50 +00005285/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5286/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005287static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5288 Qualifiers VRQuals;
5289 const RecordType *TyRec;
5290 if (const MemberPointerType *RHSMPType =
5291 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00005292 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005293 else
5294 TyRec = ArgExpr->getType()->getAs<RecordType>();
5295 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005296 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005297 VRQuals.addVolatile();
5298 VRQuals.addRestrict();
5299 return VRQuals;
5300 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005301
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005302 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00005303 if (!ClassDecl->hasDefinition())
5304 return VRQuals;
5305
John McCalleec51cf2010-01-20 00:46:10 +00005306 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00005307 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005308
John McCalleec51cf2010-01-20 00:46:10 +00005309 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00005310 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00005311 NamedDecl *D = I.getDecl();
5312 if (isa<UsingShadowDecl>(D))
5313 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5314 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005315 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5316 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5317 CanTy = ResTypeRef->getPointeeType();
5318 // Need to go down the pointer/mempointer chain and add qualifiers
5319 // as see them.
5320 bool done = false;
5321 while (!done) {
5322 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5323 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005324 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005325 CanTy->getAs<MemberPointerType>())
5326 CanTy = ResTypeMPtr->getPointeeType();
5327 else
5328 done = true;
5329 if (CanTy.isVolatileQualified())
5330 VRQuals.addVolatile();
5331 if (CanTy.isRestrictQualified())
5332 VRQuals.addRestrict();
5333 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5334 return VRQuals;
5335 }
5336 }
5337 }
5338 return VRQuals;
5339}
John McCall00071ec2010-11-13 05:51:15 +00005340
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005341namespace {
John McCall00071ec2010-11-13 05:51:15 +00005342
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005343/// \brief Helper class to manage the addition of builtin operator overload
5344/// candidates. It provides shared state and utility methods used throughout
5345/// the process, as well as a helper method to add each group of builtin
5346/// operator overloads from the standard to a candidate set.
5347class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00005348 // Common instance state available to all overload candidate addition methods.
5349 Sema &S;
5350 Expr **Args;
5351 unsigned NumArgs;
5352 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00005353 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005354 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00005355 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005356
Chandler Carruth6d695582010-12-12 10:35:00 +00005357 // Define some constants used to index and iterate over the arithemetic types
5358 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00005359 // The "promoted arithmetic types" are the arithmetic
5360 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00005361 static const unsigned FirstIntegralType = 3;
5362 static const unsigned LastIntegralType = 18;
5363 static const unsigned FirstPromotedIntegralType = 3,
5364 LastPromotedIntegralType = 9;
5365 static const unsigned FirstPromotedArithmeticType = 0,
5366 LastPromotedArithmeticType = 9;
5367 static const unsigned NumArithmeticTypes = 18;
5368
Chandler Carruth6d695582010-12-12 10:35:00 +00005369 /// \brief Get the canonical type for a given arithmetic type index.
5370 CanQualType getArithmeticType(unsigned index) {
5371 assert(index < NumArithmeticTypes);
5372 static CanQualType ASTContext::* const
5373 ArithmeticTypes[NumArithmeticTypes] = {
5374 // Start of promoted types.
5375 &ASTContext::FloatTy,
5376 &ASTContext::DoubleTy,
5377 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00005378
Chandler Carruth6d695582010-12-12 10:35:00 +00005379 // Start of integral types.
5380 &ASTContext::IntTy,
5381 &ASTContext::LongTy,
5382 &ASTContext::LongLongTy,
5383 &ASTContext::UnsignedIntTy,
5384 &ASTContext::UnsignedLongTy,
5385 &ASTContext::UnsignedLongLongTy,
5386 // End of promoted types.
5387
5388 &ASTContext::BoolTy,
5389 &ASTContext::CharTy,
5390 &ASTContext::WCharTy,
5391 &ASTContext::Char16Ty,
5392 &ASTContext::Char32Ty,
5393 &ASTContext::SignedCharTy,
5394 &ASTContext::ShortTy,
5395 &ASTContext::UnsignedCharTy,
5396 &ASTContext::UnsignedShortTy,
5397 // End of integral types.
5398 // FIXME: What about complex?
5399 };
5400 return S.Context.*ArithmeticTypes[index];
5401 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005402
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005403 /// \brief Gets the canonical type resulting from the usual arithemetic
5404 /// converions for the given arithmetic types.
5405 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5406 // Accelerator table for performing the usual arithmetic conversions.
5407 // The rules are basically:
5408 // - if either is floating-point, use the wider floating-point
5409 // - if same signedness, use the higher rank
5410 // - if same size, use unsigned of the higher rank
5411 // - use the larger type
5412 // These rules, together with the axiom that higher ranks are
5413 // never smaller, are sufficient to precompute all of these results
5414 // *except* when dealing with signed types of higher rank.
5415 // (we could precompute SLL x UI for all known platforms, but it's
5416 // better not to make any assumptions).
5417 enum PromotedType {
5418 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5419 };
5420 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5421 [LastPromotedArithmeticType] = {
5422 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5423 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5424 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5425 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5426 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5427 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5428 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5429 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5430 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5431 };
5432
5433 assert(L < LastPromotedArithmeticType);
5434 assert(R < LastPromotedArithmeticType);
5435 int Idx = ConversionsTable[L][R];
5436
5437 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00005438 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005439
5440 // Slow path: we need to compare widths.
5441 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00005442 CanQualType LT = getArithmeticType(L),
5443 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005444 unsigned LW = S.Context.getIntWidth(LT),
5445 RW = S.Context.getIntWidth(RT);
5446
5447 // If they're different widths, use the signed type.
5448 if (LW > RW) return LT;
5449 else if (LW < RW) return RT;
5450
5451 // Otherwise, use the unsigned type of the signed type's rank.
5452 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5453 assert(L == SLL || R == SLL);
5454 return S.Context.UnsignedLongLongTy;
5455 }
5456
Chandler Carruth3c69dc42010-12-12 09:22:45 +00005457 /// \brief Helper method to factor out the common pattern of adding overloads
5458 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005459 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5460 bool HasVolatile) {
5461 QualType ParamTypes[2] = {
5462 S.Context.getLValueReferenceType(CandidateTy),
5463 S.Context.IntTy
5464 };
5465
5466 // Non-volatile version.
5467 if (NumArgs == 1)
5468 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5469 else
5470 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5471
5472 // Use a heuristic to reduce number of builtin candidates in the set:
5473 // add volatile version only if there are conversions to a volatile type.
5474 if (HasVolatile) {
5475 ParamTypes[0] =
5476 S.Context.getLValueReferenceType(
5477 S.Context.getVolatileType(CandidateTy));
5478 if (NumArgs == 1)
5479 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5480 else
5481 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5482 }
5483 }
5484
5485public:
5486 BuiltinOperatorOverloadBuilder(
5487 Sema &S, Expr **Args, unsigned NumArgs,
5488 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00005489 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005490 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005491 OverloadCandidateSet &CandidateSet)
5492 : S(S), Args(Args), NumArgs(NumArgs),
5493 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00005494 HasArithmeticOrEnumeralCandidateType(
5495 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005496 CandidateTypes(CandidateTypes),
5497 CandidateSet(CandidateSet) {
5498 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00005499 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005500 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005501 assert(getArithmeticType(LastPromotedIntegralType - 1)
5502 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005503 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005504 assert(getArithmeticType(FirstPromotedArithmeticType)
5505 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005506 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005507 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5508 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005509 "Invalid last promoted arithmetic type");
5510 }
5511
5512 // C++ [over.built]p3:
5513 //
5514 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5515 // is either volatile or empty, there exist candidate operator
5516 // functions of the form
5517 //
5518 // VQ T& operator++(VQ T&);
5519 // T operator++(VQ T&, int);
5520 //
5521 // C++ [over.built]p4:
5522 //
5523 // For every pair (T, VQ), where T is an arithmetic type other
5524 // than bool, and VQ is either volatile or empty, there exist
5525 // candidate operator functions of the form
5526 //
5527 // VQ T& operator--(VQ T&);
5528 // T operator--(VQ T&, int);
5529 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005530 if (!HasArithmeticOrEnumeralCandidateType)
5531 return;
5532
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005533 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5534 Arith < NumArithmeticTypes; ++Arith) {
5535 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00005536 getArithmeticType(Arith),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005537 VisibleTypeConversionsQuals.hasVolatile());
5538 }
5539 }
5540
5541 // C++ [over.built]p5:
5542 //
5543 // For every pair (T, VQ), where T is a cv-qualified or
5544 // cv-unqualified object type, and VQ is either volatile or
5545 // empty, there exist candidate operator functions of the form
5546 //
5547 // T*VQ& operator++(T*VQ&);
5548 // T*VQ& operator--(T*VQ&);
5549 // T* operator++(T*VQ&, int);
5550 // T* operator--(T*VQ&, int);
5551 void addPlusPlusMinusMinusPointerOverloads() {
5552 for (BuiltinCandidateTypeSet::iterator
5553 Ptr = CandidateTypes[0].pointer_begin(),
5554 PtrEnd = CandidateTypes[0].pointer_end();
5555 Ptr != PtrEnd; ++Ptr) {
5556 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005557 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005558 continue;
5559
5560 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5561 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5562 VisibleTypeConversionsQuals.hasVolatile()));
5563 }
5564 }
5565
5566 // C++ [over.built]p6:
5567 // For every cv-qualified or cv-unqualified object type T, there
5568 // exist candidate operator functions of the form
5569 //
5570 // T& operator*(T*);
5571 //
5572 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005573 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005574 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005575 // T& operator*(T*);
5576 void addUnaryStarPointerOverloads() {
5577 for (BuiltinCandidateTypeSet::iterator
5578 Ptr = CandidateTypes[0].pointer_begin(),
5579 PtrEnd = CandidateTypes[0].pointer_end();
5580 Ptr != PtrEnd; ++Ptr) {
5581 QualType ParamTy = *Ptr;
5582 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005583 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5584 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005585
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005586 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5587 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5588 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005589
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005590 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5591 &ParamTy, Args, 1, CandidateSet);
5592 }
5593 }
5594
5595 // C++ [over.built]p9:
5596 // For every promoted arithmetic type T, there exist candidate
5597 // operator functions of the form
5598 //
5599 // T operator+(T);
5600 // T operator-(T);
5601 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00005602 if (!HasArithmeticOrEnumeralCandidateType)
5603 return;
5604
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005605 for (unsigned Arith = FirstPromotedArithmeticType;
5606 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005607 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005608 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5609 }
5610
5611 // Extension: We also add these operators for vector types.
5612 for (BuiltinCandidateTypeSet::iterator
5613 Vec = CandidateTypes[0].vector_begin(),
5614 VecEnd = CandidateTypes[0].vector_end();
5615 Vec != VecEnd; ++Vec) {
5616 QualType VecTy = *Vec;
5617 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5618 }
5619 }
5620
5621 // C++ [over.built]p8:
5622 // For every type T, there exist candidate operator functions of
5623 // the form
5624 //
5625 // T* operator+(T*);
5626 void addUnaryPlusPointerOverloads() {
5627 for (BuiltinCandidateTypeSet::iterator
5628 Ptr = CandidateTypes[0].pointer_begin(),
5629 PtrEnd = CandidateTypes[0].pointer_end();
5630 Ptr != PtrEnd; ++Ptr) {
5631 QualType ParamTy = *Ptr;
5632 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5633 }
5634 }
5635
5636 // C++ [over.built]p10:
5637 // For every promoted integral type T, there exist candidate
5638 // operator functions of the form
5639 //
5640 // T operator~(T);
5641 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00005642 if (!HasArithmeticOrEnumeralCandidateType)
5643 return;
5644
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005645 for (unsigned Int = FirstPromotedIntegralType;
5646 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005647 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005648 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5649 }
5650
5651 // Extension: We also add this operator for vector types.
5652 for (BuiltinCandidateTypeSet::iterator
5653 Vec = CandidateTypes[0].vector_begin(),
5654 VecEnd = CandidateTypes[0].vector_end();
5655 Vec != VecEnd; ++Vec) {
5656 QualType VecTy = *Vec;
5657 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5658 }
5659 }
5660
5661 // C++ [over.match.oper]p16:
5662 // For every pointer to member type T, there exist candidate operator
5663 // functions of the form
5664 //
5665 // bool operator==(T,T);
5666 // bool operator!=(T,T);
5667 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5668 /// Set of (canonical) types that we've already handled.
5669 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5670
5671 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5672 for (BuiltinCandidateTypeSet::iterator
5673 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5674 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5675 MemPtr != MemPtrEnd;
5676 ++MemPtr) {
5677 // Don't add the same builtin candidate twice.
5678 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5679 continue;
5680
5681 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5682 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5683 CandidateSet);
5684 }
5685 }
5686 }
5687
5688 // C++ [over.built]p15:
5689 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005690 // For every T, where T is an enumeration type, a pointer type, or
5691 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005692 //
5693 // bool operator<(T, T);
5694 // bool operator>(T, T);
5695 // bool operator<=(T, T);
5696 // bool operator>=(T, T);
5697 // bool operator==(T, T);
5698 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005699 void addRelationalPointerOrEnumeralOverloads() {
5700 // C++ [over.built]p1:
5701 // If there is a user-written candidate with the same name and parameter
5702 // types as a built-in candidate operator function, the built-in operator
5703 // function is hidden and is not included in the set of candidate
5704 // functions.
5705 //
5706 // The text is actually in a note, but if we don't implement it then we end
5707 // up with ambiguities when the user provides an overloaded operator for
5708 // an enumeration type. Note that only enumeration types have this problem,
5709 // so we track which enumeration types we've seen operators for. Also, the
5710 // only other overloaded operator with enumeration argumenst, operator=,
5711 // cannot be overloaded for enumeration types, so this is the only place
5712 // where we must suppress candidates like this.
5713 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5714 UserDefinedBinaryOperators;
5715
5716 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5717 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5718 CandidateTypes[ArgIdx].enumeration_end()) {
5719 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5720 CEnd = CandidateSet.end();
5721 C != CEnd; ++C) {
5722 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5723 continue;
5724
5725 QualType FirstParamType =
5726 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5727 QualType SecondParamType =
5728 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5729
5730 // Skip if either parameter isn't of enumeral type.
5731 if (!FirstParamType->isEnumeralType() ||
5732 !SecondParamType->isEnumeralType())
5733 continue;
5734
5735 // Add this operator to the set of known user-defined operators.
5736 UserDefinedBinaryOperators.insert(
5737 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5738 S.Context.getCanonicalType(SecondParamType)));
5739 }
5740 }
5741 }
5742
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005743 /// Set of (canonical) types that we've already handled.
5744 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5745
5746 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5747 for (BuiltinCandidateTypeSet::iterator
5748 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5749 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5750 Ptr != PtrEnd; ++Ptr) {
5751 // Don't add the same builtin candidate twice.
5752 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5753 continue;
5754
5755 QualType ParamTypes[2] = { *Ptr, *Ptr };
5756 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5757 CandidateSet);
5758 }
5759 for (BuiltinCandidateTypeSet::iterator
5760 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5761 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5762 Enum != EnumEnd; ++Enum) {
5763 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5764
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005765 // Don't add the same builtin candidate twice, or if a user defined
5766 // candidate exists.
5767 if (!AddedTypes.insert(CanonType) ||
5768 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5769 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005770 continue;
5771
5772 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005773 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5774 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005775 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005776
5777 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5778 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5779 if (AddedTypes.insert(NullPtrTy) &&
5780 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
5781 NullPtrTy))) {
5782 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5783 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5784 CandidateSet);
5785 }
5786 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005787 }
5788 }
5789
5790 // C++ [over.built]p13:
5791 //
5792 // For every cv-qualified or cv-unqualified object type T
5793 // there exist candidate operator functions of the form
5794 //
5795 // T* operator+(T*, ptrdiff_t);
5796 // T& operator[](T*, ptrdiff_t); [BELOW]
5797 // T* operator-(T*, ptrdiff_t);
5798 // T* operator+(ptrdiff_t, T*);
5799 // T& operator[](ptrdiff_t, T*); [BELOW]
5800 //
5801 // C++ [over.built]p14:
5802 //
5803 // For every T, where T is a pointer to object type, there
5804 // exist candidate operator functions of the form
5805 //
5806 // ptrdiff_t operator-(T, T);
5807 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5808 /// Set of (canonical) types that we've already handled.
5809 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5810
5811 for (int Arg = 0; Arg < 2; ++Arg) {
5812 QualType AsymetricParamTypes[2] = {
5813 S.Context.getPointerDiffType(),
5814 S.Context.getPointerDiffType(),
5815 };
5816 for (BuiltinCandidateTypeSet::iterator
5817 Ptr = CandidateTypes[Arg].pointer_begin(),
5818 PtrEnd = CandidateTypes[Arg].pointer_end();
5819 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005820 QualType PointeeTy = (*Ptr)->getPointeeType();
5821 if (!PointeeTy->isObjectType())
5822 continue;
5823
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005824 AsymetricParamTypes[Arg] = *Ptr;
5825 if (Arg == 0 || Op == OO_Plus) {
5826 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5827 // T* operator+(ptrdiff_t, T*);
5828 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5829 CandidateSet);
5830 }
5831 if (Op == OO_Minus) {
5832 // ptrdiff_t operator-(T, T);
5833 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5834 continue;
5835
5836 QualType ParamTypes[2] = { *Ptr, *Ptr };
5837 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5838 Args, 2, CandidateSet);
5839 }
5840 }
5841 }
5842 }
5843
5844 // C++ [over.built]p12:
5845 //
5846 // For every pair of promoted arithmetic types L and R, there
5847 // exist candidate operator functions of the form
5848 //
5849 // LR operator*(L, R);
5850 // LR operator/(L, R);
5851 // LR operator+(L, R);
5852 // LR operator-(L, R);
5853 // bool operator<(L, R);
5854 // bool operator>(L, R);
5855 // bool operator<=(L, R);
5856 // bool operator>=(L, R);
5857 // bool operator==(L, R);
5858 // bool operator!=(L, R);
5859 //
5860 // where LR is the result of the usual arithmetic conversions
5861 // between types L and R.
5862 //
5863 // C++ [over.built]p24:
5864 //
5865 // For every pair of promoted arithmetic types L and R, there exist
5866 // candidate operator functions of the form
5867 //
5868 // LR operator?(bool, L, R);
5869 //
5870 // where LR is the result of the usual arithmetic conversions
5871 // between types L and R.
5872 // Our candidates ignore the first parameter.
5873 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005874 if (!HasArithmeticOrEnumeralCandidateType)
5875 return;
5876
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005877 for (unsigned Left = FirstPromotedArithmeticType;
5878 Left < LastPromotedArithmeticType; ++Left) {
5879 for (unsigned Right = FirstPromotedArithmeticType;
5880 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005881 QualType LandR[2] = { getArithmeticType(Left),
5882 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005883 QualType Result =
5884 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005885 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005886 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5887 }
5888 }
5889
5890 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5891 // conditional operator for vector types.
5892 for (BuiltinCandidateTypeSet::iterator
5893 Vec1 = CandidateTypes[0].vector_begin(),
5894 Vec1End = CandidateTypes[0].vector_end();
5895 Vec1 != Vec1End; ++Vec1) {
5896 for (BuiltinCandidateTypeSet::iterator
5897 Vec2 = CandidateTypes[1].vector_begin(),
5898 Vec2End = CandidateTypes[1].vector_end();
5899 Vec2 != Vec2End; ++Vec2) {
5900 QualType LandR[2] = { *Vec1, *Vec2 };
5901 QualType Result = S.Context.BoolTy;
5902 if (!isComparison) {
5903 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5904 Result = *Vec1;
5905 else
5906 Result = *Vec2;
5907 }
5908
5909 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5910 }
5911 }
5912 }
5913
5914 // C++ [over.built]p17:
5915 //
5916 // For every pair of promoted integral types L and R, there
5917 // exist candidate operator functions of the form
5918 //
5919 // LR operator%(L, R);
5920 // LR operator&(L, R);
5921 // LR operator^(L, R);
5922 // LR operator|(L, R);
5923 // L operator<<(L, R);
5924 // L operator>>(L, R);
5925 //
5926 // where LR is the result of the usual arithmetic conversions
5927 // between types L and R.
5928 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005929 if (!HasArithmeticOrEnumeralCandidateType)
5930 return;
5931
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005932 for (unsigned Left = FirstPromotedIntegralType;
5933 Left < LastPromotedIntegralType; ++Left) {
5934 for (unsigned Right = FirstPromotedIntegralType;
5935 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005936 QualType LandR[2] = { getArithmeticType(Left),
5937 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005938 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5939 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005940 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005941 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5942 }
5943 }
5944 }
5945
5946 // C++ [over.built]p20:
5947 //
5948 // For every pair (T, VQ), where T is an enumeration or
5949 // pointer to member type and VQ is either volatile or
5950 // empty, there exist candidate operator functions of the form
5951 //
5952 // VQ T& operator=(VQ T&, T);
5953 void addAssignmentMemberPointerOrEnumeralOverloads() {
5954 /// Set of (canonical) types that we've already handled.
5955 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5956
5957 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5958 for (BuiltinCandidateTypeSet::iterator
5959 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5960 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5961 Enum != EnumEnd; ++Enum) {
5962 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5963 continue;
5964
5965 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5966 CandidateSet);
5967 }
5968
5969 for (BuiltinCandidateTypeSet::iterator
5970 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5971 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5972 MemPtr != MemPtrEnd; ++MemPtr) {
5973 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5974 continue;
5975
5976 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5977 CandidateSet);
5978 }
5979 }
5980 }
5981
5982 // C++ [over.built]p19:
5983 //
5984 // For every pair (T, VQ), where T is any type and VQ is either
5985 // volatile or empty, there exist candidate operator functions
5986 // of the form
5987 //
5988 // T*VQ& operator=(T*VQ&, T*);
5989 //
5990 // C++ [over.built]p21:
5991 //
5992 // For every pair (T, VQ), where T is a cv-qualified or
5993 // cv-unqualified object type and VQ is either volatile or
5994 // empty, there exist candidate operator functions of the form
5995 //
5996 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5997 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5998 void addAssignmentPointerOverloads(bool isEqualOp) {
5999 /// Set of (canonical) types that we've already handled.
6000 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6001
6002 for (BuiltinCandidateTypeSet::iterator
6003 Ptr = CandidateTypes[0].pointer_begin(),
6004 PtrEnd = CandidateTypes[0].pointer_end();
6005 Ptr != PtrEnd; ++Ptr) {
6006 // If this is operator=, keep track of the builtin candidates we added.
6007 if (isEqualOp)
6008 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006009 else if (!(*Ptr)->getPointeeType()->isObjectType())
6010 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006011
6012 // non-volatile version
6013 QualType ParamTypes[2] = {
6014 S.Context.getLValueReferenceType(*Ptr),
6015 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6016 };
6017 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6018 /*IsAssigmentOperator=*/ isEqualOp);
6019
6020 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6021 VisibleTypeConversionsQuals.hasVolatile()) {
6022 // volatile version
6023 ParamTypes[0] =
6024 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6025 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6026 /*IsAssigmentOperator=*/isEqualOp);
6027 }
6028 }
6029
6030 if (isEqualOp) {
6031 for (BuiltinCandidateTypeSet::iterator
6032 Ptr = CandidateTypes[1].pointer_begin(),
6033 PtrEnd = CandidateTypes[1].pointer_end();
6034 Ptr != PtrEnd; ++Ptr) {
6035 // Make sure we don't add the same candidate twice.
6036 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6037 continue;
6038
Chandler Carruth6df868e2010-12-12 08:17:55 +00006039 QualType ParamTypes[2] = {
6040 S.Context.getLValueReferenceType(*Ptr),
6041 *Ptr,
6042 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006043
6044 // non-volatile version
6045 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6046 /*IsAssigmentOperator=*/true);
6047
6048 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6049 VisibleTypeConversionsQuals.hasVolatile()) {
6050 // volatile version
6051 ParamTypes[0] =
6052 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00006053 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6054 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006055 }
6056 }
6057 }
6058 }
6059
6060 // C++ [over.built]p18:
6061 //
6062 // For every triple (L, VQ, R), where L is an arithmetic type,
6063 // VQ is either volatile or empty, and R is a promoted
6064 // arithmetic type, there exist candidate operator functions of
6065 // the form
6066 //
6067 // VQ L& operator=(VQ L&, R);
6068 // VQ L& operator*=(VQ L&, R);
6069 // VQ L& operator/=(VQ L&, R);
6070 // VQ L& operator+=(VQ L&, R);
6071 // VQ L& operator-=(VQ L&, R);
6072 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006073 if (!HasArithmeticOrEnumeralCandidateType)
6074 return;
6075
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006076 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6077 for (unsigned Right = FirstPromotedArithmeticType;
6078 Right < LastPromotedArithmeticType; ++Right) {
6079 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00006080 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006081
6082 // Add this built-in operator as a candidate (VQ is empty).
6083 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006084 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006085 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6086 /*IsAssigmentOperator=*/isEqualOp);
6087
6088 // Add this built-in operator as a candidate (VQ is 'volatile').
6089 if (VisibleTypeConversionsQuals.hasVolatile()) {
6090 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006091 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006092 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006093 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6094 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006095 /*IsAssigmentOperator=*/isEqualOp);
6096 }
6097 }
6098 }
6099
6100 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6101 for (BuiltinCandidateTypeSet::iterator
6102 Vec1 = CandidateTypes[0].vector_begin(),
6103 Vec1End = CandidateTypes[0].vector_end();
6104 Vec1 != Vec1End; ++Vec1) {
6105 for (BuiltinCandidateTypeSet::iterator
6106 Vec2 = CandidateTypes[1].vector_begin(),
6107 Vec2End = CandidateTypes[1].vector_end();
6108 Vec2 != Vec2End; ++Vec2) {
6109 QualType ParamTypes[2];
6110 ParamTypes[1] = *Vec2;
6111 // Add this built-in operator as a candidate (VQ is empty).
6112 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6113 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6114 /*IsAssigmentOperator=*/isEqualOp);
6115
6116 // Add this built-in operator as a candidate (VQ is 'volatile').
6117 if (VisibleTypeConversionsQuals.hasVolatile()) {
6118 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6119 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006120 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6121 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006122 /*IsAssigmentOperator=*/isEqualOp);
6123 }
6124 }
6125 }
6126 }
6127
6128 // C++ [over.built]p22:
6129 //
6130 // For every triple (L, VQ, R), where L is an integral type, VQ
6131 // is either volatile or empty, and R is a promoted integral
6132 // type, there exist candidate operator functions of the form
6133 //
6134 // VQ L& operator%=(VQ L&, R);
6135 // VQ L& operator<<=(VQ L&, R);
6136 // VQ L& operator>>=(VQ L&, R);
6137 // VQ L& operator&=(VQ L&, R);
6138 // VQ L& operator^=(VQ L&, R);
6139 // VQ L& operator|=(VQ L&, R);
6140 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006141 if (!HasArithmeticOrEnumeralCandidateType)
6142 return;
6143
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006144 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6145 for (unsigned Right = FirstPromotedIntegralType;
6146 Right < LastPromotedIntegralType; ++Right) {
6147 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00006148 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006149
6150 // Add this built-in operator as a candidate (VQ is empty).
6151 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006152 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006153 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6154 if (VisibleTypeConversionsQuals.hasVolatile()) {
6155 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00006156 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006157 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6158 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6159 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6160 CandidateSet);
6161 }
6162 }
6163 }
6164 }
6165
6166 // C++ [over.operator]p23:
6167 //
6168 // There also exist candidate operator functions of the form
6169 //
6170 // bool operator!(bool);
6171 // bool operator&&(bool, bool);
6172 // bool operator||(bool, bool);
6173 void addExclaimOverload() {
6174 QualType ParamTy = S.Context.BoolTy;
6175 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6176 /*IsAssignmentOperator=*/false,
6177 /*NumContextualBoolArguments=*/1);
6178 }
6179 void addAmpAmpOrPipePipeOverload() {
6180 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6181 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6182 /*IsAssignmentOperator=*/false,
6183 /*NumContextualBoolArguments=*/2);
6184 }
6185
6186 // C++ [over.built]p13:
6187 //
6188 // For every cv-qualified or cv-unqualified object type T there
6189 // exist candidate operator functions of the form
6190 //
6191 // T* operator+(T*, ptrdiff_t); [ABOVE]
6192 // T& operator[](T*, ptrdiff_t);
6193 // T* operator-(T*, ptrdiff_t); [ABOVE]
6194 // T* operator+(ptrdiff_t, T*); [ABOVE]
6195 // T& operator[](ptrdiff_t, T*);
6196 void addSubscriptOverloads() {
6197 for (BuiltinCandidateTypeSet::iterator
6198 Ptr = CandidateTypes[0].pointer_begin(),
6199 PtrEnd = CandidateTypes[0].pointer_end();
6200 Ptr != PtrEnd; ++Ptr) {
6201 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6202 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006203 if (!PointeeType->isObjectType())
6204 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006205
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006206 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6207
6208 // T& operator[](T*, ptrdiff_t)
6209 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6210 }
6211
6212 for (BuiltinCandidateTypeSet::iterator
6213 Ptr = CandidateTypes[1].pointer_begin(),
6214 PtrEnd = CandidateTypes[1].pointer_end();
6215 Ptr != PtrEnd; ++Ptr) {
6216 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6217 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006218 if (!PointeeType->isObjectType())
6219 continue;
6220
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006221 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6222
6223 // T& operator[](ptrdiff_t, T*)
6224 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6225 }
6226 }
6227
6228 // C++ [over.built]p11:
6229 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6230 // C1 is the same type as C2 or is a derived class of C2, T is an object
6231 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6232 // there exist candidate operator functions of the form
6233 //
6234 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6235 //
6236 // where CV12 is the union of CV1 and CV2.
6237 void addArrowStarOverloads() {
6238 for (BuiltinCandidateTypeSet::iterator
6239 Ptr = CandidateTypes[0].pointer_begin(),
6240 PtrEnd = CandidateTypes[0].pointer_end();
6241 Ptr != PtrEnd; ++Ptr) {
6242 QualType C1Ty = (*Ptr);
6243 QualType C1;
6244 QualifierCollector Q1;
6245 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6246 if (!isa<RecordType>(C1))
6247 continue;
6248 // heuristic to reduce number of builtin candidates in the set.
6249 // Add volatile/restrict version only if there are conversions to a
6250 // volatile/restrict type.
6251 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6252 continue;
6253 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6254 continue;
6255 for (BuiltinCandidateTypeSet::iterator
6256 MemPtr = CandidateTypes[1].member_pointer_begin(),
6257 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6258 MemPtr != MemPtrEnd; ++MemPtr) {
6259 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6260 QualType C2 = QualType(mptr->getClass(), 0);
6261 C2 = C2.getUnqualifiedType();
6262 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6263 break;
6264 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6265 // build CV12 T&
6266 QualType T = mptr->getPointeeType();
6267 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6268 T.isVolatileQualified())
6269 continue;
6270 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6271 T.isRestrictQualified())
6272 continue;
6273 T = Q1.apply(S.Context, T);
6274 QualType ResultTy = S.Context.getLValueReferenceType(T);
6275 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6276 }
6277 }
6278 }
6279
6280 // Note that we don't consider the first argument, since it has been
6281 // contextually converted to bool long ago. The candidates below are
6282 // therefore added as binary.
6283 //
6284 // C++ [over.built]p25:
6285 // For every type T, where T is a pointer, pointer-to-member, or scoped
6286 // enumeration type, there exist candidate operator functions of the form
6287 //
6288 // T operator?(bool, T, T);
6289 //
6290 void addConditionalOperatorOverloads() {
6291 /// Set of (canonical) types that we've already handled.
6292 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6293
6294 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6295 for (BuiltinCandidateTypeSet::iterator
6296 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6297 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6298 Ptr != PtrEnd; ++Ptr) {
6299 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6300 continue;
6301
6302 QualType ParamTypes[2] = { *Ptr, *Ptr };
6303 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6304 }
6305
6306 for (BuiltinCandidateTypeSet::iterator
6307 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6308 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6309 MemPtr != MemPtrEnd; ++MemPtr) {
6310 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6311 continue;
6312
6313 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6314 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6315 }
6316
6317 if (S.getLangOptions().CPlusPlus0x) {
6318 for (BuiltinCandidateTypeSet::iterator
6319 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6320 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6321 Enum != EnumEnd; ++Enum) {
6322 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6323 continue;
6324
6325 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6326 continue;
6327
6328 QualType ParamTypes[2] = { *Enum, *Enum };
6329 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6330 }
6331 }
6332 }
6333 }
6334};
6335
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006336} // end anonymous namespace
6337
6338/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6339/// operator overloads to the candidate set (C++ [over.built]), based
6340/// on the operator @p Op and the arguments given. For example, if the
6341/// operator is a binary '+', this routine might add "int
6342/// operator+(int, int)" to cover integer addition.
6343void
6344Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6345 SourceLocation OpLoc,
6346 Expr **Args, unsigned NumArgs,
6347 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006348 // Find all of the types that the arguments can convert to, but only
6349 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00006350 // that make use of these types. Also record whether we encounter non-record
6351 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006352 Qualifiers VisibleTypeConversionsQuals;
6353 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00006354 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6355 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00006356
6357 bool HasNonRecordCandidateType = false;
6358 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006359 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00006360 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6361 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6362 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6363 OpLoc,
6364 true,
6365 (Op == OO_Exclaim ||
6366 Op == OO_AmpAmp ||
6367 Op == OO_PipePipe),
6368 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00006369 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6370 CandidateTypes[ArgIdx].hasNonRecordTypes();
6371 HasArithmeticOrEnumeralCandidateType =
6372 HasArithmeticOrEnumeralCandidateType ||
6373 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00006374 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006375
Chandler Carruth6a577462010-12-13 01:44:01 +00006376 // Exit early when no non-record types have been added to the candidate set
6377 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00006378 //
6379 // We can't exit early for !, ||, or &&, since there we have always have
6380 // 'bool' overloads.
6381 if (!HasNonRecordCandidateType &&
6382 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00006383 return;
6384
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006385 // Setup an object to manage the common state for building overloads.
6386 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6387 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006388 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006389 CandidateTypes, CandidateSet);
6390
6391 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006392 switch (Op) {
6393 case OO_None:
6394 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00006395 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006396
Chandler Carruthabb71842010-12-12 08:51:33 +00006397 case OO_New:
6398 case OO_Delete:
6399 case OO_Array_New:
6400 case OO_Array_Delete:
6401 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00006402 llvm_unreachable(
6403 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00006404
6405 case OO_Comma:
6406 case OO_Arrow:
6407 // C++ [over.match.oper]p3:
6408 // -- For the operator ',', the unary operator '&', or the
6409 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00006410 break;
6411
6412 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00006413 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006414 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00006415 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00006416
6417 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00006418 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006419 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00006420 } else {
6421 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6422 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6423 }
Douglas Gregor74253732008-11-19 15:42:04 +00006424 break;
6425
Chandler Carruthabb71842010-12-12 08:51:33 +00006426 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00006427 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00006428 OpBuilder.addUnaryStarPointerOverloads();
6429 else
6430 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6431 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006432
Chandler Carruthabb71842010-12-12 08:51:33 +00006433 case OO_Slash:
6434 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00006435 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006436
6437 case OO_PlusPlus:
6438 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006439 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6440 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00006441 break;
6442
Douglas Gregor19b7b152009-08-24 13:43:27 +00006443 case OO_EqualEqual:
6444 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006445 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00006446 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00006447
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006448 case OO_Less:
6449 case OO_Greater:
6450 case OO_LessEqual:
6451 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006452 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00006453 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6454 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006455
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006456 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006457 case OO_Caret:
6458 case OO_Pipe:
6459 case OO_LessLess:
6460 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006461 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006462 break;
6463
Chandler Carruthabb71842010-12-12 08:51:33 +00006464 case OO_Amp: // '&' is either unary or binary
6465 if (NumArgs == 1)
6466 // C++ [over.match.oper]p3:
6467 // -- For the operator ',', the unary operator '&', or the
6468 // operator '->', the built-in candidates set is empty.
6469 break;
6470
6471 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6472 break;
6473
6474 case OO_Tilde:
6475 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6476 break;
6477
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006478 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006479 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00006480 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006481
6482 case OO_PlusEqual:
6483 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006484 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006485 // Fall through.
6486
6487 case OO_StarEqual:
6488 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006489 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006490 break;
6491
6492 case OO_PercentEqual:
6493 case OO_LessLessEqual:
6494 case OO_GreaterGreaterEqual:
6495 case OO_AmpEqual:
6496 case OO_CaretEqual:
6497 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006498 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006499 break;
6500
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006501 case OO_Exclaim:
6502 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00006503 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006504
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006505 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006506 case OO_PipePipe:
6507 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006508 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006509
6510 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006511 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006512 break;
6513
6514 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006515 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006516 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006517
6518 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006519 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00006520 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6521 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006522 }
6523}
6524
Douglas Gregorfa047642009-02-04 00:32:51 +00006525/// \brief Add function candidates found via argument-dependent lookup
6526/// to the set of overloading candidates.
6527///
6528/// This routine performs argument-dependent name lookup based on the
6529/// given function name (which may also be an operator name) and adds
6530/// all of the overload candidates found by ADL to the overload
6531/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00006532void
Douglas Gregorfa047642009-02-04 00:32:51 +00006533Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00006534 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00006535 Expr **Args, unsigned NumArgs,
Douglas Gregor67714232011-03-03 02:41:12 +00006536 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006537 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00006538 bool PartialOverloading,
6539 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00006540 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00006541
John McCalla113e722010-01-26 06:04:06 +00006542 // FIXME: This approach for uniquing ADL results (and removing
6543 // redundant candidates from the set) relies on pointer-equality,
6544 // which means we need to key off the canonical decl. However,
6545 // always going back to the canonical decl might not get us the
6546 // right set of default arguments. What default arguments are
6547 // we supposed to consider on ADL candidates, anyway?
6548
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006549 // FIXME: Pass in the explicit template arguments?
Richard Smithad762fc2011-04-14 22:09:26 +00006550 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6551 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00006552
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006553 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006554 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6555 CandEnd = CandidateSet.end();
6556 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00006557 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00006558 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00006559 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00006560 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00006561 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006562
6563 // For each of the ADL candidates we found, add it to the overload
6564 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00006565 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00006566 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00006567 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00006568 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006569 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006570
John McCall9aa472c2010-03-19 07:35:19 +00006571 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006572 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006573 } else
John McCall6e266892010-01-26 03:27:55 +00006574 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00006575 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00006576 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00006577 }
Douglas Gregorfa047642009-02-04 00:32:51 +00006578}
6579
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006580/// isBetterOverloadCandidate - Determines whether the first overload
6581/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00006582bool
John McCall120d63c2010-08-24 20:38:10 +00006583isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00006584 const OverloadCandidate &Cand1,
6585 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006586 SourceLocation Loc,
6587 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006588 // Define viable functions to be better candidates than non-viable
6589 // functions.
6590 if (!Cand2.Viable)
6591 return Cand1.Viable;
6592 else if (!Cand1.Viable)
6593 return false;
6594
Douglas Gregor88a35142008-12-22 05:46:06 +00006595 // C++ [over.match.best]p1:
6596 //
6597 // -- if F is a static member function, ICS1(F) is defined such
6598 // that ICS1(F) is neither better nor worse than ICS1(G) for
6599 // any function G, and, symmetrically, ICS1(G) is neither
6600 // better nor worse than ICS1(F).
6601 unsigned StartArg = 0;
6602 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6603 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006604
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006605 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00006606 // A viable function F1 is defined to be a better function than another
6607 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006608 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006609 unsigned NumArgs = Cand1.Conversions.size();
6610 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6611 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006612 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00006613 switch (CompareImplicitConversionSequences(S,
6614 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006615 Cand2.Conversions[ArgIdx])) {
6616 case ImplicitConversionSequence::Better:
6617 // Cand1 has a better conversion sequence.
6618 HasBetterConversion = true;
6619 break;
6620
6621 case ImplicitConversionSequence::Worse:
6622 // Cand1 can't be better than Cand2.
6623 return false;
6624
6625 case ImplicitConversionSequence::Indistinguishable:
6626 // Do nothing.
6627 break;
6628 }
6629 }
6630
Mike Stump1eb44332009-09-09 15:08:12 +00006631 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006632 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006633 if (HasBetterConversion)
6634 return true;
6635
Mike Stump1eb44332009-09-09 15:08:12 +00006636 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006637 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00006638 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006639 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6640 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006641
6642 // -- F1 and F2 are function template specializations, and the function
6643 // template for F1 is more specialized than the template for F2
6644 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006645 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00006646 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00006647 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006648 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00006649 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6650 Cand2.Function->getPrimaryTemplate(),
6651 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006652 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00006653 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00006654 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006655 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00006656 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006657
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006658 // -- the context is an initialization by user-defined conversion
6659 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6660 // from the return type of F1 to the destination type (i.e.,
6661 // the type of the entity being initialized) is a better
6662 // conversion sequence than the standard conversion sequence
6663 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006664 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00006665 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006666 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00006667 switch (CompareStandardConversionSequences(S,
6668 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006669 Cand2.FinalConversion)) {
6670 case ImplicitConversionSequence::Better:
6671 // Cand1 has a better conversion sequence.
6672 return true;
6673
6674 case ImplicitConversionSequence::Worse:
6675 // Cand1 can't be better than Cand2.
6676 return false;
6677
6678 case ImplicitConversionSequence::Indistinguishable:
6679 // Do nothing
6680 break;
6681 }
6682 }
6683
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006684 return false;
6685}
6686
Mike Stump1eb44332009-09-09 15:08:12 +00006687/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00006688/// within an overload candidate set.
6689///
6690/// \param CandidateSet the set of candidate functions.
6691///
6692/// \param Loc the location of the function name (or operator symbol) for
6693/// which overload resolution occurs.
6694///
Mike Stump1eb44332009-09-09 15:08:12 +00006695/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00006696/// function, Best points to the candidate function found.
6697///
6698/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00006699OverloadingResult
6700OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00006701 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00006702 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006703 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00006704 Best = end();
6705 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6706 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006707 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006708 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006709 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006710 }
6711
6712 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00006713 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006714 return OR_No_Viable_Function;
6715
6716 // Make sure that this function is better than every other viable
6717 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00006718 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00006719 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006720 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006721 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006722 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00006723 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006724 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006725 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006726 }
Mike Stump1eb44332009-09-09 15:08:12 +00006727
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006728 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006729 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00006730 (Best->Function->isDeleted() ||
6731 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006732 return OR_Deleted;
6733
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006734 return OR_Success;
6735}
6736
John McCall3c80f572010-01-12 02:15:36 +00006737namespace {
6738
6739enum OverloadCandidateKind {
6740 oc_function,
6741 oc_method,
6742 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00006743 oc_function_template,
6744 oc_method_template,
6745 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00006746 oc_implicit_default_constructor,
6747 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00006748 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006749 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00006750 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006751 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00006752};
6753
John McCall220ccbf2010-01-13 00:25:19 +00006754OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6755 FunctionDecl *Fn,
6756 std::string &Description) {
6757 bool isTemplate = false;
6758
6759 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6760 isTemplate = true;
6761 Description = S.getTemplateArgumentBindingsText(
6762 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6763 }
John McCallb1622a12010-01-06 09:43:14 +00006764
6765 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00006766 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00006767 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00006768
Sebastian Redlf677ea32011-02-05 19:23:19 +00006769 if (Ctor->getInheritedConstructor())
6770 return oc_implicit_inherited_constructor;
6771
Sean Hunt82713172011-05-25 23:16:36 +00006772 if (Ctor->isDefaultConstructor())
6773 return oc_implicit_default_constructor;
6774
6775 if (Ctor->isMoveConstructor())
6776 return oc_implicit_move_constructor;
6777
6778 assert(Ctor->isCopyConstructor() &&
6779 "unexpected sort of implicit constructor");
6780 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00006781 }
6782
6783 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6784 // This actually gets spelled 'candidate function' for now, but
6785 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00006786 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00006787 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00006788
Sean Hunt82713172011-05-25 23:16:36 +00006789 if (Meth->isMoveAssignmentOperator())
6790 return oc_implicit_move_assignment;
6791
Douglas Gregor3e9438b2010-09-27 22:37:28 +00006792 assert(Meth->isCopyAssignmentOperator()
John McCallb1622a12010-01-06 09:43:14 +00006793 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00006794 return oc_implicit_copy_assignment;
6795 }
6796
John McCall220ccbf2010-01-13 00:25:19 +00006797 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00006798}
6799
Sebastian Redlf677ea32011-02-05 19:23:19 +00006800void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6801 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6802 if (!Ctor) return;
6803
6804 Ctor = Ctor->getInheritedConstructor();
6805 if (!Ctor) return;
6806
6807 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6808}
6809
John McCall3c80f572010-01-12 02:15:36 +00006810} // end anonymous namespace
6811
6812// Notes the location of an overload candidate.
6813void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00006814 std::string FnDesc;
6815 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6816 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6817 << (unsigned) K << FnDesc;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006818 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00006819}
6820
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006821//Notes the location of all overload candidates designated through
6822// OverloadedExpr
6823void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6824 assert(OverloadedExpr->getType() == Context.OverloadTy);
6825
6826 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6827 OverloadExpr *OvlExpr = Ovl.Expression;
6828
6829 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6830 IEnd = OvlExpr->decls_end();
6831 I != IEnd; ++I) {
6832 if (FunctionTemplateDecl *FunTmpl =
6833 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6834 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6835 } else if (FunctionDecl *Fun
6836 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6837 NoteOverloadCandidate(Fun);
6838 }
6839 }
6840}
6841
John McCall1d318332010-01-12 00:44:57 +00006842/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6843/// "lead" diagnostic; it will be given two arguments, the source and
6844/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00006845void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6846 Sema &S,
6847 SourceLocation CaretLoc,
6848 const PartialDiagnostic &PDiag) const {
6849 S.Diag(CaretLoc, PDiag)
6850 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00006851 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00006852 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6853 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00006854 }
John McCall81201622010-01-08 04:41:39 +00006855}
6856
John McCall1d318332010-01-12 00:44:57 +00006857namespace {
6858
John McCalladbb8f82010-01-13 09:16:55 +00006859void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6860 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6861 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00006862 assert(Cand->Function && "for now, candidate must be a function");
6863 FunctionDecl *Fn = Cand->Function;
6864
6865 // There's a conversion slot for the object argument if this is a
6866 // non-constructor method. Note that 'I' corresponds the
6867 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00006868 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00006869 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00006870 if (I == 0)
6871 isObjectArgument = true;
6872 else
6873 I--;
John McCall220ccbf2010-01-13 00:25:19 +00006874 }
6875
John McCall220ccbf2010-01-13 00:25:19 +00006876 std::string FnDesc;
6877 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6878
John McCalladbb8f82010-01-13 09:16:55 +00006879 Expr *FromExpr = Conv.Bad.FromExpr;
6880 QualType FromTy = Conv.Bad.getFromType();
6881 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00006882
John McCall5920dbb2010-02-02 02:42:52 +00006883 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00006884 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00006885 Expr *E = FromExpr->IgnoreParens();
6886 if (isa<UnaryOperator>(E))
6887 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00006888 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00006889
6890 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6891 << (unsigned) FnKind << FnDesc
6892 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6893 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006894 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00006895 return;
6896 }
6897
John McCall258b2032010-01-23 08:10:49 +00006898 // Do some hand-waving analysis to see if the non-viability is due
6899 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00006900 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6901 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6902 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6903 CToTy = RT->getPointeeType();
6904 else {
6905 // TODO: detect and diagnose the full richness of const mismatches.
6906 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6907 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6908 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6909 }
6910
6911 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6912 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6913 // It is dumb that we have to do this here.
6914 while (isa<ArrayType>(CFromTy))
6915 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6916 while (isa<ArrayType>(CToTy))
6917 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6918
6919 Qualifiers FromQs = CFromTy.getQualifiers();
6920 Qualifiers ToQs = CToTy.getQualifiers();
6921
6922 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6923 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6924 << (unsigned) FnKind << FnDesc
6925 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6926 << FromTy
6927 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6928 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006929 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00006930 return;
6931 }
6932
John McCallf85e1932011-06-15 23:02:42 +00006933 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00006934 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00006935 << (unsigned) FnKind << FnDesc
6936 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6937 << FromTy
6938 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
6939 << (unsigned) isObjectArgument << I+1;
6940 MaybeEmitInheritedConstructorNote(S, Fn);
6941 return;
6942 }
6943
Douglas Gregor028ea4b2011-04-26 23:16:46 +00006944 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
6945 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
6946 << (unsigned) FnKind << FnDesc
6947 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6948 << FromTy
6949 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
6950 << (unsigned) isObjectArgument << I+1;
6951 MaybeEmitInheritedConstructorNote(S, Fn);
6952 return;
6953 }
6954
John McCall651f3ee2010-01-14 03:28:57 +00006955 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6956 assert(CVR && "unexpected qualifiers mismatch");
6957
6958 if (isObjectArgument) {
6959 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6960 << (unsigned) FnKind << FnDesc
6961 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6962 << FromTy << (CVR - 1);
6963 } else {
6964 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6965 << (unsigned) FnKind << FnDesc
6966 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6967 << FromTy << (CVR - 1) << I+1;
6968 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00006969 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00006970 return;
6971 }
6972
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00006973 // Special diagnostic for failure to convert an initializer list, since
6974 // telling the user that it has type void is not useful.
6975 if (FromExpr && isa<InitListExpr>(FromExpr)) {
6976 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
6977 << (unsigned) FnKind << FnDesc
6978 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6979 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6980 MaybeEmitInheritedConstructorNote(S, Fn);
6981 return;
6982 }
6983
John McCall258b2032010-01-23 08:10:49 +00006984 // Diagnose references or pointers to incomplete types differently,
6985 // since it's far from impossible that the incompleteness triggered
6986 // the failure.
6987 QualType TempFromTy = FromTy.getNonReferenceType();
6988 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6989 TempFromTy = PTy->getPointeeType();
6990 if (TempFromTy->isIncompleteType()) {
6991 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6992 << (unsigned) FnKind << FnDesc
6993 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6994 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006995 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00006996 return;
6997 }
6998
Douglas Gregor85789812010-06-30 23:01:39 +00006999 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007000 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00007001 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7002 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7003 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7004 FromPtrTy->getPointeeType()) &&
7005 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7006 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007007 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00007008 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007009 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00007010 }
7011 } else if (const ObjCObjectPointerType *FromPtrTy
7012 = FromTy->getAs<ObjCObjectPointerType>()) {
7013 if (const ObjCObjectPointerType *ToPtrTy
7014 = ToTy->getAs<ObjCObjectPointerType>())
7015 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7016 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7017 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7018 FromPtrTy->getPointeeType()) &&
7019 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007020 BaseToDerivedConversion = 2;
7021 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7022 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7023 !FromTy->isIncompleteType() &&
7024 !ToRefTy->getPointeeType()->isIncompleteType() &&
7025 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7026 BaseToDerivedConversion = 3;
7027 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007028
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007029 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007030 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007031 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00007032 << (unsigned) FnKind << FnDesc
7033 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007034 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007035 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007036 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00007037 return;
7038 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007039
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00007040 if (isa<ObjCObjectPointerType>(CFromTy) &&
7041 isa<PointerType>(CToTy)) {
7042 Qualifiers FromQs = CFromTy.getQualifiers();
7043 Qualifiers ToQs = CToTy.getQualifiers();
7044 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7045 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7046 << (unsigned) FnKind << FnDesc
7047 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7048 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7049 MaybeEmitInheritedConstructorNote(S, Fn);
7050 return;
7051 }
7052 }
7053
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007054 // Emit the generic diagnostic and, optionally, add the hints to it.
7055 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7056 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00007057 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007058 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7059 << (unsigned) (Cand->Fix.Kind);
7060
7061 // If we can fix the conversion, suggest the FixIts.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007062 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007063 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7064 HI != HE; ++HI)
7065 FDiag << *HI;
7066 S.Diag(Fn->getLocation(), FDiag);
7067
Sebastian Redlf677ea32011-02-05 19:23:19 +00007068 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00007069}
7070
7071void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7072 unsigned NumFormalArgs) {
7073 // TODO: treat calls to a missing default constructor as a special case
7074
7075 FunctionDecl *Fn = Cand->Function;
7076 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7077
7078 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007079
Douglas Gregor439d3c32011-05-05 00:13:13 +00007080 // With invalid overloaded operators, it's possible that we think we
7081 // have an arity mismatch when it fact it looks like we have the
7082 // right number of arguments, because only overloaded operators have
7083 // the weird behavior of overloading member and non-member functions.
7084 // Just don't report anything.
7085 if (Fn->isInvalidDecl() &&
7086 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7087 return;
7088
John McCalladbb8f82010-01-13 09:16:55 +00007089 // at least / at most / exactly
7090 unsigned mode, modeCount;
7091 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00007092 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7093 (Cand->FailureKind == ovl_fail_bad_deduction &&
7094 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007095 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00007096 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00007097 mode = 0; // "at least"
7098 else
7099 mode = 2; // "exactly"
7100 modeCount = MinParams;
7101 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00007102 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7103 (Cand->FailureKind == ovl_fail_bad_deduction &&
7104 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00007105 if (MinParams != FnTy->getNumArgs())
7106 mode = 1; // "at most"
7107 else
7108 mode = 2; // "exactly"
7109 modeCount = FnTy->getNumArgs();
7110 }
7111
7112 std::string Description;
7113 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7114
7115 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007116 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregora18592e2010-05-08 18:13:28 +00007117 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007118 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00007119}
7120
John McCall342fec42010-02-01 18:53:26 +00007121/// Diagnose a failed template-argument deduction.
7122void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7123 Expr **Args, unsigned NumArgs) {
7124 FunctionDecl *Fn = Cand->Function; // pattern
7125
Douglas Gregora9333192010-05-08 17:41:32 +00007126 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00007127 NamedDecl *ParamD;
7128 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7129 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7130 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00007131 switch (Cand->DeductionFailure.Result) {
7132 case Sema::TDK_Success:
7133 llvm_unreachable("TDK_success while diagnosing bad deduction");
7134
7135 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00007136 assert(ParamD && "no parameter found for incomplete deduction result");
7137 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7138 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007139 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00007140 return;
7141 }
7142
John McCall57e97782010-08-05 09:05:08 +00007143 case Sema::TDK_Underqualified: {
7144 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7145 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7146
7147 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7148
7149 // Param will have been canonicalized, but it should just be a
7150 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00007151 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00007152 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00007153 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00007154 assert(S.Context.hasSameType(Param, NonCanonParam));
7155
7156 // Arg has also been canonicalized, but there's nothing we can do
7157 // about that. It also doesn't matter as much, because it won't
7158 // have any template parameters in it (because deduction isn't
7159 // done on dependent types).
7160 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7161
7162 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7163 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007164 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00007165 return;
7166 }
7167
7168 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00007169 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00007170 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00007171 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00007172 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00007173 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00007174 which = 1;
7175 else {
Douglas Gregora9333192010-05-08 17:41:32 +00007176 which = 2;
7177 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007178
Douglas Gregora9333192010-05-08 17:41:32 +00007179 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007180 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00007181 << *Cand->DeductionFailure.getFirstArg()
7182 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007183 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00007184 return;
7185 }
Douglas Gregora18592e2010-05-08 18:13:28 +00007186
Douglas Gregorf1a84452010-05-08 19:15:54 +00007187 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007188 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00007189 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007190 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00007191 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7192 << ParamD->getDeclName();
7193 else {
7194 int index = 0;
7195 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7196 index = TTP->getIndex();
7197 else if (NonTypeTemplateParmDecl *NTTP
7198 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7199 index = NTTP->getIndex();
7200 else
7201 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007202 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00007203 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7204 << (index + 1);
7205 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00007206 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00007207 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007208
Douglas Gregora18592e2010-05-08 18:13:28 +00007209 case Sema::TDK_TooManyArguments:
7210 case Sema::TDK_TooFewArguments:
7211 DiagnoseArityMismatch(S, Cand, NumArgs);
7212 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00007213
7214 case Sema::TDK_InstantiationDepth:
7215 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007216 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00007217 return;
7218
7219 case Sema::TDK_SubstitutionFailure: {
7220 std::string ArgString;
7221 if (TemplateArgumentList *Args
7222 = Cand->DeductionFailure.getTemplateArgumentList())
7223 ArgString = S.getTemplateArgumentBindingsText(
7224 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7225 *Args);
7226 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7227 << ArgString;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007228 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00007229 return;
7230 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007231
John McCall342fec42010-02-01 18:53:26 +00007232 // TODO: diagnose these individually, then kill off
7233 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00007234 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00007235 case Sema::TDK_FailedOverloadResolution:
7236 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007237 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00007238 return;
7239 }
7240}
7241
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00007242/// CUDA: diagnose an invalid call across targets.
7243void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
7244 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
7245 FunctionDecl *Callee = Cand->Function;
7246
7247 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
7248 CalleeTarget = S.IdentifyCUDATarget(Callee);
7249
7250 std::string FnDesc;
7251 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
7252
7253 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
7254 << (unsigned) FnKind << CalleeTarget << CallerTarget;
7255}
7256
John McCall342fec42010-02-01 18:53:26 +00007257/// Generates a 'note' diagnostic for an overload candidate. We've
7258/// already generated a primary error at the call site.
7259///
7260/// It really does need to be a single diagnostic with its caret
7261/// pointed at the candidate declaration. Yes, this creates some
7262/// major challenges of technical writing. Yes, this makes pointing
7263/// out problems with specific arguments quite awkward. It's still
7264/// better than generating twenty screens of text for every failed
7265/// overload.
7266///
7267/// It would be great to be able to express per-candidate problems
7268/// more richly for those diagnostic clients that cared, but we'd
7269/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00007270void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7271 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00007272 FunctionDecl *Fn = Cand->Function;
7273
John McCall81201622010-01-08 04:41:39 +00007274 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007275 if (Cand->Viable && (Fn->isDeleted() ||
7276 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00007277 std::string FnDesc;
7278 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00007279
7280 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00007281 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007282 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00007283 return;
John McCall81201622010-01-08 04:41:39 +00007284 }
7285
John McCall220ccbf2010-01-13 00:25:19 +00007286 // We don't really have anything else to say about viable candidates.
7287 if (Cand->Viable) {
7288 S.NoteOverloadCandidate(Fn);
7289 return;
7290 }
John McCall1d318332010-01-12 00:44:57 +00007291
John McCalladbb8f82010-01-13 09:16:55 +00007292 switch (Cand->FailureKind) {
7293 case ovl_fail_too_many_arguments:
7294 case ovl_fail_too_few_arguments:
7295 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00007296
John McCalladbb8f82010-01-13 09:16:55 +00007297 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00007298 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7299
John McCall717e8912010-01-23 05:17:32 +00007300 case ovl_fail_trivial_conversion:
7301 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00007302 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00007303 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00007304
John McCallb1bdc622010-02-25 01:37:24 +00007305 case ovl_fail_bad_conversion: {
7306 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7307 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00007308 if (Cand->Conversions[I].isBad())
7309 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007310
John McCalladbb8f82010-01-13 09:16:55 +00007311 // FIXME: this currently happens when we're called from SemaInit
7312 // when user-conversion overload fails. Figure out how to handle
7313 // those conditions and diagnose them well.
7314 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00007315 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00007316
7317 case ovl_fail_bad_target:
7318 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00007319 }
John McCalla1d7d622010-01-08 00:58:21 +00007320}
7321
7322void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7323 // Desugar the type of the surrogate down to a function type,
7324 // retaining as many typedefs as possible while still showing
7325 // the function type (and, therefore, its parameter types).
7326 QualType FnType = Cand->Surrogate->getConversionType();
7327 bool isLValueReference = false;
7328 bool isRValueReference = false;
7329 bool isPointer = false;
7330 if (const LValueReferenceType *FnTypeRef =
7331 FnType->getAs<LValueReferenceType>()) {
7332 FnType = FnTypeRef->getPointeeType();
7333 isLValueReference = true;
7334 } else if (const RValueReferenceType *FnTypeRef =
7335 FnType->getAs<RValueReferenceType>()) {
7336 FnType = FnTypeRef->getPointeeType();
7337 isRValueReference = true;
7338 }
7339 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7340 FnType = FnTypePtr->getPointeeType();
7341 isPointer = true;
7342 }
7343 // Desugar down to a function type.
7344 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7345 // Reconstruct the pointer/reference as appropriate.
7346 if (isPointer) FnType = S.Context.getPointerType(FnType);
7347 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7348 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7349
7350 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7351 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007352 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00007353}
7354
7355void NoteBuiltinOperatorCandidate(Sema &S,
7356 const char *Opc,
7357 SourceLocation OpLoc,
7358 OverloadCandidate *Cand) {
7359 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7360 std::string TypeStr("operator");
7361 TypeStr += Opc;
7362 TypeStr += "(";
7363 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7364 if (Cand->Conversions.size() == 1) {
7365 TypeStr += ")";
7366 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7367 } else {
7368 TypeStr += ", ";
7369 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7370 TypeStr += ")";
7371 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7372 }
7373}
7374
7375void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7376 OverloadCandidate *Cand) {
7377 unsigned NoOperands = Cand->Conversions.size();
7378 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7379 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00007380 if (ICS.isBad()) break; // all meaningless after first invalid
7381 if (!ICS.isAmbiguous()) continue;
7382
John McCall120d63c2010-08-24 20:38:10 +00007383 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007384 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00007385 }
7386}
7387
John McCall1b77e732010-01-15 23:32:50 +00007388SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7389 if (Cand->Function)
7390 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00007391 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00007392 return Cand->Surrogate->getLocation();
7393 return SourceLocation();
7394}
7395
Benjamin Kramerafc5b152011-09-10 21:52:04 +00007396static unsigned
7397RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00007398 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007399 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00007400 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00007401
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007402 case Sema::TDK_Incomplete:
7403 return 1;
7404
7405 case Sema::TDK_Underqualified:
7406 case Sema::TDK_Inconsistent:
7407 return 2;
7408
7409 case Sema::TDK_SubstitutionFailure:
7410 case Sema::TDK_NonDeducedMismatch:
7411 return 3;
7412
7413 case Sema::TDK_InstantiationDepth:
7414 case Sema::TDK_FailedOverloadResolution:
7415 return 4;
7416
7417 case Sema::TDK_InvalidExplicitArguments:
7418 return 5;
7419
7420 case Sema::TDK_TooManyArguments:
7421 case Sema::TDK_TooFewArguments:
7422 return 6;
7423 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00007424 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007425}
7426
John McCallbf65c0b2010-01-12 00:48:53 +00007427struct CompareOverloadCandidatesForDisplay {
7428 Sema &S;
7429 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00007430
7431 bool operator()(const OverloadCandidate *L,
7432 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00007433 // Fast-path this check.
7434 if (L == R) return false;
7435
John McCall81201622010-01-08 04:41:39 +00007436 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00007437 if (L->Viable) {
7438 if (!R->Viable) return true;
7439
7440 // TODO: introduce a tri-valued comparison for overload
7441 // candidates. Would be more worthwhile if we had a sort
7442 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00007443 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7444 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00007445 } else if (R->Viable)
7446 return false;
John McCall81201622010-01-08 04:41:39 +00007447
John McCall1b77e732010-01-15 23:32:50 +00007448 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00007449
John McCall1b77e732010-01-15 23:32:50 +00007450 // Criteria by which we can sort non-viable candidates:
7451 if (!L->Viable) {
7452 // 1. Arity mismatches come after other candidates.
7453 if (L->FailureKind == ovl_fail_too_many_arguments ||
7454 L->FailureKind == ovl_fail_too_few_arguments)
7455 return false;
7456 if (R->FailureKind == ovl_fail_too_many_arguments ||
7457 R->FailureKind == ovl_fail_too_few_arguments)
7458 return true;
John McCall81201622010-01-08 04:41:39 +00007459
John McCall717e8912010-01-23 05:17:32 +00007460 // 2. Bad conversions come first and are ordered by the number
7461 // of bad conversions and quality of good conversions.
7462 if (L->FailureKind == ovl_fail_bad_conversion) {
7463 if (R->FailureKind != ovl_fail_bad_conversion)
7464 return true;
7465
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007466 // The conversion that can be fixed with a smaller number of changes,
7467 // comes first.
7468 unsigned numLFixes = L->Fix.NumConversionsFixed;
7469 unsigned numRFixes = R->Fix.NumConversionsFixed;
7470 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7471 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00007472 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007473 if (numLFixes < numRFixes)
7474 return true;
7475 else
7476 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00007477 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007478
John McCall717e8912010-01-23 05:17:32 +00007479 // If there's any ordering between the defined conversions...
7480 // FIXME: this might not be transitive.
7481 assert(L->Conversions.size() == R->Conversions.size());
7482
7483 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00007484 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7485 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00007486 switch (CompareImplicitConversionSequences(S,
7487 L->Conversions[I],
7488 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00007489 case ImplicitConversionSequence::Better:
7490 leftBetter++;
7491 break;
7492
7493 case ImplicitConversionSequence::Worse:
7494 leftBetter--;
7495 break;
7496
7497 case ImplicitConversionSequence::Indistinguishable:
7498 break;
7499 }
7500 }
7501 if (leftBetter > 0) return true;
7502 if (leftBetter < 0) return false;
7503
7504 } else if (R->FailureKind == ovl_fail_bad_conversion)
7505 return false;
7506
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007507 if (L->FailureKind == ovl_fail_bad_deduction) {
7508 if (R->FailureKind != ovl_fail_bad_deduction)
7509 return true;
7510
7511 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7512 return RankDeductionFailure(L->DeductionFailure)
7513 <= RankDeductionFailure(R->DeductionFailure);
7514 }
7515
John McCall1b77e732010-01-15 23:32:50 +00007516 // TODO: others?
7517 }
7518
7519 // Sort everything else by location.
7520 SourceLocation LLoc = GetLocationForCandidate(L);
7521 SourceLocation RLoc = GetLocationForCandidate(R);
7522
7523 // Put candidates without locations (e.g. builtins) at the end.
7524 if (LLoc.isInvalid()) return false;
7525 if (RLoc.isInvalid()) return true;
7526
7527 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00007528 }
7529};
7530
John McCall717e8912010-01-23 05:17:32 +00007531/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007532/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00007533void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7534 Expr **Args, unsigned NumArgs) {
7535 assert(!Cand->Viable);
7536
7537 // Don't do anything on failures other than bad conversion.
7538 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7539
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007540 // We only want the FixIts if all the arguments can be corrected.
7541 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00007542 // Use a implicit copy initialization to check conversion fixes.
7543 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007544
John McCall717e8912010-01-23 05:17:32 +00007545 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00007546 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00007547 unsigned ConvCount = Cand->Conversions.size();
7548 while (true) {
7549 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7550 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007551 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00007552 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00007553 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007554 }
John McCall717e8912010-01-23 05:17:32 +00007555 }
7556
7557 if (ConvIdx == ConvCount)
7558 return;
7559
John McCallb1bdc622010-02-25 01:37:24 +00007560 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7561 "remaining conversion is initialized?");
7562
Douglas Gregor23ef6c02010-04-16 17:45:54 +00007563 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00007564 // operation somehow.
7565 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00007566
7567 const FunctionProtoType* Proto;
7568 unsigned ArgIdx = ConvIdx;
7569
7570 if (Cand->IsSurrogate) {
7571 QualType ConvType
7572 = Cand->Surrogate->getConversionType().getNonReferenceType();
7573 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7574 ConvType = ConvPtrType->getPointeeType();
7575 Proto = ConvType->getAs<FunctionProtoType>();
7576 ArgIdx--;
7577 } else if (Cand->Function) {
7578 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7579 if (isa<CXXMethodDecl>(Cand->Function) &&
7580 !isa<CXXConstructorDecl>(Cand->Function))
7581 ArgIdx--;
7582 } else {
7583 // Builtin binary operator with a bad first conversion.
7584 assert(ConvCount <= 3);
7585 for (; ConvIdx != ConvCount; ++ConvIdx)
7586 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00007587 = TryCopyInitialization(S, Args[ConvIdx],
7588 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007589 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00007590 /*InOverloadResolution*/ true,
7591 /*AllowObjCWritebackConversion=*/
7592 S.getLangOptions().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00007593 return;
7594 }
7595
7596 // Fill in the rest of the conversions.
7597 unsigned NumArgsInProto = Proto->getNumArgs();
7598 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007599 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00007600 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00007601 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007602 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00007603 /*InOverloadResolution=*/true,
7604 /*AllowObjCWritebackConversion=*/
7605 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007606 // Store the FixIt in the candidate if it exists.
7607 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00007608 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007609 }
John McCall717e8912010-01-23 05:17:32 +00007610 else
7611 Cand->Conversions[ConvIdx].setEllipsis();
7612 }
7613}
7614
John McCalla1d7d622010-01-08 00:58:21 +00007615} // end anonymous namespace
7616
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007617/// PrintOverloadCandidates - When overload resolution fails, prints
7618/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00007619/// set.
John McCall120d63c2010-08-24 20:38:10 +00007620void OverloadCandidateSet::NoteCandidates(Sema &S,
7621 OverloadCandidateDisplayKind OCD,
7622 Expr **Args, unsigned NumArgs,
7623 const char *Opc,
7624 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00007625 // Sort the candidates by viability and position. Sorting directly would
7626 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007627 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00007628 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7629 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00007630 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00007631 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00007632 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00007633 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007634 if (Cand->Function || Cand->IsSurrogate)
7635 Cands.push_back(Cand);
7636 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7637 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00007638 }
7639 }
7640
John McCallbf65c0b2010-01-12 00:48:53 +00007641 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00007642 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007643
John McCall1d318332010-01-12 00:44:57 +00007644 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00007645
Chris Lattner5f9e2722011-07-23 10:55:15 +00007646 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikied6471f72011-09-25 23:23:43 +00007647 const DiagnosticsEngine::OverloadsShown ShowOverloads =
7648 S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007649 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00007650 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7651 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00007652
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007653 // Set an arbitrary limit on the number of candidate functions we'll spam
7654 // the user with. FIXME: This limit should depend on details of the
7655 // candidate list.
David Blaikied6471f72011-09-25 23:23:43 +00007656 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007657 break;
7658 }
7659 ++CandsShown;
7660
John McCalla1d7d622010-01-08 00:58:21 +00007661 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00007662 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00007663 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00007664 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007665 else {
7666 assert(Cand->Viable &&
7667 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00007668 // Generally we only see ambiguities including viable builtin
7669 // operators if overload resolution got screwed up by an
7670 // ambiguous user-defined conversion.
7671 //
7672 // FIXME: It's quite possible for different conversions to see
7673 // different ambiguities, though.
7674 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00007675 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00007676 ReportedAmbiguousConversions = true;
7677 }
John McCalla1d7d622010-01-08 00:58:21 +00007678
John McCall1d318332010-01-12 00:44:57 +00007679 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00007680 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007681 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007682 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007683
7684 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00007685 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007686}
7687
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007688// [PossiblyAFunctionType] --> [Return]
7689// NonFunctionType --> NonFunctionType
7690// R (A) --> R(A)
7691// R (*)(A) --> R (A)
7692// R (&)(A) --> R (A)
7693// R (S::*)(A) --> R (A)
7694QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7695 QualType Ret = PossiblyAFunctionType;
7696 if (const PointerType *ToTypePtr =
7697 PossiblyAFunctionType->getAs<PointerType>())
7698 Ret = ToTypePtr->getPointeeType();
7699 else if (const ReferenceType *ToTypeRef =
7700 PossiblyAFunctionType->getAs<ReferenceType>())
7701 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00007702 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007703 PossiblyAFunctionType->getAs<MemberPointerType>())
7704 Ret = MemTypePtr->getPointeeType();
7705 Ret =
7706 Context.getCanonicalType(Ret).getUnqualifiedType();
7707 return Ret;
7708}
Douglas Gregor904eed32008-11-10 20:40:00 +00007709
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007710// A helper class to help with address of function resolution
7711// - allows us to avoid passing around all those ugly parameters
7712class AddressOfFunctionResolver
7713{
7714 Sema& S;
7715 Expr* SourceExpr;
7716 const QualType& TargetType;
7717 QualType TargetFunctionType; // Extracted function type from target type
7718
7719 bool Complain;
7720 //DeclAccessPair& ResultFunctionAccessPair;
7721 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007722
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007723 bool TargetTypeIsNonStaticMemberFunction;
7724 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007725
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007726 OverloadExpr::FindResult OvlExprInfo;
7727 OverloadExpr *OvlExpr;
7728 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007729 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007730
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007731public:
7732 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7733 const QualType& TargetType, bool Complain)
7734 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7735 Complain(Complain), Context(S.getASTContext()),
7736 TargetTypeIsNonStaticMemberFunction(
7737 !!TargetType->getAs<MemberPointerType>()),
7738 FoundNonTemplateFunction(false),
7739 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7740 OvlExpr(OvlExprInfo.Expression)
7741 {
7742 ExtractUnqualifiedFunctionTypeFromTargetType();
7743
7744 if (!TargetFunctionType->isFunctionType()) {
7745 if (OvlExpr->hasExplicitTemplateArgs()) {
7746 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00007747 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007748 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00007749
7750 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7751 if (!Method->isStatic()) {
7752 // If the target type is a non-function type and the function
7753 // found is a non-static member function, pretend as if that was
7754 // the target, it's the only possible type to end up with.
7755 TargetTypeIsNonStaticMemberFunction = true;
7756
7757 // And skip adding the function if its not in the proper form.
7758 // We'll diagnose this due to an empty set of functions.
7759 if (!OvlExprInfo.HasFormOfMemberPointer)
7760 return;
7761 }
7762 }
7763
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007764 Matches.push_back(std::make_pair(dap,Fn));
7765 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00007766 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007767 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00007768 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007769
7770 if (OvlExpr->hasExplicitTemplateArgs())
7771 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00007772
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007773 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7774 // C++ [over.over]p4:
7775 // If more than one function is selected, [...]
7776 if (Matches.size() > 1) {
7777 if (FoundNonTemplateFunction)
7778 EliminateAllTemplateMatches();
7779 else
7780 EliminateAllExceptMostSpecializedTemplate();
7781 }
7782 }
7783 }
7784
7785private:
7786 bool isTargetTypeAFunction() const {
7787 return TargetFunctionType->isFunctionType();
7788 }
7789
7790 // [ToType] [Return]
7791
7792 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7793 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7794 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7795 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7796 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7797 }
7798
7799 // return true if any matching specializations were found
7800 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7801 const DeclAccessPair& CurAccessFunPair) {
7802 if (CXXMethodDecl *Method
7803 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7804 // Skip non-static function templates when converting to pointer, and
7805 // static when converting to member pointer.
7806 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7807 return false;
7808 }
7809 else if (TargetTypeIsNonStaticMemberFunction)
7810 return false;
7811
7812 // C++ [over.over]p2:
7813 // If the name is a function template, template argument deduction is
7814 // done (14.8.2.2), and if the argument deduction succeeds, the
7815 // resulting template argument list is used to generate a single
7816 // function template specialization, which is added to the set of
7817 // overloaded functions considered.
7818 FunctionDecl *Specialization = 0;
7819 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7820 if (Sema::TemplateDeductionResult Result
7821 = S.DeduceTemplateArguments(FunctionTemplate,
7822 &OvlExplicitTemplateArgs,
7823 TargetFunctionType, Specialization,
7824 Info)) {
7825 // FIXME: make a note of the failed deduction for diagnostics.
7826 (void)Result;
7827 return false;
7828 }
7829
7830 // Template argument deduction ensures that we have an exact match.
7831 // This function template specicalization works.
7832 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7833 assert(TargetFunctionType
7834 == Context.getCanonicalType(Specialization->getType()));
7835 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7836 return true;
7837 }
7838
7839 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7840 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00007841 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00007842 // Skip non-static functions when converting to pointer, and static
7843 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007844 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7845 return false;
7846 }
7847 else if (TargetTypeIsNonStaticMemberFunction)
7848 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00007849
Chandler Carruthbd647292009-12-29 06:17:27 +00007850 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00007851 if (S.getLangOptions().CUDA)
7852 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
7853 if (S.CheckCUDATarget(Caller, FunDecl))
7854 return false;
7855
Douglas Gregor43c79c22009-12-09 00:47:37 +00007856 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007857 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7858 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00007859 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
7860 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007861 Matches.push_back(std::make_pair(CurAccessFunPair,
7862 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00007863 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007864 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00007865 }
Mike Stump1eb44332009-09-09 15:08:12 +00007866 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007867
7868 return false;
7869 }
7870
7871 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7872 bool Ret = false;
7873
7874 // If the overload expression doesn't have the form of a pointer to
7875 // member, don't try to convert it to a pointer-to-member type.
7876 if (IsInvalidFormOfPointerToMemberFunction())
7877 return false;
7878
7879 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7880 E = OvlExpr->decls_end();
7881 I != E; ++I) {
7882 // Look through any using declarations to find the underlying function.
7883 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7884
7885 // C++ [over.over]p3:
7886 // Non-member functions and static member functions match
7887 // targets of type "pointer-to-function" or "reference-to-function."
7888 // Nonstatic member functions match targets of
7889 // type "pointer-to-member-function."
7890 // Note that according to DR 247, the containing class does not matter.
7891 if (FunctionTemplateDecl *FunctionTemplate
7892 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7893 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7894 Ret = true;
7895 }
7896 // If we have explicit template arguments supplied, skip non-templates.
7897 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7898 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7899 Ret = true;
7900 }
7901 assert(Ret || Matches.empty());
7902 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00007903 }
7904
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007905 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007906 // [...] and any given function template specialization F1 is
7907 // eliminated if the set contains a second function template
7908 // specialization whose function template is more specialized
7909 // than the function template of F1 according to the partial
7910 // ordering rules of 14.5.5.2.
7911
7912 // The algorithm specified above is quadratic. We instead use a
7913 // two-pass algorithm (similar to the one used to identify the
7914 // best viable function in an overload set) that identifies the
7915 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00007916
7917 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7918 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7919 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007920
John McCallc373d482010-01-27 01:50:18 +00007921 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007922 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7923 TPOC_Other, 0, SourceExpr->getLocStart(),
7924 S.PDiag(),
7925 S.PDiag(diag::err_addr_ovl_ambiguous)
7926 << Matches[0].second->getDeclName(),
7927 S.PDiag(diag::note_ovl_candidate)
7928 << (unsigned) oc_function_template,
7929 Complain);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007930
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007931 if (Result != MatchesCopy.end()) {
7932 // Make it the first and only element
7933 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7934 Matches[0].second = cast<FunctionDecl>(*Result);
7935 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00007936 }
7937 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007938
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007939 void EliminateAllTemplateMatches() {
7940 // [...] any function template specializations in the set are
7941 // eliminated if the set also contains a non-template function, [...]
7942 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7943 if (Matches[I].second->getPrimaryTemplate() == 0)
7944 ++I;
7945 else {
7946 Matches[I] = Matches[--N];
7947 Matches.set_size(N);
7948 }
7949 }
7950 }
7951
7952public:
7953 void ComplainNoMatchesFound() const {
7954 assert(Matches.empty());
7955 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7956 << OvlExpr->getName() << TargetFunctionType
7957 << OvlExpr->getSourceRange();
7958 S.NoteAllOverloadCandidates(OvlExpr);
7959 }
7960
7961 bool IsInvalidFormOfPointerToMemberFunction() const {
7962 return TargetTypeIsNonStaticMemberFunction &&
7963 !OvlExprInfo.HasFormOfMemberPointer;
7964 }
7965
7966 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7967 // TODO: Should we condition this on whether any functions might
7968 // have matched, or is it more appropriate to do that in callers?
7969 // TODO: a fixit wouldn't hurt.
7970 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7971 << TargetType << OvlExpr->getSourceRange();
7972 }
7973
7974 void ComplainOfInvalidConversion() const {
7975 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7976 << OvlExpr->getName() << TargetType;
7977 }
7978
7979 void ComplainMultipleMatchesFound() const {
7980 assert(Matches.size() > 1);
7981 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7982 << OvlExpr->getName()
7983 << OvlExpr->getSourceRange();
7984 S.NoteAllOverloadCandidates(OvlExpr);
7985 }
7986
7987 int getNumMatches() const { return Matches.size(); }
7988
7989 FunctionDecl* getMatchingFunctionDecl() const {
7990 if (Matches.size() != 1) return 0;
7991 return Matches[0].second;
7992 }
7993
7994 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7995 if (Matches.size() != 1) return 0;
7996 return &Matches[0].first;
7997 }
7998};
7999
8000/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8001/// an overloaded function (C++ [over.over]), where @p From is an
8002/// expression with overloaded function type and @p ToType is the type
8003/// we're trying to resolve to. For example:
8004///
8005/// @code
8006/// int f(double);
8007/// int f(int);
8008///
8009/// int (*pfd)(double) = f; // selects f(double)
8010/// @endcode
8011///
8012/// This routine returns the resulting FunctionDecl if it could be
8013/// resolved, and NULL otherwise. When @p Complain is true, this
8014/// routine will emit diagnostics if there is an error.
8015FunctionDecl *
8016Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
8017 bool Complain,
8018 DeclAccessPair &FoundResult) {
8019
8020 assert(AddressOfExpr->getType() == Context.OverloadTy);
8021
8022 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
8023 int NumMatches = Resolver.getNumMatches();
8024 FunctionDecl* Fn = 0;
8025 if ( NumMatches == 0 && Complain) {
8026 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8027 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8028 else
8029 Resolver.ComplainNoMatchesFound();
8030 }
8031 else if (NumMatches > 1 && Complain)
8032 Resolver.ComplainMultipleMatchesFound();
8033 else if (NumMatches == 1) {
8034 Fn = Resolver.getMatchingFunctionDecl();
8035 assert(Fn);
8036 FoundResult = *Resolver.getMatchingFunctionAccessPair();
8037 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00008038 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008039 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00008040 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008041
8042 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00008043}
8044
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008045/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00008046/// resolve that overloaded function expression down to a single function.
8047///
8048/// This routine can only resolve template-ids that refer to a single function
8049/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008050/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00008051/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00008052FunctionDecl *
8053Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8054 bool Complain,
8055 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00008056 // C++ [over.over]p1:
8057 // [...] [Note: any redundant set of parentheses surrounding the
8058 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00008059 // C++ [over.over]p1:
8060 // [...] The overloaded function name can be preceded by the &
8061 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008062
Douglas Gregor4b52e252009-12-21 23:17:24 +00008063 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00008064 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00008065 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00008066
8067 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00008068 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008069
Douglas Gregor4b52e252009-12-21 23:17:24 +00008070 // Look through all of the overloaded functions, searching for one
8071 // whose type matches exactly.
8072 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00008073 for (UnresolvedSetIterator I = ovl->decls_begin(),
8074 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00008075 // C++0x [temp.arg.explicit]p3:
8076 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008077 // where deduction is not done, if a template argument list is
8078 // specified and it, along with any default template arguments,
8079 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00008080 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00008081 FunctionTemplateDecl *FunctionTemplate
8082 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008083
Douglas Gregor4b52e252009-12-21 23:17:24 +00008084 // C++ [over.over]p2:
8085 // If the name is a function template, template argument deduction is
8086 // done (14.8.2.2), and if the argument deduction succeeds, the
8087 // resulting template argument list is used to generate a single
8088 // function template specialization, which is added to the set of
8089 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00008090 FunctionDecl *Specialization = 0;
John McCall864c0412011-04-26 20:42:42 +00008091 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00008092 if (TemplateDeductionResult Result
8093 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8094 Specialization, Info)) {
8095 // FIXME: make a note of the failed deduction for diagnostics.
8096 (void)Result;
8097 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008098 }
8099
John McCall864c0412011-04-26 20:42:42 +00008100 assert(Specialization && "no specialization and no error?");
8101
Douglas Gregor4b52e252009-12-21 23:17:24 +00008102 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008103 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008104 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00008105 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8106 << ovl->getName();
8107 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008108 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00008109 return 0;
John McCall864c0412011-04-26 20:42:42 +00008110 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008111
John McCall864c0412011-04-26 20:42:42 +00008112 Matched = Specialization;
8113 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00008114 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008115
Douglas Gregor4b52e252009-12-21 23:17:24 +00008116 return Matched;
8117}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008118
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008119
8120
8121
John McCall6dbba4f2011-10-11 23:14:30 +00008122// Resolve and fix an overloaded expression that can be resolved
8123// because it identifies a single function template specialization.
8124//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008125// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00008126//
8127// Return true if it was logically possible to so resolve the
8128// expression, regardless of whether or not it succeeded. Always
8129// returns true if 'complain' is set.
8130bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8131 ExprResult &SrcExpr, bool doFunctionPointerConverion,
8132 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008133 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00008134 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00008135 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008136
John McCall6dbba4f2011-10-11 23:14:30 +00008137 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008138
John McCall864c0412011-04-26 20:42:42 +00008139 DeclAccessPair found;
8140 ExprResult SingleFunctionExpression;
8141 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8142 ovl.Expression, /*complain*/ false, &found)) {
John McCall6dbba4f2011-10-11 23:14:30 +00008143 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8144 SrcExpr = ExprError();
8145 return true;
8146 }
John McCall864c0412011-04-26 20:42:42 +00008147
8148 // It is only correct to resolve to an instance method if we're
8149 // resolving a form that's permitted to be a pointer to member.
8150 // Otherwise we'll end up making a bound member expression, which
8151 // is illegal in all the contexts we resolve like this.
8152 if (!ovl.HasFormOfMemberPointer &&
8153 isa<CXXMethodDecl>(fn) &&
8154 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00008155 if (!complain) return false;
8156
8157 Diag(ovl.Expression->getExprLoc(),
8158 diag::err_bound_member_function)
8159 << 0 << ovl.Expression->getSourceRange();
8160
8161 // TODO: I believe we only end up here if there's a mix of
8162 // static and non-static candidates (otherwise the expression
8163 // would have 'bound member' type, not 'overload' type).
8164 // Ideally we would note which candidate was chosen and why
8165 // the static candidates were rejected.
8166 SrcExpr = ExprError();
8167 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008168 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00008169
John McCall864c0412011-04-26 20:42:42 +00008170 // Fix the expresion to refer to 'fn'.
8171 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00008172 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00008173
8174 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00008175 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00008176 SingleFunctionExpression =
8177 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00008178 if (SingleFunctionExpression.isInvalid()) {
8179 SrcExpr = ExprError();
8180 return true;
8181 }
8182 }
John McCall864c0412011-04-26 20:42:42 +00008183 }
8184
8185 if (!SingleFunctionExpression.isUsable()) {
8186 if (complain) {
8187 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8188 << ovl.Expression->getName()
8189 << DestTypeForComplaining
8190 << OpRangeForComplaining
8191 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00008192 NoteAllOverloadCandidates(SrcExpr.get());
8193
8194 SrcExpr = ExprError();
8195 return true;
8196 }
8197
8198 return false;
John McCall864c0412011-04-26 20:42:42 +00008199 }
8200
John McCall6dbba4f2011-10-11 23:14:30 +00008201 SrcExpr = SingleFunctionExpression;
8202 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008203}
8204
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008205/// \brief Add a single candidate to the overload set.
8206static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00008207 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00008208 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008209 Expr **Args, unsigned NumArgs,
8210 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00008211 bool PartialOverloading,
8212 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00008213 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00008214 if (isa<UsingShadowDecl>(Callee))
8215 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8216
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008217 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00008218 if (ExplicitTemplateArgs) {
8219 assert(!KnownValid && "Explicit template arguments?");
8220 return;
8221 }
John McCall9aa472c2010-03-19 07:35:19 +00008222 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00008223 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008224 return;
John McCallba135432009-11-21 08:51:07 +00008225 }
8226
8227 if (FunctionTemplateDecl *FuncTemplate
8228 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00008229 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8230 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00008231 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00008232 return;
8233 }
8234
Richard Smith2ced0442011-06-26 22:19:54 +00008235 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008236}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008237
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008238/// \brief Add the overload candidates named by callee and/or found by argument
8239/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00008240void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008241 Expr **Args, unsigned NumArgs,
8242 OverloadCandidateSet &CandidateSet,
8243 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00008244
8245#ifndef NDEBUG
8246 // Verify that ArgumentDependentLookup is consistent with the rules
8247 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008248 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008249 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8250 // and let Y be the lookup set produced by argument dependent
8251 // lookup (defined as follows). If X contains
8252 //
8253 // -- a declaration of a class member, or
8254 //
8255 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00008256 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008257 //
8258 // -- a declaration that is neither a function or a function
8259 // template
8260 //
8261 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00008262
John McCall3b4294e2009-12-16 12:17:52 +00008263 if (ULE->requiresADL()) {
8264 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8265 E = ULE->decls_end(); I != E; ++I) {
8266 assert(!(*I)->getDeclContext()->isRecord());
8267 assert(isa<UsingShadowDecl>(*I) ||
8268 !(*I)->getDeclContext()->isFunctionOrMethod());
8269 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00008270 }
8271 }
8272#endif
8273
John McCall3b4294e2009-12-16 12:17:52 +00008274 // It would be nice to avoid this copy.
8275 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00008276 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00008277 if (ULE->hasExplicitTemplateArgs()) {
8278 ULE->copyTemplateArgumentsInto(TABuffer);
8279 ExplicitTemplateArgs = &TABuffer;
8280 }
8281
8282 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8283 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00008284 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008285 Args, NumArgs, CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00008286 PartialOverloading, /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00008287
John McCall3b4294e2009-12-16 12:17:52 +00008288 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00008289 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8290 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008291 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008292 CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00008293 PartialOverloading,
8294 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008295}
John McCall578b69b2009-12-16 08:11:27 +00008296
Richard Smithf50e88a2011-06-05 22:42:48 +00008297/// Attempt to recover from an ill-formed use of a non-dependent name in a
8298/// template, where the non-dependent name was declared after the template
8299/// was defined. This is common in code written for a compilers which do not
8300/// correctly implement two-stage name lookup.
8301///
8302/// Returns true if a viable candidate was found and a diagnostic was issued.
8303static bool
8304DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8305 const CXXScopeSpec &SS, LookupResult &R,
8306 TemplateArgumentListInfo *ExplicitTemplateArgs,
8307 Expr **Args, unsigned NumArgs) {
8308 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8309 return false;
8310
8311 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8312 SemaRef.LookupQualifiedName(R, DC);
8313
8314 if (!R.empty()) {
8315 R.suppressDiagnostics();
8316
8317 if (isa<CXXRecordDecl>(DC)) {
8318 // Don't diagnose names we find in classes; we get much better
8319 // diagnostics for these from DiagnoseEmptyLookup.
8320 R.clear();
8321 return false;
8322 }
8323
8324 OverloadCandidateSet Candidates(FnLoc);
8325 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8326 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8327 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith2ced0442011-06-26 22:19:54 +00008328 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00008329
8330 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00008331 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008332 // No viable functions. Don't bother the user with notes for functions
8333 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00008334 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00008335 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00008336 }
Richard Smithf50e88a2011-06-05 22:42:48 +00008337
8338 // Find the namespaces where ADL would have looked, and suggest
8339 // declaring the function there instead.
8340 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8341 Sema::AssociatedClassSet AssociatedClasses;
8342 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8343 AssociatedNamespaces,
8344 AssociatedClasses);
8345 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00008346 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00008347 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008348 for (Sema::AssociatedNamespaceSet::iterator
8349 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00008350 end = AssociatedNamespaces.end(); it != end; ++it) {
8351 if (!Std->Encloses(*it))
8352 SuggestedNamespaces.insert(*it);
8353 }
Chandler Carruth45cad4a2011-06-08 10:13:17 +00008354 } else {
8355 // Lacking the 'std::' namespace, use all of the associated namespaces.
8356 SuggestedNamespaces = AssociatedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00008357 }
8358
8359 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8360 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00008361 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008362 SemaRef.Diag(Best->Function->getLocation(),
8363 diag::note_not_found_by_two_phase_lookup)
8364 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00008365 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008366 SemaRef.Diag(Best->Function->getLocation(),
8367 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00008368 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00008369 } else {
8370 // FIXME: It would be useful to list the associated namespaces here,
8371 // but the diagnostics infrastructure doesn't provide a way to produce
8372 // a localized representation of a list of items.
8373 SemaRef.Diag(Best->Function->getLocation(),
8374 diag::note_not_found_by_two_phase_lookup)
8375 << R.getLookupName() << 2;
8376 }
8377
8378 // Try to recover by calling this function.
8379 return true;
8380 }
8381
8382 R.clear();
8383 }
8384
8385 return false;
8386}
8387
8388/// Attempt to recover from ill-formed use of a non-dependent operator in a
8389/// template, where the non-dependent operator was declared after the template
8390/// was defined.
8391///
8392/// Returns true if a viable candidate was found and a diagnostic was issued.
8393static bool
8394DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8395 SourceLocation OpLoc,
8396 Expr **Args, unsigned NumArgs) {
8397 DeclarationName OpName =
8398 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8399 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8400 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8401 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8402}
8403
John McCall578b69b2009-12-16 08:11:27 +00008404/// Attempts to recover from a call where no functions were found.
8405///
8406/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00008407static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00008408BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00008409 UnresolvedLookupExpr *ULE,
8410 SourceLocation LParenLoc,
8411 Expr **Args, unsigned NumArgs,
Richard Smithf50e88a2011-06-05 22:42:48 +00008412 SourceLocation RParenLoc,
8413 bool EmptyLookup) {
John McCall578b69b2009-12-16 08:11:27 +00008414
8415 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00008416 SS.Adopt(ULE->getQualifierLoc());
John McCall578b69b2009-12-16 08:11:27 +00008417
John McCall3b4294e2009-12-16 12:17:52 +00008418 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00008419 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00008420 if (ULE->hasExplicitTemplateArgs()) {
8421 ULE->copyTemplateArgumentsInto(TABuffer);
8422 ExplicitTemplateArgs = &TABuffer;
8423 }
8424
John McCall578b69b2009-12-16 08:11:27 +00008425 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8426 Sema::LookupOrdinaryName);
Richard Smithf50e88a2011-06-05 22:42:48 +00008427 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8428 ExplicitTemplateArgs, Args, NumArgs) &&
8429 (!EmptyLookup ||
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00008430 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00008431 ExplicitTemplateArgs, Args, NumArgs)))
John McCallf312b1e2010-08-26 23:41:50 +00008432 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00008433
John McCall3b4294e2009-12-16 12:17:52 +00008434 assert(!R.empty() && "lookup results empty despite recovery");
8435
8436 // Build an implicit member call if appropriate. Just drop the
8437 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00008438 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00008439 if ((*R.begin())->isCXXClassMember())
Chandler Carruth6df868e2010-12-12 08:17:55 +00008440 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8441 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00008442 else if (ExplicitTemplateArgs)
8443 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8444 else
8445 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8446
8447 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008448 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00008449
8450 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00008451 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00008452 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00008453 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00008454 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00008455}
Douglas Gregord7a95972010-06-08 17:35:15 +00008456
Douglas Gregorf6b89692008-11-26 05:54:23 +00008457/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00008458/// (which eventually refers to the declaration Func) and the call
8459/// arguments Args/NumArgs, attempt to resolve the function call down
8460/// to a specific function. If overload resolution succeeds, returns
8461/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00008462/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00008463/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00008464ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00008465Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00008466 SourceLocation LParenLoc,
8467 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00008468 SourceLocation RParenLoc,
8469 Expr *ExecConfig) {
John McCall3b4294e2009-12-16 12:17:52 +00008470#ifndef NDEBUG
8471 if (ULE->requiresADL()) {
8472 // To do ADL, we must have found an unqualified name.
8473 assert(!ULE->getQualifier() && "qualified name with ADL");
8474
8475 // We don't perform ADL for implicit declarations of builtins.
8476 // Verify that this was correctly set up.
8477 FunctionDecl *F;
8478 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8479 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8480 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00008481 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008482
John McCall3b4294e2009-12-16 12:17:52 +00008483 // We don't perform ADL in C.
8484 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00008485 } else
8486 assert(!ULE->isStdAssociatedNamespace() &&
8487 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00008488#endif
8489
John McCall5769d612010-02-08 23:07:23 +00008490 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00008491
John McCall3b4294e2009-12-16 12:17:52 +00008492 // Add the functions denoted by the callee to the set of candidate
8493 // functions, including those from argument-dependent lookup.
8494 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00008495
8496 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00008497 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8498 // out if it fails.
Francois Pichet0f74d1e2011-09-07 00:14:57 +00008499 if (CandidateSet.empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00008500 // In Microsoft mode, if we are inside a template class member function then
8501 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00008502 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00008503 // classes.
8504 if (getLangOptions().MicrosoftExt && CurContext->isDependentContext() &&
8505 isa<CXXMethodDecl>(CurContext)) {
8506 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8507 Context.DependentTy, VK_RValue,
8508 RParenLoc);
8509 CE->setTypeDependent(true);
8510 return Owned(CE);
8511 }
Douglas Gregor1aae80b2010-04-14 20:27:54 +00008512 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smithf50e88a2011-06-05 22:42:48 +00008513 RParenLoc, /*EmptyLookup=*/true);
Francois Pichet0f74d1e2011-09-07 00:14:57 +00008514 }
John McCall578b69b2009-12-16 08:11:27 +00008515
Douglas Gregorf6b89692008-11-26 05:54:23 +00008516 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008517 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00008518 case OR_Success: {
8519 FunctionDecl *FDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00008520 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCall9aa472c2010-03-19 07:35:19 +00008521 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth6df868e2010-12-12 08:17:55 +00008522 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
8523 ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00008524 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00008525 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8526 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00008527 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00008528
Richard Smithf50e88a2011-06-05 22:42:48 +00008529 case OR_No_Viable_Function: {
8530 // Try to recover by looking for viable functions which the user might
8531 // have meant to call.
8532 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8533 Args, NumArgs, RParenLoc,
8534 /*EmptyLookup=*/false);
8535 if (!Recovery.isInvalid())
8536 return Recovery;
8537
Chris Lattner4330d652009-02-17 07:29:20 +00008538 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00008539 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00008540 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008541 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00008542 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00008543 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00008544
8545 case OR_Ambiguous:
8546 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00008547 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008548 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00008549 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008550
8551 case OR_Deleted:
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00008552 {
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00008553 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8554 << Best->Function->isDeleted()
8555 << ULE->getName()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00008556 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00008557 << Fn->getSourceRange();
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00008558 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8559 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008560 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00008561 }
8562
Douglas Gregorff331c12010-07-25 18:17:45 +00008563 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00008564 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00008565}
8566
John McCall6e266892010-01-26 03:27:55 +00008567static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00008568 return Functions.size() > 1 ||
8569 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8570}
8571
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008572/// \brief Create a unary operation that may resolve to an overloaded
8573/// operator.
8574///
8575/// \param OpLoc The location of the operator itself (e.g., '*').
8576///
8577/// \param OpcIn The UnaryOperator::Opcode that describes this
8578/// operator.
8579///
8580/// \param Functions The set of non-member functions that will be
8581/// considered by overload resolution. The caller needs to build this
8582/// set based on the context using, e.g.,
8583/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8584/// set should not contain any member functions; those will be added
8585/// by CreateOverloadedUnaryOp().
8586///
8587/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00008588ExprResult
John McCall6e266892010-01-26 03:27:55 +00008589Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8590 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00008591 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008592 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008593
8594 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8595 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8596 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00008597 // TODO: provide better source location info.
8598 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008599
John Wiegley429bb272011-04-08 18:41:53 +00008600 if (Input->getObjectKind() == OK_ObjCProperty) {
8601 ExprResult Result = ConvertPropertyForRValue(Input);
8602 if (Result.isInvalid())
8603 return ExprError();
8604 Input = Result.take();
8605 }
John McCall0e800c92010-12-04 08:14:53 +00008606
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008607 Expr *Args[2] = { Input, 0 };
8608 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00008609
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008610 // For post-increment and post-decrement, add the implicit '0' as
8611 // the second argument, so that we know this is a post-increment or
8612 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00008613 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008614 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008615 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8616 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008617 NumArgs = 2;
8618 }
8619
8620 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00008621 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00008622 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008623 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00008624 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008625 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00008626 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008627
John McCallc373d482010-01-27 01:50:18 +00008628 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00008629 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00008630 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00008631 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00008632 /*ADL*/ true, IsOverloaded(Fns),
8633 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008634 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor4c9be892011-02-28 20:01:57 +00008635 &Args[0], NumArgs,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008636 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008637 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008638 OpLoc));
8639 }
8640
8641 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00008642 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008643
8644 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00008645 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008646
8647 // Add operator candidates that are member functions.
8648 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8649
John McCall6e266892010-01-26 03:27:55 +00008650 // Add candidates from ADL.
8651 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00008652 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00008653 /*ExplicitTemplateArgs*/ 0,
8654 CandidateSet);
8655
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008656 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00008657 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008658
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008659 bool HadMultipleCandidates = (CandidateSet.size() > 1);
8660
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008661 // Perform overload resolution.
8662 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008663 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008664 case OR_Success: {
8665 // We found a built-in operator or an overloaded operator.
8666 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00008667
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008668 if (FnDecl) {
8669 // We matched an overloaded operator. Build a call to that
8670 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00008671
Chandler Carruth25ca4212011-02-25 19:41:05 +00008672 MarkDeclarationReferenced(OpLoc, FnDecl);
8673
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008674 // Convert the arguments.
8675 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00008676 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00008677
John Wiegley429bb272011-04-08 18:41:53 +00008678 ExprResult InputRes =
8679 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8680 Best->FoundDecl, Method);
8681 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008682 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008683 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008684 } else {
8685 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00008686 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00008687 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00008688 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00008689 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008690 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00008691 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00008692 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008693 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00008694 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008695 }
8696
John McCallb697e082010-05-06 18:15:07 +00008697 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8698
John McCallf89e55a2010-11-18 06:31:45 +00008699 // Determine the result type.
8700 QualType ResultTy = FnDecl->getResultType();
8701 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8702 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00008703
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008704 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008705 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
8706 HadMultipleCandidates);
John Wiegley429bb272011-04-08 18:41:53 +00008707 if (FnExpr.isInvalid())
8708 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00008709
Eli Friedman4c3b8962009-11-18 03:58:17 +00008710 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00008711 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00008712 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00008713 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00008714
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008715 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00008716 FnDecl))
8717 return ExprError();
8718
John McCall9ae2f072010-08-23 23:25:46 +00008719 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008720 } else {
8721 // We matched a built-in operator. Convert the arguments, then
8722 // break out so that we will build the appropriate built-in
8723 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00008724 ExprResult InputRes =
8725 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8726 Best->Conversions[0], AA_Passing);
8727 if (InputRes.isInvalid())
8728 return ExprError();
8729 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008730 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008731 }
John Wiegley429bb272011-04-08 18:41:53 +00008732 }
8733
8734 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +00008735 // This is an erroneous use of an operator which can be overloaded by
8736 // a non-member function. Check for non-member operators which were
8737 // defined too late to be candidates.
8738 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
8739 // FIXME: Recover by calling the found function.
8740 return ExprError();
8741
John Wiegley429bb272011-04-08 18:41:53 +00008742 // No viable function; fall through to handling this as a
8743 // built-in operator, which will produce an error message for us.
8744 break;
8745
8746 case OR_Ambiguous:
8747 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8748 << UnaryOperator::getOpcodeStr(Opc)
8749 << Input->getType()
8750 << Input->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00008751 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley429bb272011-04-08 18:41:53 +00008752 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8753 return ExprError();
8754
8755 case OR_Deleted:
8756 Diag(OpLoc, diag::err_ovl_deleted_oper)
8757 << Best->Function->isDeleted()
8758 << UnaryOperator::getOpcodeStr(Opc)
8759 << getDeletedOrUnavailableSuffix(Best->Function)
8760 << Input->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00008761 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
8762 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00008763 return ExprError();
8764 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008765
8766 // Either we found no viable overloaded operator or we matched a
8767 // built-in operator. In either case, fall through to trying to
8768 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00008769 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008770}
8771
Douglas Gregor063daf62009-03-13 18:40:31 +00008772/// \brief Create a binary operation that may resolve to an overloaded
8773/// operator.
8774///
8775/// \param OpLoc The location of the operator itself (e.g., '+').
8776///
8777/// \param OpcIn The BinaryOperator::Opcode that describes this
8778/// operator.
8779///
8780/// \param Functions The set of non-member functions that will be
8781/// considered by overload resolution. The caller needs to build this
8782/// set based on the context using, e.g.,
8783/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8784/// set should not contain any member functions; those will be added
8785/// by CreateOverloadedBinOp().
8786///
8787/// \param LHS Left-hand argument.
8788/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00008789ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00008790Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00008791 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00008792 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00008793 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00008794 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008795 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00008796
8797 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8798 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8799 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8800
8801 // If either side is type-dependent, create an appropriate dependent
8802 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008803 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00008804 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008805 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008806 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00008807 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008808 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +00008809 Context.DependentTy,
8810 VK_RValue, OK_Ordinary,
8811 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008812
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008813 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8814 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008815 VK_LValue,
8816 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008817 Context.DependentTy,
8818 Context.DependentTy,
8819 OpLoc));
8820 }
John McCall6e266892010-01-26 03:27:55 +00008821
8822 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00008823 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00008824 // TODO: provide better source location info in DNLoc component.
8825 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00008826 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +00008827 = UnresolvedLookupExpr::Create(Context, NamingClass,
8828 NestedNameSpecifierLoc(), OpNameInfo,
8829 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00008830 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00008831 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00008832 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00008833 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008834 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +00008835 OpLoc));
8836 }
8837
John McCall0e800c92010-12-04 08:14:53 +00008838 // Always do property rvalue conversions on the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00008839 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8840 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8841 if (Result.isInvalid())
8842 return ExprError();
8843 Args[1] = Result.take();
8844 }
John McCall0e800c92010-12-04 08:14:53 +00008845
8846 // The LHS is more complicated.
8847 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8848
8849 // There's a tension for assignment operators between primitive
8850 // property assignment and the overloaded operators.
8851 if (BinaryOperator::isAssignmentOp(Opc)) {
8852 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8853
8854 // Is the property "logically" settable?
8855 bool Settable = (PRE->isExplicitProperty() ||
8856 PRE->getImplicitPropertySetter());
8857
8858 // To avoid gratuitously inventing semantics, use the primitive
8859 // unless it isn't. Thoughts in case we ever really care:
8860 // - If the property isn't logically settable, we have to
8861 // load and hope.
8862 // - If the property is settable and this is simple assignment,
8863 // we really should use the primitive.
8864 // - If the property is settable, then we could try overloading
8865 // on a generic lvalue of the appropriate type; if it works
8866 // out to a builtin candidate, we would do that same operation
8867 // on the property, and otherwise just error.
8868 if (Settable)
8869 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8870 }
8871
John Wiegley429bb272011-04-08 18:41:53 +00008872 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8873 if (Result.isInvalid())
8874 return ExprError();
8875 Args[0] = Result.take();
John McCall0e800c92010-12-04 08:14:53 +00008876 }
Douglas Gregor063daf62009-03-13 18:40:31 +00008877
Sebastian Redl275c2b42009-11-18 23:10:33 +00008878 // If this is the assignment operator, we only perform overload resolution
8879 // if the left-hand side is a class or enumeration type. This is actually
8880 // a hack. The standard requires that we do overload resolution between the
8881 // various built-in candidates, but as DR507 points out, this can lead to
8882 // problems. So we do it this way, which pretty much follows what GCC does.
8883 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00008884 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00008885 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00008886
John McCall0e800c92010-12-04 08:14:53 +00008887 // If this is the .* operator, which is not overloadable, just
8888 // create a built-in binary operator.
8889 if (Opc == BO_PtrMemD)
8890 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8891
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008892 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00008893 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00008894
8895 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00008896 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00008897
8898 // Add operator candidates that are member functions.
8899 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8900
John McCall6e266892010-01-26 03:27:55 +00008901 // Add candidates from ADL.
8902 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8903 Args, 2,
8904 /*ExplicitTemplateArgs*/ 0,
8905 CandidateSet);
8906
Douglas Gregor063daf62009-03-13 18:40:31 +00008907 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00008908 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00008909
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008910 bool HadMultipleCandidates = (CandidateSet.size() > 1);
8911
Douglas Gregor063daf62009-03-13 18:40:31 +00008912 // Perform overload resolution.
8913 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008914 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00008915 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00008916 // We found a built-in operator or an overloaded operator.
8917 FunctionDecl *FnDecl = Best->Function;
8918
8919 if (FnDecl) {
8920 // We matched an overloaded operator. Build a call to that
8921 // operator.
8922
Chandler Carruth25ca4212011-02-25 19:41:05 +00008923 MarkDeclarationReferenced(OpLoc, FnDecl);
8924
Douglas Gregor063daf62009-03-13 18:40:31 +00008925 // Convert the arguments.
8926 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00008927 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00008928 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00008929
Chandler Carruth6df868e2010-12-12 08:17:55 +00008930 ExprResult Arg1 =
8931 PerformCopyInitialization(
8932 InitializedEntity::InitializeParameter(Context,
8933 FnDecl->getParamDecl(0)),
8934 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008935 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00008936 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008937
John Wiegley429bb272011-04-08 18:41:53 +00008938 ExprResult Arg0 =
8939 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8940 Best->FoundDecl, Method);
8941 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008942 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008943 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008944 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00008945 } else {
8946 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +00008947 ExprResult Arg0 = PerformCopyInitialization(
8948 InitializedEntity::InitializeParameter(Context,
8949 FnDecl->getParamDecl(0)),
8950 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008951 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00008952 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008953
Chandler Carruth6df868e2010-12-12 08:17:55 +00008954 ExprResult Arg1 =
8955 PerformCopyInitialization(
8956 InitializedEntity::InitializeParameter(Context,
8957 FnDecl->getParamDecl(1)),
8958 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00008959 if (Arg1.isInvalid())
8960 return ExprError();
8961 Args[0] = LHS = Arg0.takeAs<Expr>();
8962 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00008963 }
8964
John McCallb697e082010-05-06 18:15:07 +00008965 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8966
John McCallf89e55a2010-11-18 06:31:45 +00008967 // Determine the result type.
8968 QualType ResultTy = FnDecl->getResultType();
8969 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8970 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00008971
8972 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008973 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
8974 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00008975 if (FnExpr.isInvalid())
8976 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +00008977
John McCall9ae2f072010-08-23 23:25:46 +00008978 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00008979 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00008980 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008981
8982 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00008983 FnDecl))
8984 return ExprError();
8985
John McCall9ae2f072010-08-23 23:25:46 +00008986 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00008987 } else {
8988 // We matched a built-in operator. Convert the arguments, then
8989 // break out so that we will build the appropriate built-in
8990 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00008991 ExprResult ArgsRes0 =
8992 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8993 Best->Conversions[0], AA_Passing);
8994 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00008995 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008996 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00008997
John Wiegley429bb272011-04-08 18:41:53 +00008998 ExprResult ArgsRes1 =
8999 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9000 Best->Conversions[1], AA_Passing);
9001 if (ArgsRes1.isInvalid())
9002 return ExprError();
9003 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00009004 break;
9005 }
9006 }
9007
Douglas Gregor33074752009-09-30 21:46:01 +00009008 case OR_No_Viable_Function: {
9009 // C++ [over.match.oper]p9:
9010 // If the operator is the operator , [...] and there are no
9011 // viable functions, then the operator is assumed to be the
9012 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00009013 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00009014 break;
9015
Chandler Carruth6df868e2010-12-12 08:17:55 +00009016 // For class as left operand for assignment or compound assigment
9017 // operator do not fall through to handling in built-in, but report that
9018 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00009019 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009020 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00009021 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00009022 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9023 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009024 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00009025 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +00009026 // This is an erroneous use of an operator which can be overloaded by
9027 // a non-member function. Check for non-member operators which were
9028 // defined too late to be candidates.
9029 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9030 // FIXME: Recover by calling the found function.
9031 return ExprError();
9032
Douglas Gregor33074752009-09-30 21:46:01 +00009033 // No viable function; try to create a built-in operation, which will
9034 // produce an error. Then, show the non-viable candidates.
9035 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00009036 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009037 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +00009038 "C++ binary operator overloading is missing candidates!");
9039 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00009040 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9041 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00009042 return move(Result);
9043 }
Douglas Gregor063daf62009-03-13 18:40:31 +00009044
9045 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00009046 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +00009047 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00009048 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009049 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009050 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9051 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009052 return ExprError();
9053
9054 case OR_Deleted:
9055 Diag(OpLoc, diag::err_ovl_deleted_oper)
9056 << Best->Function->isDeleted()
9057 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009058 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009059 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00009060 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9061 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009062 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00009063 }
Douglas Gregor063daf62009-03-13 18:40:31 +00009064
Douglas Gregor33074752009-09-30 21:46:01 +00009065 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009066 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00009067}
9068
John McCall60d7b3a2010-08-24 06:29:42 +00009069ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +00009070Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9071 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009072 Expr *Base, Expr *Idx) {
9073 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +00009074 DeclarationName OpName =
9075 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9076
9077 // If either side is type-dependent, create an appropriate dependent
9078 // expression.
9079 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9080
John McCallc373d482010-01-27 01:50:18 +00009081 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00009082 // CHECKME: no 'operator' keyword?
9083 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9084 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00009085 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009086 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009087 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009088 /*ADL*/ true, /*Overloaded*/ false,
9089 UnresolvedSetIterator(),
9090 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00009091 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00009092
Sebastian Redlf322ed62009-10-29 20:17:01 +00009093 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9094 Args, 2,
9095 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009096 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +00009097 RLoc));
9098 }
9099
John Wiegley429bb272011-04-08 18:41:53 +00009100 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
9101 ExprResult Result = ConvertPropertyForRValue(Args[0]);
9102 if (Result.isInvalid())
9103 return ExprError();
9104 Args[0] = Result.take();
9105 }
9106 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
9107 ExprResult Result = ConvertPropertyForRValue(Args[1]);
9108 if (Result.isInvalid())
9109 return ExprError();
9110 Args[1] = Result.take();
9111 }
John McCall0e800c92010-12-04 08:14:53 +00009112
Sebastian Redlf322ed62009-10-29 20:17:01 +00009113 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009114 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009115
9116 // Subscript can only be overloaded as a member function.
9117
9118 // Add operator candidates that are member functions.
9119 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9120
9121 // Add builtin operator candidates.
9122 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9123
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009124 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9125
Sebastian Redlf322ed62009-10-29 20:17:01 +00009126 // Perform overload resolution.
9127 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009128 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00009129 case OR_Success: {
9130 // We found a built-in operator or an overloaded operator.
9131 FunctionDecl *FnDecl = Best->Function;
9132
9133 if (FnDecl) {
9134 // We matched an overloaded operator. Build a call to that
9135 // operator.
9136
Chandler Carruth25ca4212011-02-25 19:41:05 +00009137 MarkDeclarationReferenced(LLoc, FnDecl);
9138
John McCall9aa472c2010-03-19 07:35:19 +00009139 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009140 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00009141
Sebastian Redlf322ed62009-10-29 20:17:01 +00009142 // Convert the arguments.
9143 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +00009144 ExprResult Arg0 =
9145 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9146 Best->FoundDecl, Method);
9147 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +00009148 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009149 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +00009150
Anders Carlsson38f88ab2010-01-29 18:37:50 +00009151 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00009152 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +00009153 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009154 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +00009155 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009156 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +00009157 Owned(Args[1]));
9158 if (InputInit.isInvalid())
9159 return ExprError();
9160
9161 Args[1] = InputInit.takeAs<Expr>();
9162
Sebastian Redlf322ed62009-10-29 20:17:01 +00009163 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +00009164 QualType ResultTy = FnDecl->getResultType();
9165 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9166 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009167
9168 // Build the actual expression node.
Douglas Gregor5b8968c2011-07-15 16:25:15 +00009169 DeclarationNameLoc LocInfo;
9170 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9171 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009172 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9173 HadMultipleCandidates,
9174 LLoc, LocInfo);
John Wiegley429bb272011-04-08 18:41:53 +00009175 if (FnExpr.isInvalid())
9176 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00009177
John McCall9ae2f072010-08-23 23:25:46 +00009178 CXXOperatorCallExpr *TheCall =
9179 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley429bb272011-04-08 18:41:53 +00009180 FnExpr.take(), Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +00009181 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009182
John McCall9ae2f072010-08-23 23:25:46 +00009183 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +00009184 FnDecl))
9185 return ExprError();
9186
John McCall9ae2f072010-08-23 23:25:46 +00009187 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009188 } else {
9189 // We matched a built-in operator. Convert the arguments, then
9190 // break out so that we will build the appropriate built-in
9191 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009192 ExprResult ArgsRes0 =
9193 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9194 Best->Conversions[0], AA_Passing);
9195 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +00009196 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009197 Args[0] = ArgsRes0.take();
9198
9199 ExprResult ArgsRes1 =
9200 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9201 Best->Conversions[1], AA_Passing);
9202 if (ArgsRes1.isInvalid())
9203 return ExprError();
9204 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +00009205
9206 break;
9207 }
9208 }
9209
9210 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00009211 if (CandidateSet.empty())
9212 Diag(LLoc, diag::err_ovl_no_oper)
9213 << Args[0]->getType() << /*subscript*/ 0
9214 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9215 else
9216 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9217 << Args[0]->getType()
9218 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009219 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9220 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +00009221 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00009222 }
9223
9224 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00009225 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009226 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +00009227 << Args[0]->getType() << Args[1]->getType()
9228 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009229 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9230 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009231 return ExprError();
9232
9233 case OR_Deleted:
9234 Diag(LLoc, diag::err_ovl_deleted_oper)
9235 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009236 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +00009237 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009238 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9239 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009240 return ExprError();
9241 }
9242
9243 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +00009244 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009245}
9246
Douglas Gregor88a35142008-12-22 05:46:06 +00009247/// BuildCallToMemberFunction - Build a call to a member
9248/// function. MemExpr is the expression that refers to the member
9249/// function (and includes the object parameter), Args/NumArgs are the
9250/// arguments to the function call (not including the object
9251/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +00009252/// expression refers to a non-static member function or an overloaded
9253/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +00009254ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00009255Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9256 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +00009257 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +00009258 assert(MemExprE->getType() == Context.BoundMemberTy ||
9259 MemExprE->getType() == Context.OverloadTy);
9260
Douglas Gregor88a35142008-12-22 05:46:06 +00009261 // Dig out the member expression. This holds both the object
9262 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00009263 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009264
John McCall864c0412011-04-26 20:42:42 +00009265 // Determine whether this is a call to a pointer-to-member function.
9266 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9267 assert(op->getType() == Context.BoundMemberTy);
9268 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9269
9270 QualType fnType =
9271 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9272
9273 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9274 QualType resultType = proto->getCallResultType(Context);
9275 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9276
9277 // Check that the object type isn't more qualified than the
9278 // member function we're calling.
9279 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9280
9281 QualType objectType = op->getLHS()->getType();
9282 if (op->getOpcode() == BO_PtrMemI)
9283 objectType = objectType->castAs<PointerType>()->getPointeeType();
9284 Qualifiers objectQuals = objectType.getQualifiers();
9285
9286 Qualifiers difference = objectQuals - funcQuals;
9287 difference.removeObjCGCAttr();
9288 difference.removeAddressSpace();
9289 if (difference) {
9290 std::string qualsString = difference.getAsString();
9291 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9292 << fnType.getUnqualifiedType()
9293 << qualsString
9294 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9295 }
9296
9297 CXXMemberCallExpr *call
9298 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9299 resultType, valueKind, RParenLoc);
9300
9301 if (CheckCallReturnType(proto->getResultType(),
9302 op->getRHS()->getSourceRange().getBegin(),
9303 call, 0))
9304 return ExprError();
9305
9306 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9307 return ExprError();
9308
9309 return MaybeBindToTemporary(call);
9310 }
9311
John McCall129e2df2009-11-30 22:42:35 +00009312 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00009313 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00009314 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00009315 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00009316 if (isa<MemberExpr>(NakedMemExpr)) {
9317 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00009318 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00009319 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00009320 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00009321 } else {
9322 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00009323 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009324
John McCall701c89e2009-12-03 04:06:58 +00009325 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009326 Expr::Classification ObjectClassification
9327 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9328 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +00009329
Douglas Gregor88a35142008-12-22 05:46:06 +00009330 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00009331 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00009332
John McCallaa81e162009-12-01 22:10:20 +00009333 // FIXME: avoid copy.
9334 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9335 if (UnresExpr->hasExplicitTemplateArgs()) {
9336 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9337 TemplateArgs = &TemplateArgsBuffer;
9338 }
9339
John McCall129e2df2009-11-30 22:42:35 +00009340 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9341 E = UnresExpr->decls_end(); I != E; ++I) {
9342
John McCall701c89e2009-12-03 04:06:58 +00009343 NamedDecl *Func = *I;
9344 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9345 if (isa<UsingShadowDecl>(Func))
9346 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9347
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009348
Francois Pichetdbee3412011-01-18 05:04:39 +00009349 // Microsoft supports direct constructor calls.
Francois Pichet62ec1f22011-09-17 17:15:52 +00009350 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichetdbee3412011-01-18 05:04:39 +00009351 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9352 CandidateSet);
9353 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00009354 // If explicit template arguments were provided, we can't call a
9355 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00009356 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00009357 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009358
John McCall9aa472c2010-03-19 07:35:19 +00009359 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009360 ObjectClassification,
9361 Args, NumArgs, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009362 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00009363 } else {
John McCall129e2df2009-11-30 22:42:35 +00009364 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00009365 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009366 ObjectType, ObjectClassification,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009367 Args, NumArgs, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +00009368 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00009369 }
Douglas Gregordec06662009-08-21 18:42:58 +00009370 }
Mike Stump1eb44332009-09-09 15:08:12 +00009371
John McCall129e2df2009-11-30 22:42:35 +00009372 DeclarationName DeclName = UnresExpr->getMemberName();
9373
Douglas Gregor88a35142008-12-22 05:46:06 +00009374 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009375 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +00009376 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00009377 case OR_Success:
9378 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009379 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +00009380 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00009381 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009382 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00009383 break;
9384
9385 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00009386 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00009387 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00009388 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009389 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00009390 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00009391 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00009392
9393 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00009394 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00009395 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009396 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00009397 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00009398 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009399
9400 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00009401 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009402 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009403 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009404 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009405 << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009406 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009407 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00009408 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00009409 }
9410
John McCall6bb80172010-03-30 21:47:33 +00009411 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00009412
John McCallaa81e162009-12-01 22:10:20 +00009413 // If overload resolution picked a static member, build a
9414 // non-member call based on that function.
9415 if (Method->isStatic()) {
9416 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9417 Args, NumArgs, RParenLoc);
9418 }
9419
John McCall129e2df2009-11-30 22:42:35 +00009420 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00009421 }
9422
John McCallf89e55a2010-11-18 06:31:45 +00009423 QualType ResultType = Method->getResultType();
9424 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9425 ResultType = ResultType.getNonLValueExprType(Context);
9426
Douglas Gregor88a35142008-12-22 05:46:06 +00009427 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009428 CXXMemberCallExpr *TheCall =
John McCall9ae2f072010-08-23 23:25:46 +00009429 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +00009430 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +00009431
Anders Carlssoneed3e692009-10-10 00:06:20 +00009432 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009433 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +00009434 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +00009435 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009436
Douglas Gregor88a35142008-12-22 05:46:06 +00009437 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00009438 // We only need to do this if there was actually an overload; otherwise
9439 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +00009440 if (!Method->isStatic()) {
9441 ExprResult ObjectArg =
9442 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9443 FoundDecl, Method);
9444 if (ObjectArg.isInvalid())
9445 return ExprError();
9446 MemExpr->setBase(ObjectArg.take());
9447 }
Douglas Gregor88a35142008-12-22 05:46:06 +00009448
9449 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +00009450 const FunctionProtoType *Proto =
9451 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +00009452 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00009453 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00009454 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00009455
John McCall9ae2f072010-08-23 23:25:46 +00009456 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +00009457 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00009458
Anders Carlsson2174d4c2011-05-06 14:25:31 +00009459 if ((isa<CXXConstructorDecl>(CurContext) ||
9460 isa<CXXDestructorDecl>(CurContext)) &&
9461 TheCall->getMethodDecl()->isPure()) {
9462 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9463
Chandler Carruthae198062011-06-27 08:31:58 +00009464 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +00009465 Diag(MemExpr->getLocStart(),
9466 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9467 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9468 << MD->getParent()->getDeclName();
9469
9470 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +00009471 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +00009472 }
John McCall9ae2f072010-08-23 23:25:46 +00009473 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +00009474}
9475
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009476/// BuildCallToObjectOfClassType - Build a call to an object of class
9477/// type (C++ [over.call.object]), which can end up invoking an
9478/// overloaded function call operator (@c operator()) or performing a
9479/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +00009480ExprResult
John Wiegley429bb272011-04-08 18:41:53 +00009481Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +00009482 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009483 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009484 SourceLocation RParenLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00009485 ExprResult Object = Owned(Obj);
9486 if (Object.get()->getObjectKind() == OK_ObjCProperty) {
9487 Object = ConvertPropertyForRValue(Object.take());
9488 if (Object.isInvalid())
9489 return ExprError();
9490 }
John McCall0e800c92010-12-04 08:14:53 +00009491
John Wiegley429bb272011-04-08 18:41:53 +00009492 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9493 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00009494
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009495 // C++ [over.call.object]p1:
9496 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00009497 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009498 // candidate functions includes at least the function call
9499 // operators of T. The function call operators of T are obtained by
9500 // ordinary lookup of the name operator() in the context of
9501 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00009502 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00009503 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00009504
John Wiegley429bb272011-04-08 18:41:53 +00009505 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00009506 PDiag(diag::err_incomplete_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00009507 << Object.get()->getSourceRange()))
Douglas Gregor593564b2009-11-15 07:48:03 +00009508 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009509
John McCalla24dc2e2009-11-17 02:14:36 +00009510 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9511 LookupQualifiedName(R, Record->getDecl());
9512 R.suppressDiagnostics();
9513
Douglas Gregor593564b2009-11-15 07:48:03 +00009514 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00009515 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +00009516 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9517 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00009518 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00009519 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009520
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009521 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +00009522 // In addition, for each (non-explicit in C++0x) conversion function
9523 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009524 //
9525 // operator conversion-type-id () cv-qualifier;
9526 //
9527 // where cv-qualifier is the same cv-qualification as, or a
9528 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00009529 // denotes the type "pointer to function of (P1,...,Pn) returning
9530 // R", or the type "reference to pointer to function of
9531 // (P1,...,Pn) returning R", or the type "reference to function
9532 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009533 // is also considered as a candidate function. Similarly,
9534 // surrogate call functions are added to the set of candidate
9535 // functions for each conversion function declared in an
9536 // accessible base class provided the function is not hidden
9537 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00009538 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00009539 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00009540 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00009541 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00009542 NamedDecl *D = *I;
9543 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9544 if (isa<UsingShadowDecl>(D))
9545 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009546
Douglas Gregor4a27d702009-10-21 06:18:39 +00009547 // Skip over templated conversion functions; they aren't
9548 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00009549 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00009550 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009551
John McCall701c89e2009-12-03 04:06:58 +00009552 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +00009553 if (!Conv->isExplicit()) {
9554 // Strip the reference type (if any) and then the pointer type (if
9555 // any) to get down to what might be a function type.
9556 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9557 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9558 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +00009559
Douglas Gregorbf6e3172011-07-23 18:59:35 +00009560 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9561 {
9562 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9563 Object.get(), Args, NumArgs, CandidateSet);
9564 }
9565 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009566 }
Mike Stump1eb44332009-09-09 15:08:12 +00009567
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009568 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9569
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009570 // Perform overload resolution.
9571 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +00009572 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +00009573 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009574 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009575 // Overload resolution succeeded; we'll build the appropriate call
9576 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009577 break;
9578
9579 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00009580 if (CandidateSet.empty())
John Wiegley429bb272011-04-08 18:41:53 +00009581 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9582 << Object.get()->getType() << /*call*/ 1
9583 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +00009584 else
John Wiegley429bb272011-04-08 18:41:53 +00009585 Diag(Object.get()->getSourceRange().getBegin(),
John McCall1eb3e102010-01-07 02:04:15 +00009586 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00009587 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009588 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009589 break;
9590
9591 case OR_Ambiguous:
John Wiegley429bb272011-04-08 18:41:53 +00009592 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009593 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00009594 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009595 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009596 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009597
9598 case OR_Deleted:
John Wiegley429bb272011-04-08 18:41:53 +00009599 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009600 diag::err_ovl_deleted_object_call)
9601 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +00009602 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009603 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +00009604 << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009605 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009606 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009607 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009608
Douglas Gregorff331c12010-07-25 18:17:45 +00009609 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009610 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009611
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009612 if (Best->Function == 0) {
9613 // Since there is no function declaration, this is one of the
9614 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00009615 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009616 = cast<CXXConversionDecl>(
9617 Best->Conversions[0].UserDefined.ConversionFunction);
9618
John Wiegley429bb272011-04-08 18:41:53 +00009619 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009620 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00009621
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009622 // We selected one of the surrogate functions that converts the
9623 // object parameter to a function pointer. Perform the conversion
9624 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009625
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00009626 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00009627 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009628 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
9629 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00009630 if (Call.isInvalid())
9631 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009632
Douglas Gregorf2ae5262011-01-20 00:18:04 +00009633 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00009634 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009635 }
9636
Chandler Carruth25ca4212011-02-25 19:41:05 +00009637 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +00009638 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009639 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00009640
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009641 // We found an overloaded operator(). Build a CXXOperatorCallExpr
9642 // that calls this method, using Object for the implicit object
9643 // parameter and passing along the remaining arguments.
9644 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +00009645 const FunctionProtoType *Proto =
9646 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009647
9648 unsigned NumArgsInProto = Proto->getNumArgs();
9649 unsigned NumArgsToCheck = NumArgs;
9650
9651 // Build the full argument list for the method call (the
9652 // implicit object parameter is placed at the beginning of the
9653 // list).
9654 Expr **MethodArgs;
9655 if (NumArgs < NumArgsInProto) {
9656 NumArgsToCheck = NumArgsInProto;
9657 MethodArgs = new Expr*[NumArgsInProto + 1];
9658 } else {
9659 MethodArgs = new Expr*[NumArgs + 1];
9660 }
John Wiegley429bb272011-04-08 18:41:53 +00009661 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009662 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9663 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00009664
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009665 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
9666 HadMultipleCandidates);
John Wiegley429bb272011-04-08 18:41:53 +00009667 if (NewFn.isInvalid())
9668 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009669
9670 // Once we've built TheCall, all of the expressions are properly
9671 // owned.
John McCallf89e55a2010-11-18 06:31:45 +00009672 QualType ResultTy = Method->getResultType();
9673 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9674 ResultTy = ResultTy.getNonLValueExprType(Context);
9675
John McCall9ae2f072010-08-23 23:25:46 +00009676 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009677 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCall9ae2f072010-08-23 23:25:46 +00009678 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +00009679 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009680 delete [] MethodArgs;
9681
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009682 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +00009683 Method))
9684 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009685
Douglas Gregor518fda12009-01-13 05:10:00 +00009686 // We may have default arguments. If so, we need to allocate more
9687 // slots in the call for them.
9688 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00009689 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00009690 else if (NumArgs > NumArgsInProto)
9691 NumArgsToCheck = NumArgsInProto;
9692
Chris Lattner312531a2009-04-12 08:11:20 +00009693 bool IsError = false;
9694
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009695 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +00009696 ExprResult ObjRes =
9697 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9698 Best->FoundDecl, Method);
9699 if (ObjRes.isInvalid())
9700 IsError = true;
9701 else
9702 Object = move(ObjRes);
9703 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +00009704
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009705 // Check the argument types.
9706 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009707 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00009708 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009709 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00009710
Douglas Gregor518fda12009-01-13 05:10:00 +00009711 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00009712
John McCall60d7b3a2010-08-24 06:29:42 +00009713 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +00009714 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009715 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +00009716 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +00009717 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009718
Anders Carlsson3faa4862010-01-29 18:43:53 +00009719 IsError |= InputInit.isInvalid();
9720 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00009721 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00009722 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +00009723 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9724 if (DefArg.isInvalid()) {
9725 IsError = true;
9726 break;
9727 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009728
Douglas Gregord47c47d2009-11-09 19:27:57 +00009729 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00009730 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009731
9732 TheCall->setArg(i + 1, Arg);
9733 }
9734
9735 // If this is a variadic call, handle args passed through "...".
9736 if (Proto->isVariadic()) {
9737 // Promote the arguments (C99 6.5.2.2p7).
9738 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +00009739 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9740 IsError |= Arg.isInvalid();
9741 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009742 }
9743 }
9744
Chris Lattner312531a2009-04-12 08:11:20 +00009745 if (IsError) return true;
9746
John McCall9ae2f072010-08-23 23:25:46 +00009747 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00009748 return true;
9749
John McCall182f7092010-08-24 06:09:16 +00009750 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009751}
9752
Douglas Gregor8ba10742008-11-20 16:27:02 +00009753/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00009754/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00009755/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +00009756ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009757Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +00009758 assert(Base->getType()->isRecordType() &&
9759 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00009760
John Wiegley429bb272011-04-08 18:41:53 +00009761 if (Base->getObjectKind() == OK_ObjCProperty) {
9762 ExprResult Result = ConvertPropertyForRValue(Base);
9763 if (Result.isInvalid())
9764 return ExprError();
9765 Base = Result.take();
9766 }
John McCall0e800c92010-12-04 08:14:53 +00009767
John McCall5769d612010-02-08 23:07:23 +00009768 SourceLocation Loc = Base->getExprLoc();
9769
Douglas Gregor8ba10742008-11-20 16:27:02 +00009770 // C++ [over.ref]p1:
9771 //
9772 // [...] An expression x->m is interpreted as (x.operator->())->m
9773 // for a class object x of type T if T::operator->() exists and if
9774 // the operator is selected as the best match function by the
9775 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +00009776 DeclarationName OpName =
9777 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00009778 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00009779 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009780
John McCall5769d612010-02-08 23:07:23 +00009781 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00009782 PDiag(diag::err_typecheck_incomplete_tag)
9783 << Base->getSourceRange()))
9784 return ExprError();
9785
John McCalla24dc2e2009-11-17 02:14:36 +00009786 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9787 LookupQualifiedName(R, BaseRecord->getDecl());
9788 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00009789
9790 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00009791 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009792 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9793 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00009794 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00009795
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009796 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9797
Douglas Gregor8ba10742008-11-20 16:27:02 +00009798 // Perform overload resolution.
9799 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009800 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00009801 case OR_Success:
9802 // Overload resolution succeeded; we'll build the call below.
9803 break;
9804
9805 case OR_No_Viable_Function:
9806 if (CandidateSet.empty())
9807 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009808 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00009809 else
9810 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009811 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009812 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009813 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00009814
9815 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00009816 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9817 << "->" << Base->getType() << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009818 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009819 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009820
9821 case OR_Deleted:
9822 Diag(OpLoc, diag::err_ovl_deleted_oper)
9823 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009824 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009825 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009826 << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009827 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009828 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00009829 }
9830
Chandler Carruth25ca4212011-02-25 19:41:05 +00009831 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +00009832 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009833 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00009834
Douglas Gregor8ba10742008-11-20 16:27:02 +00009835 // Convert the object parameter.
9836 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +00009837 ExprResult BaseResult =
9838 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9839 Best->FoundDecl, Method);
9840 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009841 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009842 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00009843
Douglas Gregor8ba10742008-11-20 16:27:02 +00009844 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009845 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
9846 HadMultipleCandidates);
John Wiegley429bb272011-04-08 18:41:53 +00009847 if (FnExpr.isInvalid())
9848 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009849
John McCallf89e55a2010-11-18 06:31:45 +00009850 QualType ResultTy = Method->getResultType();
9851 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9852 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +00009853 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009854 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009855 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00009856
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009857 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00009858 Method))
9859 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +00009860
9861 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00009862}
9863
Douglas Gregor904eed32008-11-10 20:40:00 +00009864/// FixOverloadedFunctionReference - E is an expression that refers to
9865/// a C++ overloaded function (possibly with some parentheses and
9866/// perhaps a '&' around it). We have resolved the overloaded function
9867/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00009868/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00009869Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00009870 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00009871 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00009872 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9873 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00009874 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00009875 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009876
Douglas Gregor699ee522009-11-20 19:42:02 +00009877 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009878 }
9879
Douglas Gregor699ee522009-11-20 19:42:02 +00009880 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00009881 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9882 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009883 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00009884 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00009885 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +00009886 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +00009887 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00009888 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009889
9890 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +00009891 ICE->getCastKind(),
9892 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00009893 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009894 }
9895
Douglas Gregor699ee522009-11-20 19:42:02 +00009896 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00009897 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00009898 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00009899 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9900 if (Method->isStatic()) {
9901 // Do nothing: static member functions aren't any different
9902 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00009903 } else {
John McCallf7a1a742009-11-24 19:00:30 +00009904 // Fix the sub expression, which really has to be an
9905 // UnresolvedLookupExpr holding an overloaded member function
9906 // or template.
John McCall6bb80172010-03-30 21:47:33 +00009907 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9908 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00009909 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00009910 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +00009911
John McCallba135432009-11-21 08:51:07 +00009912 assert(isa<DeclRefExpr>(SubExpr)
9913 && "fixed to something other than a decl ref");
9914 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
9915 && "fixed to a member ref with no nested name qualifier");
9916
9917 // We have taken the address of a pointer to member
9918 // function. Perform the computation here so that we get the
9919 // appropriate pointer to member type.
9920 QualType ClassType
9921 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
9922 QualType MemPtrType
9923 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9924
John McCallf89e55a2010-11-18 06:31:45 +00009925 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9926 VK_RValue, OK_Ordinary,
9927 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00009928 }
9929 }
John McCall6bb80172010-03-30 21:47:33 +00009930 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9931 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00009932 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00009933 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009934
John McCall2de56d12010-08-25 11:45:40 +00009935 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +00009936 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00009937 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +00009938 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009939 }
John McCallba135432009-11-21 08:51:07 +00009940
9941 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00009942 // FIXME: avoid copy.
9943 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00009944 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00009945 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9946 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00009947 }
9948
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009949 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
9950 ULE->getQualifierLoc(),
9951 Fn,
9952 ULE->getNameLoc(),
9953 Fn->getType(),
9954 VK_LValue,
9955 Found.getDecl(),
9956 TemplateArgs);
9957 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
9958 return DRE;
John McCallba135432009-11-21 08:51:07 +00009959 }
9960
John McCall129e2df2009-11-30 22:42:35 +00009961 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00009962 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00009963 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9964 if (MemExpr->hasExplicitTemplateArgs()) {
9965 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9966 TemplateArgs = &TemplateArgsBuffer;
9967 }
John McCalld5532b62009-11-23 01:53:49 +00009968
John McCallaa81e162009-12-01 22:10:20 +00009969 Expr *Base;
9970
John McCallf89e55a2010-11-18 06:31:45 +00009971 // If we're filling in a static method where we used to have an
9972 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +00009973 if (MemExpr->isImplicitAccess()) {
9974 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009975 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
9976 MemExpr->getQualifierLoc(),
9977 Fn,
9978 MemExpr->getMemberLoc(),
9979 Fn->getType(),
9980 VK_LValue,
9981 Found.getDecl(),
9982 TemplateArgs);
9983 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
9984 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +00009985 } else {
9986 SourceLocation Loc = MemExpr->getMemberLoc();
9987 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +00009988 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregor828a1972010-01-07 23:12:05 +00009989 Base = new (Context) CXXThisExpr(Loc,
9990 MemExpr->getBaseType(),
9991 /*isImplicit=*/true);
9992 }
John McCallaa81e162009-12-01 22:10:20 +00009993 } else
John McCall3fa5cae2010-10-26 07:05:15 +00009994 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +00009995
John McCallf5307512011-04-27 00:36:17 +00009996 ExprValueKind valueKind;
9997 QualType type;
9998 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9999 valueKind = VK_LValue;
10000 type = Fn->getType();
10001 } else {
10002 valueKind = VK_RValue;
10003 type = Context.BoundMemberTy;
10004 }
10005
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010006 MemberExpr *ME = MemberExpr::Create(Context, Base,
10007 MemExpr->isArrow(),
10008 MemExpr->getQualifierLoc(),
10009 Fn,
10010 Found,
10011 MemExpr->getMemberNameInfo(),
10012 TemplateArgs,
10013 type, valueKind, OK_Ordinary);
10014 ME->setHadMultipleCandidates(true);
10015 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000010016 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010017
John McCall3fa5cae2010-10-26 07:05:15 +000010018 llvm_unreachable("Invalid reference to overloaded function");
10019 return E;
Douglas Gregor904eed32008-11-10 20:40:00 +000010020}
10021
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010022ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000010023 DeclAccessPair Found,
10024 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000010025 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000010026}
10027
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000010028} // end namespace clang