blob: bc48f08a34085d9c463a94bcb2e87b1201955865 [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
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000261/// Skip any implicit casts which could be either part of a narrowing conversion
262/// or after one in an implicit conversion.
263static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
264 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
265 switch (ICE->getCastKind()) {
266 case CK_NoOp:
267 case CK_IntegralCast:
268 case CK_IntegralToBoolean:
269 case CK_IntegralToFloating:
270 case CK_FloatingToIntegral:
271 case CK_FloatingToBoolean:
272 case CK_FloatingCast:
273 Converted = ICE->getSubExpr();
274 continue;
275
276 default:
277 return Converted;
278 }
279 }
280
281 return Converted;
282}
283
284/// Check if this standard conversion sequence represents a narrowing
285/// conversion, according to C++11 [dcl.init.list]p7.
286///
287/// \param Ctx The AST context.
288/// \param Converted The result of applying this standard conversion sequence.
289/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
290/// value of the expression prior to the narrowing conversion.
291NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000292StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293 const Expr *Converted,
294 APValue &ConstantValue) const {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000295 assert(Ctx.getLangOptions().CPlusPlus && "narrowing check outside C++");
296
297 // C++11 [dcl.init.list]p7:
298 // A narrowing conversion is an implicit conversion ...
299 QualType FromType = getToType(0);
300 QualType ToType = getToType(1);
301 switch (Second) {
302 // -- from a floating-point type to an integer type, or
303 //
304 // -- from an integer type or unscoped enumeration type to a floating-point
305 // type, except where the source is a constant expression and the actual
306 // value after conversion will fit into the target type and will produce
307 // the original value when converted back to the original type, or
308 case ICK_Floating_Integral:
309 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
310 return NK_Type_Narrowing;
311 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
312 llvm::APSInt IntConstantValue;
313 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
314 if (Initializer &&
315 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
316 // Convert the integer to the floating type.
317 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
318 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
319 llvm::APFloat::rmNearestTiesToEven);
320 // And back.
321 llvm::APSInt ConvertedValue = IntConstantValue;
322 bool ignored;
323 Result.convertToInteger(ConvertedValue,
324 llvm::APFloat::rmTowardZero, &ignored);
325 // If the resulting value is different, this was a narrowing conversion.
326 if (IntConstantValue != ConvertedValue) {
327 ConstantValue = APValue(IntConstantValue);
328 return NK_Constant_Narrowing;
329 }
330 } else {
331 // Variables are always narrowings.
332 return NK_Variable_Narrowing;
333 }
334 }
335 return NK_Not_Narrowing;
336
337 // -- from long double to double or float, or from double to float, except
338 // where the source is a constant expression and the actual value after
339 // conversion is within the range of values that can be represented (even
340 // if it cannot be represented exactly), or
341 case ICK_Floating_Conversion:
342 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
343 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
344 // FromType is larger than ToType.
345 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
346 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
347 // Constant!
348 assert(ConstantValue.isFloat());
349 llvm::APFloat FloatVal = ConstantValue.getFloat();
350 // Convert the source value into the target type.
351 bool ignored;
352 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
353 Ctx.getFloatTypeSemantics(ToType),
354 llvm::APFloat::rmNearestTiesToEven, &ignored);
355 // If there was no overflow, the source value is within the range of
356 // values that can be represented.
357 if (ConvertStatus & llvm::APFloat::opOverflow)
358 return NK_Constant_Narrowing;
359 } else {
360 return NK_Variable_Narrowing;
361 }
362 }
363 return NK_Not_Narrowing;
364
365 // -- from an integer type or unscoped enumeration type to an integer type
366 // that cannot represent all the values of the original type, except where
367 // the source is a constant expression and the actual value after
368 // conversion will fit into the target type and will produce the original
369 // value when converted back to the original type.
370 case ICK_Boolean_Conversion: // Bools are integers too.
371 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
372 // Boolean conversions can be from pointers and pointers to members
373 // [conv.bool], and those aren't considered narrowing conversions.
374 return NK_Not_Narrowing;
375 } // Otherwise, fall through to the integral case.
376 case ICK_Integral_Conversion: {
377 assert(FromType->isIntegralOrUnscopedEnumerationType());
378 assert(ToType->isIntegralOrUnscopedEnumerationType());
379 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
380 const unsigned FromWidth = Ctx.getIntWidth(FromType);
381 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
382 const unsigned ToWidth = Ctx.getIntWidth(ToType);
383
384 if (FromWidth > ToWidth ||
385 (FromWidth == ToWidth && FromSigned != ToSigned)) {
386 // Not all values of FromType can be represented in ToType.
387 llvm::APSInt InitializerValue;
388 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
389 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
390 ConstantValue = APValue(InitializerValue);
391
392 // Add a bit to the InitializerValue so we don't have to worry about
393 // signed vs. unsigned comparisons.
394 InitializerValue = InitializerValue.extend(
395 InitializerValue.getBitWidth() + 1);
396 // Convert the initializer to and from the target width and signed-ness.
397 llvm::APSInt ConvertedValue = InitializerValue;
398 ConvertedValue = ConvertedValue.trunc(ToWidth);
399 ConvertedValue.setIsSigned(ToSigned);
400 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
401 ConvertedValue.setIsSigned(InitializerValue.isSigned());
402 // If the result is different, this was a narrowing conversion.
403 if (ConvertedValue != InitializerValue)
404 return NK_Constant_Narrowing;
405 } else {
406 // Variables are always narrowings.
407 return NK_Variable_Narrowing;
408 }
409 }
410 return NK_Not_Narrowing;
411 }
412
413 default:
414 // Other kinds of conversions are not narrowings.
415 return NK_Not_Narrowing;
416 }
417}
418
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000419/// DebugPrint - Print this standard conversion sequence to standard
420/// error. Useful for debugging overloading issues.
421void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000422 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000423 bool PrintedSomething = false;
424 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000425 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000426 PrintedSomething = true;
427 }
428
429 if (Second != ICK_Identity) {
430 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000431 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000432 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000433 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000434
435 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000436 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000437 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000438 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000439 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000440 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000441 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000442 PrintedSomething = true;
443 }
444
445 if (Third != ICK_Identity) {
446 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000447 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000448 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000449 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000450 PrintedSomething = true;
451 }
452
453 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000454 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000455 }
456}
457
458/// DebugPrint - Print this user-defined conversion sequence to standard
459/// error. Useful for debugging overloading issues.
460void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000461 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000462 if (Before.First || Before.Second || Before.Third) {
463 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000464 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000465 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000466 if (ConversionFunction)
467 OS << '\'' << *ConversionFunction << '\'';
468 else
469 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000470 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000471 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000472 After.DebugPrint();
473 }
474}
475
476/// DebugPrint - Print this implicit conversion sequence to standard
477/// error. Useful for debugging overloading issues.
478void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000479 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000480 switch (ConversionKind) {
481 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000482 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000483 Standard.DebugPrint();
484 break;
485 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000486 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000487 UserDefined.DebugPrint();
488 break;
489 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000490 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491 break;
John McCall1d318332010-01-12 00:44:57 +0000492 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000493 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000494 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000495 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000496 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000497 break;
498 }
499
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000500 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000501}
502
John McCall1d318332010-01-12 00:44:57 +0000503void AmbiguousConversionSequence::construct() {
504 new (&conversions()) ConversionSet();
505}
506
507void AmbiguousConversionSequence::destruct() {
508 conversions().~ConversionSet();
509}
510
511void
512AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
513 FromTypePtr = O.FromTypePtr;
514 ToTypePtr = O.ToTypePtr;
515 new (&conversions()) ConversionSet(O.conversions());
516}
517
Douglas Gregora9333192010-05-08 17:41:32 +0000518namespace {
519 // Structure used by OverloadCandidate::DeductionFailureInfo to store
520 // template parameter and template argument information.
521 struct DFIParamWithArguments {
522 TemplateParameter Param;
523 TemplateArgument FirstArg;
524 TemplateArgument SecondArg;
525 };
526}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000527
Douglas Gregora9333192010-05-08 17:41:32 +0000528/// \brief Convert from Sema's representation of template deduction information
529/// to the form used in overload-candidate information.
530OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000531static MakeDeductionFailureInfo(ASTContext &Context,
532 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000533 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000534 OverloadCandidate::DeductionFailureInfo Result;
535 Result.Result = static_cast<unsigned>(TDK);
536 Result.Data = 0;
537 switch (TDK) {
538 case Sema::TDK_Success:
539 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000540 case Sema::TDK_TooManyArguments:
541 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000542 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000543
Douglas Gregora9333192010-05-08 17:41:32 +0000544 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000545 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000546 Result.Data = Info.Param.getOpaqueValue();
547 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000548
Douglas Gregora9333192010-05-08 17:41:32 +0000549 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000550 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000551 // FIXME: Should allocate from normal heap so that we can free this later.
552 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000553 Saved->Param = Info.Param;
554 Saved->FirstArg = Info.FirstArg;
555 Saved->SecondArg = Info.SecondArg;
556 Result.Data = Saved;
557 break;
558 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000559
Douglas Gregora9333192010-05-08 17:41:32 +0000560 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000561 Result.Data = Info.take();
562 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000563
Douglas Gregora9333192010-05-08 17:41:32 +0000564 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000565 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000566 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000567 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000568
Douglas Gregora9333192010-05-08 17:41:32 +0000569 return Result;
570}
John McCall1d318332010-01-12 00:44:57 +0000571
Douglas Gregora9333192010-05-08 17:41:32 +0000572void OverloadCandidate::DeductionFailureInfo::Destroy() {
573 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
574 case Sema::TDK_Success:
575 case Sema::TDK_InstantiationDepth:
576 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000577 case Sema::TDK_TooManyArguments:
578 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000579 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000580 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000581
Douglas Gregora9333192010-05-08 17:41:32 +0000582 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000583 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000584 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000585 Data = 0;
586 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000587
588 case Sema::TDK_SubstitutionFailure:
589 // FIXME: Destroy the template arugment list?
590 Data = 0;
591 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000592
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000593 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000594 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000595 case Sema::TDK_FailedOverloadResolution:
596 break;
597 }
598}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000599
600TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000601OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
602 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
603 case Sema::TDK_Success:
604 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000605 case Sema::TDK_TooManyArguments:
606 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000607 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000608 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000609
Douglas Gregora9333192010-05-08 17:41:32 +0000610 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000611 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000612 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000613
614 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000615 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000616 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000617
Douglas Gregora9333192010-05-08 17:41:32 +0000618 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000619 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000620 case Sema::TDK_FailedOverloadResolution:
621 break;
622 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000623
Douglas Gregora9333192010-05-08 17:41:32 +0000624 return TemplateParameter();
625}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000626
Douglas Gregorec20f462010-05-08 20:07:26 +0000627TemplateArgumentList *
628OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
630 case Sema::TDK_Success:
631 case Sema::TDK_InstantiationDepth:
632 case Sema::TDK_TooManyArguments:
633 case Sema::TDK_TooFewArguments:
634 case Sema::TDK_Incomplete:
635 case Sema::TDK_InvalidExplicitArguments:
636 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000637 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000638 return 0;
639
640 case Sema::TDK_SubstitutionFailure:
641 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000642
Douglas Gregorec20f462010-05-08 20:07:26 +0000643 // Unhandled
644 case Sema::TDK_NonDeducedMismatch:
645 case Sema::TDK_FailedOverloadResolution:
646 break;
647 }
648
649 return 0;
650}
651
Douglas Gregora9333192010-05-08 17:41:32 +0000652const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
653 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
654 case Sema::TDK_Success:
655 case Sema::TDK_InstantiationDepth:
656 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000657 case Sema::TDK_TooManyArguments:
658 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000659 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000660 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000661 return 0;
662
Douglas Gregora9333192010-05-08 17:41:32 +0000663 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000664 case Sema::TDK_Underqualified:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000665 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000666
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000667 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000668 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000669 case Sema::TDK_FailedOverloadResolution:
670 break;
671 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000672
Douglas Gregora9333192010-05-08 17:41:32 +0000673 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000674}
Douglas Gregora9333192010-05-08 17:41:32 +0000675
676const TemplateArgument *
677OverloadCandidate::DeductionFailureInfo::getSecondArg() {
678 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
679 case Sema::TDK_Success:
680 case Sema::TDK_InstantiationDepth:
681 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000682 case Sema::TDK_TooManyArguments:
683 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000684 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000685 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000686 return 0;
687
Douglas Gregora9333192010-05-08 17:41:32 +0000688 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000689 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000690 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
691
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000692 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000693 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000694 case Sema::TDK_FailedOverloadResolution:
695 break;
696 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000697
Douglas Gregora9333192010-05-08 17:41:32 +0000698 return 0;
699}
700
701void OverloadCandidateSet::clear() {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000702 for (iterator i = begin(), e = end(); i != e; ++i)
703 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
704 i->Conversions[ii].~ImplicitConversionSequence();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000705 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000706 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000707 Functions.clear();
708}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000709
John McCall5acb0c92011-10-17 18:40:02 +0000710namespace {
711 class UnbridgedCastsSet {
712 struct Entry {
713 Expr **Addr;
714 Expr *Saved;
715 };
716 SmallVector<Entry, 2> Entries;
717
718 public:
719 void save(Sema &S, Expr *&E) {
720 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
721 Entry entry = { &E, E };
722 Entries.push_back(entry);
723 E = S.stripARCUnbridgedCast(E);
724 }
725
726 void restore() {
727 for (SmallVectorImpl<Entry>::iterator
728 i = Entries.begin(), e = Entries.end(); i != e; ++i)
729 *i->Addr = i->Saved;
730 }
731 };
732}
733
734/// checkPlaceholderForOverload - Do any interesting placeholder-like
735/// preprocessing on the given expression.
736///
737/// \param unbridgedCasts a collection to which to add unbridged casts;
738/// without this, they will be immediately diagnosed as errors
739///
740/// Return true on unrecoverable error.
741static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
742 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000743 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
744 // We can't handle overloaded expressions here because overload
745 // resolution might reasonably tweak them.
746 if (placeholder->getKind() == BuiltinType::Overload) return false;
747
748 // If the context potentially accepts unbridged ARC casts, strip
749 // the unbridged cast and add it to the collection for later restoration.
750 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
751 unbridgedCasts) {
752 unbridgedCasts->save(S, E);
753 return false;
754 }
755
756 // Go ahead and check everything else.
757 ExprResult result = S.CheckPlaceholderExpr(E);
758 if (result.isInvalid())
759 return true;
760
761 E = result.take();
762 return false;
763 }
764
765 // Nothing to do.
766 return false;
767}
768
769/// checkArgPlaceholdersForOverload - Check a set of call operands for
770/// placeholders.
771static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
772 unsigned numArgs,
773 UnbridgedCastsSet &unbridged) {
774 for (unsigned i = 0; i != numArgs; ++i)
775 if (checkPlaceholderForOverload(S, args[i], &unbridged))
776 return true;
777
778 return false;
779}
780
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000781// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000782// overload of the declarations in Old. This routine returns false if
783// New and Old cannot be overloaded, e.g., if New has the same
784// signature as some function in Old (C++ 1.3.10) or if the Old
785// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000786// it does return false, MatchedDecl will point to the decl that New
787// cannot be overloaded with. This decl may be a UsingShadowDecl on
788// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000789//
790// Example: Given the following input:
791//
792// void f(int, float); // #1
793// void f(int, int); // #2
794// int f(int, int); // #3
795//
796// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000797// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000798//
John McCall51fa86f2009-12-02 08:47:38 +0000799// When we process #2, Old contains only the FunctionDecl for #1. By
800// comparing the parameter types, we see that #1 and #2 are overloaded
801// (since they have different signatures), so this routine returns
802// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000803//
John McCall51fa86f2009-12-02 08:47:38 +0000804// When we process #3, Old is an overload set containing #1 and #2. We
805// compare the signatures of #3 to #1 (they're overloaded, so we do
806// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
807// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000808// signature), IsOverload returns false and MatchedDecl will be set to
809// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000810//
811// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
812// into a class by a using declaration. The rules for whether to hide
813// shadow declarations ignore some properties which otherwise figure
814// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000815Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000816Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
817 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000818 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000819 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000820 NamedDecl *OldD = *I;
821
822 bool OldIsUsingDecl = false;
823 if (isa<UsingShadowDecl>(OldD)) {
824 OldIsUsingDecl = true;
825
826 // We can always introduce two using declarations into the same
827 // context, even if they have identical signatures.
828 if (NewIsUsingDecl) continue;
829
830 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
831 }
832
833 // If either declaration was introduced by a using declaration,
834 // we'll need to use slightly different rules for matching.
835 // Essentially, these rules are the normal rules, except that
836 // function templates hide function templates with different
837 // return types or template parameter lists.
838 bool UseMemberUsingDeclRules =
839 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
840
John McCall51fa86f2009-12-02 08:47:38 +0000841 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000842 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
843 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
844 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
845 continue;
846 }
847
John McCall871b2e72009-12-09 03:35:25 +0000848 Match = *I;
849 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000850 }
John McCall51fa86f2009-12-02 08:47:38 +0000851 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000852 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
853 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
854 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
855 continue;
856 }
857
John McCall871b2e72009-12-09 03:35:25 +0000858 Match = *I;
859 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000860 }
John McCalld7945c62010-11-10 03:01:53 +0000861 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000862 // We can overload with these, which can show up when doing
863 // redeclaration checks for UsingDecls.
864 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000865 } else if (isa<TagDecl>(OldD)) {
866 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000867 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
868 // Optimistically assume that an unresolved using decl will
869 // overload; if it doesn't, we'll have to diagnose during
870 // template instantiation.
871 } else {
John McCall68263142009-11-18 22:49:29 +0000872 // (C++ 13p1):
873 // Only function declarations can be overloaded; object and type
874 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000875 Match = *I;
876 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000877 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000878 }
John McCall68263142009-11-18 22:49:29 +0000879
John McCall871b2e72009-12-09 03:35:25 +0000880 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000881}
882
John McCallad00b772010-06-16 08:42:20 +0000883bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
884 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000885 // If both of the functions are extern "C", then they are not
886 // overloads.
887 if (Old->isExternC() && New->isExternC())
888 return false;
889
John McCall68263142009-11-18 22:49:29 +0000890 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
891 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
892
893 // C++ [temp.fct]p2:
894 // A function template can be overloaded with other function templates
895 // and with normal (non-template) functions.
896 if ((OldTemplate == 0) != (NewTemplate == 0))
897 return true;
898
899 // Is the function New an overload of the function Old?
900 QualType OldQType = Context.getCanonicalType(Old->getType());
901 QualType NewQType = Context.getCanonicalType(New->getType());
902
903 // Compare the signatures (C++ 1.3.10) of the two functions to
904 // determine whether they are overloads. If we find any mismatch
905 // in the signature, they are overloads.
906
907 // If either of these functions is a K&R-style function (no
908 // prototype), then we consider them to have matching signatures.
909 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
910 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
911 return false;
912
John McCallf4c73712011-01-19 06:33:43 +0000913 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
914 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000915
916 // The signature of a function includes the types of its
917 // parameters (C++ 1.3.10), which includes the presence or absence
918 // of the ellipsis; see C++ DR 357).
919 if (OldQType != NewQType &&
920 (OldType->getNumArgs() != NewType->getNumArgs() ||
921 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000922 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000923 return true;
924
925 // C++ [temp.over.link]p4:
926 // The signature of a function template consists of its function
927 // signature, its return type and its template parameter list. The names
928 // of the template parameters are significant only for establishing the
929 // relationship between the template parameters and the rest of the
930 // signature.
931 //
932 // We check the return type and template parameter lists for function
933 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000934 //
935 // However, we don't consider either of these when deciding whether
936 // a member introduced by a shadow declaration is hidden.
937 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000938 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
939 OldTemplate->getTemplateParameters(),
940 false, TPL_TemplateMatch) ||
941 OldType->getResultType() != NewType->getResultType()))
942 return true;
943
944 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000945 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +0000946 //
947 // As part of this, also check whether one of the member functions
948 // is static, in which case they are not overloads (C++
949 // 13.1p2). While not part of the definition of the signature,
950 // this check is important to determine whether these functions
951 // can be overloaded.
952 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
953 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
954 if (OldMethod && NewMethod &&
955 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000956 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-01-26 21:20:37 +0000957 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
958 if (!UseUsingDeclRules &&
959 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
960 (OldMethod->getRefQualifier() == RQ_None ||
961 NewMethod->getRefQualifier() == RQ_None)) {
962 // C++0x [over.load]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000963 // - Member function declarations with the same name and the same
964 // parameter-type-list as well as member function template
965 // declarations with the same name, the same parameter-type-list, and
966 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorb145ee62011-01-26 21:20:37 +0000967 // them, but not all, have a ref-qualifier (8.3.5).
968 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
969 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
970 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
971 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000972
John McCall68263142009-11-18 22:49:29 +0000973 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +0000974 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000975
John McCall68263142009-11-18 22:49:29 +0000976 // The signatures match; this is not an overload.
977 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000978}
979
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +0000980/// \brief Checks availability of the function depending on the current
981/// function context. Inside an unavailable function, unavailability is ignored.
982///
983/// \returns true if \arg FD is unavailable and current context is inside
984/// an available function, false otherwise.
985bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
986 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
987}
988
Sebastian Redlcf15cef2011-12-22 18:58:38 +0000989/// \brief Tries a user-defined conversion from From to ToType.
990///
991/// Produces an implicit conversion sequence for when a standard conversion
992/// is not an option. See TryImplicitConversion for more information.
993static ImplicitConversionSequence
994TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
995 bool SuppressUserConversions,
996 bool AllowExplicit,
997 bool InOverloadResolution,
998 bool CStyle,
999 bool AllowObjCWritebackConversion) {
1000 ImplicitConversionSequence ICS;
1001
1002 if (SuppressUserConversions) {
1003 // We're not in the case above, so there is no conversion that
1004 // we can perform.
1005 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1006 return ICS;
1007 }
1008
1009 // Attempt user-defined conversion.
1010 OverloadCandidateSet Conversions(From->getExprLoc());
1011 OverloadingResult UserDefResult
1012 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1013 AllowExplicit);
1014
1015 if (UserDefResult == OR_Success) {
1016 ICS.setUserDefined();
1017 // C++ [over.ics.user]p4:
1018 // A conversion of an expression of class type to the same class
1019 // type is given Exact Match rank, and a conversion of an
1020 // expression of class type to a base class of that type is
1021 // given Conversion rank, in spite of the fact that a copy
1022 // constructor (i.e., a user-defined conversion function) is
1023 // called for those cases.
1024 if (CXXConstructorDecl *Constructor
1025 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1026 QualType FromCanon
1027 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1028 QualType ToCanon
1029 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1030 if (Constructor->isCopyConstructor() &&
1031 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1032 // Turn this into a "standard" conversion sequence, so that it
1033 // gets ranked with standard conversion sequences.
1034 ICS.setStandard();
1035 ICS.Standard.setAsIdentityConversion();
1036 ICS.Standard.setFromType(From->getType());
1037 ICS.Standard.setAllToTypes(ToType);
1038 ICS.Standard.CopyConstructor = Constructor;
1039 if (ToCanon != FromCanon)
1040 ICS.Standard.Second = ICK_Derived_To_Base;
1041 }
1042 }
1043
1044 // C++ [over.best.ics]p4:
1045 // However, when considering the argument of a user-defined
1046 // conversion function that is a candidate by 13.3.1.3 when
1047 // invoked for the copying of the temporary in the second step
1048 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1049 // 13.3.1.6 in all cases, only standard conversion sequences and
1050 // ellipsis conversion sequences are allowed.
1051 if (SuppressUserConversions && ICS.isUserDefined()) {
1052 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1053 }
1054 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1055 ICS.setAmbiguous();
1056 ICS.Ambiguous.setFromType(From->getType());
1057 ICS.Ambiguous.setToType(ToType);
1058 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1059 Cand != Conversions.end(); ++Cand)
1060 if (Cand->Viable)
1061 ICS.Ambiguous.addConversion(Cand->Function);
1062 } else {
1063 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1064 }
1065
1066 return ICS;
1067}
1068
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001069/// TryImplicitConversion - Attempt to perform an implicit conversion
1070/// from the given expression (Expr) to the given type (ToType). This
1071/// function returns an implicit conversion sequence that can be used
1072/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001073///
1074/// void f(float f);
1075/// void g(int i) { f(i); }
1076///
1077/// this routine would produce an implicit conversion sequence to
1078/// describe the initialization of f from i, which will be a standard
1079/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1080/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1081//
1082/// Note that this routine only determines how the conversion can be
1083/// performed; it does not actually perform the conversion. As such,
1084/// it will not produce any diagnostics if no conversion is available,
1085/// but will instead return an implicit conversion sequence of kind
1086/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001087///
1088/// If @p SuppressUserConversions, then user-defined conversions are
1089/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001090/// If @p AllowExplicit, then explicit user-defined conversions are
1091/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001092///
1093/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1094/// writeback conversion, which allows __autoreleasing id* parameters to
1095/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001096static ImplicitConversionSequence
1097TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1098 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001099 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001100 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001101 bool CStyle,
1102 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001103 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001104 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001105 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001106 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001107 return ICS;
1108 }
1109
John McCall120d63c2010-08-24 20:38:10 +00001110 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001111 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001112 return ICS;
1113 }
1114
Douglas Gregor604eb652010-08-11 02:15:33 +00001115 // C++ [over.ics.user]p4:
1116 // A conversion of an expression of class type to the same class
1117 // type is given Exact Match rank, and a conversion of an
1118 // expression of class type to a base class of that type is
1119 // given Conversion rank, in spite of the fact that a copy/move
1120 // constructor (i.e., a user-defined conversion function) is
1121 // called for those cases.
1122 QualType FromType = From->getType();
1123 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001124 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1125 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001126 ICS.setStandard();
1127 ICS.Standard.setAsIdentityConversion();
1128 ICS.Standard.setFromType(FromType);
1129 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001130
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001131 // We don't actually check at this point whether there is a valid
1132 // copy/move constructor, since overloading just assumes that it
1133 // exists. When we actually perform initialization, we'll find the
1134 // appropriate constructor to copy the returned object, if needed.
1135 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001136
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001137 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001138 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001139 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001140
Douglas Gregor604eb652010-08-11 02:15:33 +00001141 return ICS;
1142 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001143
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001144 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1145 AllowExplicit, InOverloadResolution, CStyle,
1146 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001147}
1148
John McCallf85e1932011-06-15 23:02:42 +00001149ImplicitConversionSequence
1150Sema::TryImplicitConversion(Expr *From, QualType ToType,
1151 bool SuppressUserConversions,
1152 bool AllowExplicit,
1153 bool InOverloadResolution,
1154 bool CStyle,
1155 bool AllowObjCWritebackConversion) {
1156 return clang::TryImplicitConversion(*this, From, ToType,
1157 SuppressUserConversions, AllowExplicit,
1158 InOverloadResolution, CStyle,
1159 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001160}
1161
Douglas Gregor575c63a2010-04-16 22:27:05 +00001162/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001163/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001164/// converted expression. Flavor is the kind of conversion we're
1165/// performing, used in the error message. If @p AllowExplicit,
1166/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001167ExprResult
1168Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001169 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001170 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001171 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001172}
1173
John Wiegley429bb272011-04-08 18:41:53 +00001174ExprResult
1175Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001176 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001177 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001178 if (checkPlaceholderForOverload(*this, From))
1179 return ExprError();
1180
John McCallf85e1932011-06-15 23:02:42 +00001181 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1182 bool AllowObjCWritebackConversion
1183 = getLangOptions().ObjCAutoRefCount &&
1184 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001185
John McCall120d63c2010-08-24 20:38:10 +00001186 ICS = clang::TryImplicitConversion(*this, From, ToType,
1187 /*SuppressUserConversions=*/false,
1188 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001189 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001190 /*CStyle=*/false,
1191 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001192 return PerformImplicitConversion(From, ToType, ICS, Action);
1193}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001194
1195/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001196/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001197bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1198 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001199 if (Context.hasSameUnqualifiedType(FromType, ToType))
1200 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001201
John McCall00ccbef2010-12-21 00:44:39 +00001202 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1203 // where F adds one of the following at most once:
1204 // - a pointer
1205 // - a member pointer
1206 // - a block pointer
1207 CanQualType CanTo = Context.getCanonicalType(ToType);
1208 CanQualType CanFrom = Context.getCanonicalType(FromType);
1209 Type::TypeClass TyClass = CanTo->getTypeClass();
1210 if (TyClass != CanFrom->getTypeClass()) return false;
1211 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1212 if (TyClass == Type::Pointer) {
1213 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1214 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1215 } else if (TyClass == Type::BlockPointer) {
1216 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1217 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1218 } else if (TyClass == Type::MemberPointer) {
1219 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1220 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1221 } else {
1222 return false;
1223 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001224
John McCall00ccbef2010-12-21 00:44:39 +00001225 TyClass = CanTo->getTypeClass();
1226 if (TyClass != CanFrom->getTypeClass()) return false;
1227 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1228 return false;
1229 }
1230
1231 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1232 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1233 if (!EInfo.getNoReturn()) return false;
1234
1235 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1236 assert(QualType(FromFn, 0).isCanonical());
1237 if (QualType(FromFn, 0) != CanTo) return false;
1238
1239 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001240 return true;
1241}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001242
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001243/// \brief Determine whether the conversion from FromType to ToType is a valid
1244/// vector conversion.
1245///
1246/// \param ICK Will be set to the vector conversion kind, if this is a vector
1247/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001248static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1249 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001250 // We need at least one of these types to be a vector type to have a vector
1251 // conversion.
1252 if (!ToType->isVectorType() && !FromType->isVectorType())
1253 return false;
1254
1255 // Identical types require no conversions.
1256 if (Context.hasSameUnqualifiedType(FromType, ToType))
1257 return false;
1258
1259 // There are no conversions between extended vector types, only identity.
1260 if (ToType->isExtVectorType()) {
1261 // There are no conversions between extended vector types other than the
1262 // identity conversion.
1263 if (FromType->isExtVectorType())
1264 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001265
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001266 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001267 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001268 ICK = ICK_Vector_Splat;
1269 return true;
1270 }
1271 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001272
1273 // We can perform the conversion between vector types in the following cases:
1274 // 1)vector types are equivalent AltiVec and GCC vector types
1275 // 2)lax vector conversions are permitted and the vector types are of the
1276 // same size
1277 if (ToType->isVectorType() && FromType->isVectorType()) {
1278 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001279 (Context.getLangOptions().LaxVectorConversions &&
1280 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001281 ICK = ICK_Vector_Conversion;
1282 return true;
1283 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001284 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001285
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001286 return false;
1287}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001288
Douglas Gregor60d62c22008-10-31 16:23:19 +00001289/// IsStandardConversion - Determines whether there is a standard
1290/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1291/// expression From to the type ToType. Standard conversion sequences
1292/// only consider non-class types; for conversions that involve class
1293/// types, use TryImplicitConversion. If a conversion exists, SCS will
1294/// contain the standard conversion sequence required to perform this
1295/// conversion and this routine will return true. Otherwise, this
1296/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001297static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1298 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001299 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001300 bool CStyle,
1301 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001302 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001303
Douglas Gregor60d62c22008-10-31 16:23:19 +00001304 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001305 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001306 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001307 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001308 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001309 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001310
Douglas Gregorf9201e02009-02-11 23:02:49 +00001311 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001312 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001313 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +00001314 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001315 return false;
1316
Mike Stump1eb44332009-09-09 15:08:12 +00001317 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001318 }
1319
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001320 // The first conversion can be an lvalue-to-rvalue conversion,
1321 // array-to-pointer conversion, or function-to-pointer conversion
1322 // (C++ 4p1).
1323
John McCall120d63c2010-08-24 20:38:10 +00001324 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001325 DeclAccessPair AccessPair;
1326 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001327 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001328 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001329 // We were able to resolve the address of the overloaded function,
1330 // so we can convert to the type of that function.
1331 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001332
1333 // we can sometimes resolve &foo<int> regardless of ToType, so check
1334 // if the type matches (identity) or we are converting to bool
1335 if (!S.Context.hasSameUnqualifiedType(
1336 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1337 QualType resultTy;
1338 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001339 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001340 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1341 // otherwise, only a boolean conversion is standard
1342 if (!ToType->isBooleanType())
1343 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001344 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001345
Chandler Carruth90434232011-03-29 08:08:18 +00001346 // Check if the "from" expression is taking the address of an overloaded
1347 // function and recompute the FromType accordingly. Take advantage of the
1348 // fact that non-static member functions *must* have such an address-of
1349 // expression.
1350 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1351 if (Method && !Method->isStatic()) {
1352 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1353 "Non-unary operator on non-static member address");
1354 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1355 == UO_AddrOf &&
1356 "Non-address-of operator on non-static member address");
1357 const Type *ClassType
1358 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1359 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001360 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1361 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1362 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001363 "Non-address-of operator for overloaded function expression");
1364 FromType = S.Context.getPointerType(FromType);
1365 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001366
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001367 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001368 assert(S.Context.hasSameType(
1369 FromType,
1370 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001371 } else {
1372 return false;
1373 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001374 }
John McCall21480112011-08-30 00:57:29 +00001375 // Lvalue-to-rvalue conversion (C++11 4.1):
1376 // A glvalue (3.10) of a non-function, non-array type T can
1377 // be converted to a prvalue.
1378 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001379 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001380 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001381 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001382 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001383
1384 // If T is a non-class type, the type of the rvalue is the
1385 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001386 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1387 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001388 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001389 } else if (FromType->isArrayType()) {
1390 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001391 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001392
1393 // An lvalue or rvalue of type "array of N T" or "array of unknown
1394 // bound of T" can be converted to an rvalue of type "pointer to
1395 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001396 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001397
John McCall120d63c2010-08-24 20:38:10 +00001398 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001399 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001400 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001401
1402 // For the purpose of ranking in overload resolution
1403 // (13.3.3.1.1), this conversion is considered an
1404 // array-to-pointer conversion followed by a qualification
1405 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001406 SCS.Second = ICK_Identity;
1407 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001408 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001409 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001410 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001411 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001412 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001413 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001414 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001415
1416 // An lvalue of function type T can be converted to an rvalue of
1417 // type "pointer to T." The result is a pointer to the
1418 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001419 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001420 } else {
1421 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001422 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001423 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001424 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001425
1426 // The second conversion can be an integral promotion, floating
1427 // point promotion, integral conversion, floating point conversion,
1428 // floating-integral conversion, pointer conversion,
1429 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001430 // For overloading in C, this can also be a "compatible-type"
1431 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001432 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001433 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001434 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001435 // The unqualified versions of the types are the same: there's no
1436 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001437 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001438 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001439 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001440 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001441 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001442 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001443 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001444 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001445 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001446 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001447 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001448 SCS.Second = ICK_Complex_Promotion;
1449 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001450 } else if (ToType->isBooleanType() &&
1451 (FromType->isArithmeticType() ||
1452 FromType->isAnyPointerType() ||
1453 FromType->isBlockPointerType() ||
1454 FromType->isMemberPointerType() ||
1455 FromType->isNullPtrType())) {
1456 // Boolean conversions (C++ 4.12).
1457 SCS.Second = ICK_Boolean_Conversion;
1458 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001459 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001460 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001461 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001462 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001463 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001464 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001465 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001466 SCS.Second = ICK_Complex_Conversion;
1467 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001468 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1469 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001470 // Complex-real conversions (C99 6.3.1.7)
1471 SCS.Second = ICK_Complex_Real;
1472 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001473 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001474 // Floating point conversions (C++ 4.8).
1475 SCS.Second = ICK_Floating_Conversion;
1476 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001477 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001478 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001479 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001480 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001481 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001482 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001483 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001484 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001485 SCS.Second = ICK_Block_Pointer_Conversion;
1486 } else if (AllowObjCWritebackConversion &&
1487 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1488 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001489 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1490 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001491 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001492 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001493 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001494 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001495 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001496 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001497 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001498 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001499 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001500 SCS.Second = SecondICK;
1501 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001502 } else if (!S.getLangOptions().CPlusPlus &&
1503 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001504 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001505 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001506 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001507 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001508 // Treat a conversion that strips "noreturn" as an identity conversion.
1509 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001510 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1511 InOverloadResolution,
1512 SCS, CStyle)) {
1513 SCS.Second = ICK_TransparentUnionConversion;
1514 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001515 } else {
1516 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001517 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001518 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001519 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001520
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001521 QualType CanonFrom;
1522 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001523 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001524 bool ObjCLifetimeConversion;
1525 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1526 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001527 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001528 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001529 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001530 CanonFrom = S.Context.getCanonicalType(FromType);
1531 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001532 } else {
1533 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001534 SCS.Third = ICK_Identity;
1535
Mike Stump1eb44332009-09-09 15:08:12 +00001536 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001537 // [...] Any difference in top-level cv-qualification is
1538 // subsumed by the initialization itself and does not constitute
1539 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001540 CanonFrom = S.Context.getCanonicalType(FromType);
1541 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001542 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001543 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001544 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001545 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1546 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001547 FromType = ToType;
1548 CanonFrom = CanonTo;
1549 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001550 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001551 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001552
1553 // If we have not converted the argument type to the parameter type,
1554 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001555 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001556 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001557
Douglas Gregor60d62c22008-10-31 16:23:19 +00001558 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001559}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001560
1561static bool
1562IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1563 QualType &ToType,
1564 bool InOverloadResolution,
1565 StandardConversionSequence &SCS,
1566 bool CStyle) {
1567
1568 const RecordType *UT = ToType->getAsUnionType();
1569 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1570 return false;
1571 // The field to initialize within the transparent union.
1572 RecordDecl *UD = UT->getDecl();
1573 // It's compatible if the expression matches any of the fields.
1574 for (RecordDecl::field_iterator it = UD->field_begin(),
1575 itend = UD->field_end();
1576 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001577 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1578 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001579 ToType = it->getType();
1580 return true;
1581 }
1582 }
1583 return false;
1584}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001585
1586/// IsIntegralPromotion - Determines whether the conversion from the
1587/// expression From (whose potentially-adjusted type is FromType) to
1588/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1589/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001590bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001591 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001592 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001593 if (!To) {
1594 return false;
1595 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001596
1597 // An rvalue of type char, signed char, unsigned char, short int, or
1598 // unsigned short int can be converted to an rvalue of type int if
1599 // int can represent all the values of the source type; otherwise,
1600 // the source rvalue can be converted to an rvalue of type unsigned
1601 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001602 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1603 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001604 if (// We can promote any signed, promotable integer type to an int
1605 (FromType->isSignedIntegerType() ||
1606 // We can promote any unsigned integer type whose size is
1607 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001608 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001609 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001610 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001611 }
1612
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001613 return To->getKind() == BuiltinType::UInt;
1614 }
1615
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001616 // C++0x [conv.prom]p3:
1617 // A prvalue of an unscoped enumeration type whose underlying type is not
1618 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1619 // following types that can represent all the values of the enumeration
1620 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1621 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001622 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001623 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001624 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001625 // with lowest integer conversion rank (4.13) greater than the rank of long
1626 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001627 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001628 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1629 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1630 // provided for a scoped enumeration.
1631 if (FromEnumType->getDecl()->isScoped())
1632 return false;
1633
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001634 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001635 if (ToType->isIntegerType() &&
Douglas Gregor5dde1602010-09-12 03:38:25 +00001636 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001637 return Context.hasSameUnqualifiedType(ToType,
1638 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001639 }
John McCall842aef82009-12-09 09:09:27 +00001640
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001641 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001642 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1643 // to an rvalue a prvalue of the first of the following types that can
1644 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001645 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001646 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001647 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001648 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001649 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001650 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001651 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001652 // Determine whether the type we're converting from is signed or
1653 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001654 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001655 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001656
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001657 // The types we'll try to promote to, in the appropriate
1658 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001659 QualType PromoteTypes[6] = {
1660 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001661 Context.LongTy, Context.UnsignedLongTy ,
1662 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001663 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001664 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001665 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1666 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001667 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001668 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1669 // We found the type that we can promote to. If this is the
1670 // type we wanted, we have a promotion. Otherwise, no
1671 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001672 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001673 }
1674 }
1675 }
1676
1677 // An rvalue for an integral bit-field (9.6) can be converted to an
1678 // rvalue of type int if int can represent all the values of the
1679 // bit-field; otherwise, it can be converted to unsigned int if
1680 // unsigned int can represent all the values of the bit-field. If
1681 // the bit-field is larger yet, no integral promotion applies to
1682 // it. If the bit-field has an enumerated type, it is treated as any
1683 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001684 // FIXME: We should delay checking of bit-fields until we actually perform the
1685 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001686 using llvm::APSInt;
1687 if (From)
1688 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001689 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001690 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001691 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1692 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1693 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001694
Douglas Gregor86f19402008-12-20 23:49:58 +00001695 // Are we promoting to an int from a bitfield that fits in an int?
1696 if (BitWidth < ToSize ||
1697 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1698 return To->getKind() == BuiltinType::Int;
1699 }
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Douglas Gregor86f19402008-12-20 23:49:58 +00001701 // Are we promoting to an unsigned int from an unsigned bitfield
1702 // that fits into an unsigned int?
1703 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1704 return To->getKind() == BuiltinType::UInt;
1705 }
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Douglas Gregor86f19402008-12-20 23:49:58 +00001707 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001708 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001709 }
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001711 // An rvalue of type bool can be converted to an rvalue of type int,
1712 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001713 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001714 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001715 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001716
1717 return false;
1718}
1719
1720/// IsFloatingPointPromotion - Determines whether the conversion from
1721/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1722/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001723bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001724 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1725 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001726 /// An rvalue of type float can be converted to an rvalue of type
1727 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001728 if (FromBuiltin->getKind() == BuiltinType::Float &&
1729 ToBuiltin->getKind() == BuiltinType::Double)
1730 return true;
1731
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001732 // C99 6.3.1.5p1:
1733 // When a float is promoted to double or long double, or a
1734 // double is promoted to long double [...].
1735 if (!getLangOptions().CPlusPlus &&
1736 (FromBuiltin->getKind() == BuiltinType::Float ||
1737 FromBuiltin->getKind() == BuiltinType::Double) &&
1738 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1739 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001740
1741 // Half can be promoted to float.
1742 if (FromBuiltin->getKind() == BuiltinType::Half &&
1743 ToBuiltin->getKind() == BuiltinType::Float)
1744 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001745 }
1746
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001747 return false;
1748}
1749
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001750/// \brief Determine if a conversion is a complex promotion.
1751///
1752/// A complex promotion is defined as a complex -> complex conversion
1753/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001754/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001755bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001756 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001757 if (!FromComplex)
1758 return false;
1759
John McCall183700f2009-09-21 23:43:11 +00001760 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001761 if (!ToComplex)
1762 return false;
1763
1764 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001765 ToComplex->getElementType()) ||
1766 IsIntegralPromotion(0, FromComplex->getElementType(),
1767 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001768}
1769
Douglas Gregorcb7de522008-11-26 23:31:11 +00001770/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1771/// the pointer type FromPtr to a pointer to type ToPointee, with the
1772/// same type qualifiers as FromPtr has on its pointee type. ToType,
1773/// if non-empty, will be a pointer to ToType that may or may not have
1774/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001775///
Mike Stump1eb44332009-09-09 15:08:12 +00001776static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001777BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001778 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001779 ASTContext &Context,
1780 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001781 assert((FromPtr->getTypeClass() == Type::Pointer ||
1782 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1783 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001784
John McCallf85e1932011-06-15 23:02:42 +00001785 /// Conversions to 'id' subsume cv-qualifier conversions.
1786 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001787 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001788
1789 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001790 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001791 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001792 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001793
John McCallf85e1932011-06-15 23:02:42 +00001794 if (StripObjCLifetime)
1795 Quals.removeObjCLifetime();
1796
Mike Stump1eb44332009-09-09 15:08:12 +00001797 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001798 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001799 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001800 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001801 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001802
1803 // Build a pointer to ToPointee. It has the right qualifiers
1804 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001805 if (isa<ObjCObjectPointerType>(ToType))
1806 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001807 return Context.getPointerType(ToPointee);
1808 }
1809
1810 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001811 QualType QualifiedCanonToPointee
1812 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001813
Douglas Gregorda80f742010-12-01 21:43:58 +00001814 if (isa<ObjCObjectPointerType>(ToType))
1815 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1816 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001817}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001818
Mike Stump1eb44332009-09-09 15:08:12 +00001819static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001820 bool InOverloadResolution,
1821 ASTContext &Context) {
1822 // Handle value-dependent integral null pointer constants correctly.
1823 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1824 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001825 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001826 return !InOverloadResolution;
1827
Douglas Gregorce940492009-09-25 04:25:58 +00001828 return Expr->isNullPointerConstant(Context,
1829 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1830 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001831}
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001833/// IsPointerConversion - Determines whether the conversion of the
1834/// expression From, which has the (possibly adjusted) type FromType,
1835/// can be converted to the type ToType via a pointer conversion (C++
1836/// 4.10). If so, returns true and places the converted type (that
1837/// might differ from ToType in its cv-qualifiers at some level) into
1838/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001839///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001840/// This routine also supports conversions to and from block pointers
1841/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1842/// pointers to interfaces. FIXME: Once we've determined the
1843/// appropriate overloading rules for Objective-C, we may want to
1844/// split the Objective-C checks into a different routine; however,
1845/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001846/// conversions, so for now they live here. IncompatibleObjC will be
1847/// set if the conversion is an allowed Objective-C conversion that
1848/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001849bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001850 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001851 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001852 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001853 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001854 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1855 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001856 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001857
Mike Stump1eb44332009-09-09 15:08:12 +00001858 // Conversion from a null pointer constant to any Objective-C pointer type.
1859 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001860 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001861 ConvertedType = ToType;
1862 return true;
1863 }
1864
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001865 // Blocks: Block pointers can be converted to void*.
1866 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001867 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001868 ConvertedType = ToType;
1869 return true;
1870 }
1871 // Blocks: A null pointer constant can be converted to a block
1872 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001873 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001874 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001875 ConvertedType = ToType;
1876 return true;
1877 }
1878
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001879 // If the left-hand-side is nullptr_t, the right side can be a null
1880 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001881 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001882 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001883 ConvertedType = ToType;
1884 return true;
1885 }
1886
Ted Kremenek6217b802009-07-29 21:53:49 +00001887 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001888 if (!ToTypePtr)
1889 return false;
1890
1891 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001892 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001893 ConvertedType = ToType;
1894 return true;
1895 }
Sebastian Redl07779722008-10-31 14:43:28 +00001896
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001897 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001898 // , including objective-c pointers.
1899 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001900 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1901 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001902 ConvertedType = BuildSimilarlyQualifiedPointerType(
1903 FromType->getAs<ObjCObjectPointerType>(),
1904 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001905 ToType, Context);
1906 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001907 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001908 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001909 if (!FromTypePtr)
1910 return false;
1911
1912 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001913
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001914 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001915 // pointer conversion, so don't do all of the work below.
1916 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1917 return false;
1918
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001919 // An rvalue of type "pointer to cv T," where T is an object type,
1920 // can be converted to an rvalue of type "pointer to cv void" (C++
1921 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001922 if (FromPointeeType->isIncompleteOrObjectType() &&
1923 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001924 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001925 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00001926 ToType, Context,
1927 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001928 return true;
1929 }
1930
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001931 // MSVC allows implicit function to void* type conversion.
Francois Pichet62ec1f22011-09-17 17:15:52 +00001932 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001933 ToPointeeType->isVoidType()) {
1934 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1935 ToPointeeType,
1936 ToType, Context);
1937 return true;
1938 }
1939
Douglas Gregorf9201e02009-02-11 23:02:49 +00001940 // When we're overloading in C, we allow a special kind of pointer
1941 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001942 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001943 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001944 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001945 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001946 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001947 return true;
1948 }
1949
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001950 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001951 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001952 // An rvalue of type "pointer to cv D," where D is a class type,
1953 // can be converted to an rvalue of type "pointer to cv B," where
1954 // B is a base class (clause 10) of D. If B is an inaccessible
1955 // (clause 11) or ambiguous (10.2) base class of D, a program that
1956 // necessitates this conversion is ill-formed. The result of the
1957 // conversion is a pointer to the base class sub-object of the
1958 // derived class object. The null pointer value is converted to
1959 // the null pointer value of the destination type.
1960 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001961 // Note that we do not check for ambiguity or inaccessibility
1962 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001963 if (getLangOptions().CPlusPlus &&
1964 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001965 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001966 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001967 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001968 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001969 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001970 ToType, Context);
1971 return true;
1972 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001973
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00001974 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1975 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1976 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1977 ToPointeeType,
1978 ToType, Context);
1979 return true;
1980 }
1981
Douglas Gregorc7887512008-12-19 19:13:09 +00001982 return false;
1983}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001984
1985/// \brief Adopt the given qualifiers for the given type.
1986static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1987 Qualifiers TQs = T.getQualifiers();
1988
1989 // Check whether qualifiers already match.
1990 if (TQs == Qs)
1991 return T;
1992
1993 if (Qs.compatiblyIncludes(TQs))
1994 return Context.getQualifiedType(T, Qs);
1995
1996 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1997}
Douglas Gregorc7887512008-12-19 19:13:09 +00001998
1999/// isObjCPointerConversion - Determines whether this is an
2000/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2001/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002002bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002003 QualType& ConvertedType,
2004 bool &IncompatibleObjC) {
2005 if (!getLangOptions().ObjC1)
2006 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002007
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002008 // The set of qualifiers on the type we're converting from.
2009 Qualifiers FromQualifiers = FromType.getQualifiers();
2010
Steve Naroff14108da2009-07-10 23:34:53 +00002011 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002012 const ObjCObjectPointerType* ToObjCPtr =
2013 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002014 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002015 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002016
Steve Naroff14108da2009-07-10 23:34:53 +00002017 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002018 // If the pointee types are the same (ignoring qualifications),
2019 // then this is not a pointer conversion.
2020 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2021 FromObjCPtr->getPointeeType()))
2022 return false;
2023
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002024 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002025 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002026 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002027 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002028 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002029 return true;
2030 }
2031 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002032 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002033 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002034 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002035 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002036 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002037 return true;
2038 }
2039 // Objective C++: We're able to convert from a pointer to an
2040 // interface to a pointer to a different interface.
2041 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002042 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2043 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2044 if (getLangOptions().CPlusPlus && LHS && RHS &&
2045 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2046 FromObjCPtr->getPointeeType()))
2047 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002048 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002049 ToObjCPtr->getPointeeType(),
2050 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002051 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002052 return true;
2053 }
2054
2055 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2056 // Okay: this is some kind of implicit downcast of Objective-C
2057 // interfaces, which is permitted. However, we're going to
2058 // complain about it.
2059 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002060 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002061 ToObjCPtr->getPointeeType(),
2062 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002063 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002064 return true;
2065 }
Mike Stump1eb44332009-09-09 15:08:12 +00002066 }
Steve Naroff14108da2009-07-10 23:34:53 +00002067 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002068 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002069 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002070 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002071 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002072 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002073 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002074 // to a block pointer type.
2075 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002076 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002077 return true;
2078 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002079 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002080 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002081 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002082 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002083 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002084 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002085 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002086 return true;
2087 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002088 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002089 return false;
2090
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002091 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002092 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002093 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002094 else if (const BlockPointerType *FromBlockPtr =
2095 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002096 FromPointeeType = FromBlockPtr->getPointeeType();
2097 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002098 return false;
2099
Douglas Gregorc7887512008-12-19 19:13:09 +00002100 // If we have pointers to pointers, recursively check whether this
2101 // is an Objective-C conversion.
2102 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2103 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2104 IncompatibleObjC)) {
2105 // We always complain about this conversion.
2106 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002107 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002108 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002109 return true;
2110 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002111 // Allow conversion of pointee being objective-c pointer to another one;
2112 // as in I* to id.
2113 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2114 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2115 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2116 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002117
Douglas Gregorda80f742010-12-01 21:43:58 +00002118 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002119 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002120 return true;
2121 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002122
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002123 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002124 // differences in the argument and result types are in Objective-C
2125 // pointer conversions. If so, we permit the conversion (but
2126 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002127 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002128 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002129 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002130 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002131 if (FromFunctionType && ToFunctionType) {
2132 // If the function types are exactly the same, this isn't an
2133 // Objective-C pointer conversion.
2134 if (Context.getCanonicalType(FromPointeeType)
2135 == Context.getCanonicalType(ToPointeeType))
2136 return false;
2137
2138 // Perform the quick checks that will tell us whether these
2139 // function types are obviously different.
2140 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2141 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2142 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2143 return false;
2144
2145 bool HasObjCConversion = false;
2146 if (Context.getCanonicalType(FromFunctionType->getResultType())
2147 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2148 // Okay, the types match exactly. Nothing to do.
2149 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2150 ToFunctionType->getResultType(),
2151 ConvertedType, IncompatibleObjC)) {
2152 // Okay, we have an Objective-C pointer conversion.
2153 HasObjCConversion = true;
2154 } else {
2155 // Function types are too different. Abort.
2156 return false;
2157 }
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Douglas Gregorc7887512008-12-19 19:13:09 +00002159 // Check argument types.
2160 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2161 ArgIdx != NumArgs; ++ArgIdx) {
2162 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2163 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2164 if (Context.getCanonicalType(FromArgType)
2165 == Context.getCanonicalType(ToArgType)) {
2166 // Okay, the types match exactly. Nothing to do.
2167 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2168 ConvertedType, IncompatibleObjC)) {
2169 // Okay, we have an Objective-C pointer conversion.
2170 HasObjCConversion = true;
2171 } else {
2172 // Argument types are too different. Abort.
2173 return false;
2174 }
2175 }
2176
2177 if (HasObjCConversion) {
2178 // We had an Objective-C conversion. Allow this pointer
2179 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002180 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002181 IncompatibleObjC = true;
2182 return true;
2183 }
2184 }
2185
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002186 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002187}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002188
John McCallf85e1932011-06-15 23:02:42 +00002189/// \brief Determine whether this is an Objective-C writeback conversion,
2190/// used for parameter passing when performing automatic reference counting.
2191///
2192/// \param FromType The type we're converting form.
2193///
2194/// \param ToType The type we're converting to.
2195///
2196/// \param ConvertedType The type that will be produced after applying
2197/// this conversion.
2198bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2199 QualType &ConvertedType) {
2200 if (!getLangOptions().ObjCAutoRefCount ||
2201 Context.hasSameUnqualifiedType(FromType, ToType))
2202 return false;
2203
2204 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2205 QualType ToPointee;
2206 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2207 ToPointee = ToPointer->getPointeeType();
2208 else
2209 return false;
2210
2211 Qualifiers ToQuals = ToPointee.getQualifiers();
2212 if (!ToPointee->isObjCLifetimeType() ||
2213 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002214 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002215 return false;
2216
2217 // Argument must be a pointer to __strong to __weak.
2218 QualType FromPointee;
2219 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2220 FromPointee = FromPointer->getPointeeType();
2221 else
2222 return false;
2223
2224 Qualifiers FromQuals = FromPointee.getQualifiers();
2225 if (!FromPointee->isObjCLifetimeType() ||
2226 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2227 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2228 return false;
2229
2230 // Make sure that we have compatible qualifiers.
2231 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2232 if (!ToQuals.compatiblyIncludes(FromQuals))
2233 return false;
2234
2235 // Remove qualifiers from the pointee type we're converting from; they
2236 // aren't used in the compatibility check belong, and we'll be adding back
2237 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2238 FromPointee = FromPointee.getUnqualifiedType();
2239
2240 // The unqualified form of the pointee types must be compatible.
2241 ToPointee = ToPointee.getUnqualifiedType();
2242 bool IncompatibleObjC;
2243 if (Context.typesAreCompatible(FromPointee, ToPointee))
2244 FromPointee = ToPointee;
2245 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2246 IncompatibleObjC))
2247 return false;
2248
2249 /// \brief Construct the type we're converting to, which is a pointer to
2250 /// __autoreleasing pointee.
2251 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2252 ConvertedType = Context.getPointerType(FromPointee);
2253 return true;
2254}
2255
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002256bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2257 QualType& ConvertedType) {
2258 QualType ToPointeeType;
2259 if (const BlockPointerType *ToBlockPtr =
2260 ToType->getAs<BlockPointerType>())
2261 ToPointeeType = ToBlockPtr->getPointeeType();
2262 else
2263 return false;
2264
2265 QualType FromPointeeType;
2266 if (const BlockPointerType *FromBlockPtr =
2267 FromType->getAs<BlockPointerType>())
2268 FromPointeeType = FromBlockPtr->getPointeeType();
2269 else
2270 return false;
2271 // We have pointer to blocks, check whether the only
2272 // differences in the argument and result types are in Objective-C
2273 // pointer conversions. If so, we permit the conversion.
2274
2275 const FunctionProtoType *FromFunctionType
2276 = FromPointeeType->getAs<FunctionProtoType>();
2277 const FunctionProtoType *ToFunctionType
2278 = ToPointeeType->getAs<FunctionProtoType>();
2279
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002280 if (!FromFunctionType || !ToFunctionType)
2281 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002282
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002283 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002284 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002285
2286 // Perform the quick checks that will tell us whether these
2287 // function types are obviously different.
2288 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2289 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2290 return false;
2291
2292 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2293 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2294 if (FromEInfo != ToEInfo)
2295 return false;
2296
2297 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002298 if (Context.hasSameType(FromFunctionType->getResultType(),
2299 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002300 // Okay, the types match exactly. Nothing to do.
2301 } else {
2302 QualType RHS = FromFunctionType->getResultType();
2303 QualType LHS = ToFunctionType->getResultType();
2304 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2305 !RHS.hasQualifiers() && LHS.hasQualifiers())
2306 LHS = LHS.getUnqualifiedType();
2307
2308 if (Context.hasSameType(RHS,LHS)) {
2309 // OK exact match.
2310 } else if (isObjCPointerConversion(RHS, LHS,
2311 ConvertedType, IncompatibleObjC)) {
2312 if (IncompatibleObjC)
2313 return false;
2314 // Okay, we have an Objective-C pointer conversion.
2315 }
2316 else
2317 return false;
2318 }
2319
2320 // Check argument types.
2321 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2322 ArgIdx != NumArgs; ++ArgIdx) {
2323 IncompatibleObjC = false;
2324 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2325 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2326 if (Context.hasSameType(FromArgType, ToArgType)) {
2327 // Okay, the types match exactly. Nothing to do.
2328 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2329 ConvertedType, IncompatibleObjC)) {
2330 if (IncompatibleObjC)
2331 return false;
2332 // Okay, we have an Objective-C pointer conversion.
2333 } else
2334 // Argument types are too different. Abort.
2335 return false;
2336 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002337 if (LangOpts.ObjCAutoRefCount &&
2338 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2339 ToFunctionType))
2340 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002341
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002342 ConvertedType = ToType;
2343 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002344}
2345
Richard Trieu6efd4c52011-11-23 22:32:32 +00002346enum {
2347 ft_default,
2348 ft_different_class,
2349 ft_parameter_arity,
2350 ft_parameter_mismatch,
2351 ft_return_type,
2352 ft_qualifer_mismatch
2353};
2354
2355/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2356/// function types. Catches different number of parameter, mismatch in
2357/// parameter types, and different return types.
2358void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2359 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002360 // If either type is not valid, include no extra info.
2361 if (FromType.isNull() || ToType.isNull()) {
2362 PDiag << ft_default;
2363 return;
2364 }
2365
Richard Trieu6efd4c52011-11-23 22:32:32 +00002366 // Get the function type from the pointers.
2367 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2368 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2369 *ToMember = ToType->getAs<MemberPointerType>();
2370 if (FromMember->getClass() != ToMember->getClass()) {
2371 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2372 << QualType(FromMember->getClass(), 0);
2373 return;
2374 }
2375 FromType = FromMember->getPointeeType();
2376 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002377 }
2378
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002379 if (FromType->isPointerType())
2380 FromType = FromType->getPointeeType();
2381 if (ToType->isPointerType())
2382 ToType = ToType->getPointeeType();
2383
2384 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002385 FromType = FromType.getNonReferenceType();
2386 ToType = ToType.getNonReferenceType();
2387
Richard Trieu6efd4c52011-11-23 22:32:32 +00002388 // Don't print extra info for non-specialized template functions.
2389 if (FromType->isInstantiationDependentType() &&
2390 !FromType->getAs<TemplateSpecializationType>()) {
2391 PDiag << ft_default;
2392 return;
2393 }
2394
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002395 // No extra info for same types.
2396 if (Context.hasSameType(FromType, ToType)) {
2397 PDiag << ft_default;
2398 return;
2399 }
2400
Richard Trieu6efd4c52011-11-23 22:32:32 +00002401 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2402 *ToFunction = ToType->getAs<FunctionProtoType>();
2403
2404 // Both types need to be function types.
2405 if (!FromFunction || !ToFunction) {
2406 PDiag << ft_default;
2407 return;
2408 }
2409
2410 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2411 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2412 << FromFunction->getNumArgs();
2413 return;
2414 }
2415
2416 // Handle different parameter types.
2417 unsigned ArgPos;
2418 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2419 PDiag << ft_parameter_mismatch << ArgPos + 1
2420 << ToFunction->getArgType(ArgPos)
2421 << FromFunction->getArgType(ArgPos);
2422 return;
2423 }
2424
2425 // Handle different return type.
2426 if (!Context.hasSameType(FromFunction->getResultType(),
2427 ToFunction->getResultType())) {
2428 PDiag << ft_return_type << ToFunction->getResultType()
2429 << FromFunction->getResultType();
2430 return;
2431 }
2432
2433 unsigned FromQuals = FromFunction->getTypeQuals(),
2434 ToQuals = ToFunction->getTypeQuals();
2435 if (FromQuals != ToQuals) {
2436 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2437 return;
2438 }
2439
2440 // Unable to find a difference, so add no extra info.
2441 PDiag << ft_default;
2442}
2443
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002444/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002445/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002446/// they have same number of arguments. This routine assumes that Objective-C
2447/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002448/// If the parameters are different, ArgPos will have the the parameter index
2449/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002450bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002451 const FunctionProtoType *NewType,
2452 unsigned *ArgPos) {
2453 if (!getLangOptions().ObjC1) {
2454 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2455 N = NewType->arg_type_begin(),
2456 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2457 if (!Context.hasSameType(*O, *N)) {
2458 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2459 return false;
2460 }
2461 }
2462 return true;
2463 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002464
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002465 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2466 N = NewType->arg_type_begin(),
2467 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2468 QualType ToType = (*O);
2469 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002470 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002471 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2472 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002473 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2474 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2475 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2476 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002477 continue;
2478 }
John McCallc12c5bb2010-05-15 11:32:37 +00002479 else if (const ObjCObjectPointerType *PTTo =
2480 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002481 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002482 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002483 if (Context.hasSameUnqualifiedType(
2484 PTTo->getObjectType()->getBaseType(),
2485 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002486 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002487 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002488 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002489 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002490 }
2491 }
2492 return true;
2493}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002494
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002495/// CheckPointerConversion - Check the pointer conversion from the
2496/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002497/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002498/// conversions for which IsPointerConversion has already returned
2499/// true. It returns true and produces a diagnostic if there was an
2500/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002501bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002502 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002503 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002504 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002505 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002506 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002507
John McCalldaa8e4e2010-11-15 09:13:47 +00002508 Kind = CK_BitCast;
2509
Chandler Carruth88f0aed2011-04-09 07:32:05 +00002510 if (!IsCStyleOrFunctionalCast &&
2511 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2512 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2513 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruthb6006692011-04-09 07:48:17 +00002514 PDiag(diag::warn_impcast_bool_to_null_pointer)
2515 << ToType << From->getSourceRange());
Douglas Gregord7a95972010-06-08 17:35:15 +00002516
John McCall1d9b3b22011-09-09 05:25:32 +00002517 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2518 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002519 QualType FromPointeeType = FromPtrType->getPointeeType(),
2520 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002521
Douglas Gregor5fccd362010-03-03 23:55:11 +00002522 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2523 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002524 // We must have a derived-to-base conversion. Check an
2525 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002526 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2527 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002528 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002529 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002530 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002531
Anders Carlsson61faec12009-09-12 04:46:44 +00002532 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002533 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002534 }
2535 }
John McCall1d9b3b22011-09-09 05:25:32 +00002536 } else if (const ObjCObjectPointerType *ToPtrType =
2537 ToType->getAs<ObjCObjectPointerType>()) {
2538 if (const ObjCObjectPointerType *FromPtrType =
2539 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002540 // Objective-C++ conversions are always okay.
2541 // FIXME: We should have a different class of conversions for the
2542 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002543 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002544 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002545 } else if (FromType->isBlockPointerType()) {
2546 Kind = CK_BlockPointerToObjCPointerCast;
2547 } else {
2548 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002549 }
John McCall1d9b3b22011-09-09 05:25:32 +00002550 } else if (ToType->isBlockPointerType()) {
2551 if (!FromType->isBlockPointerType())
2552 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002553 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002554
2555 // We shouldn't fall into this case unless it's valid for other
2556 // reasons.
2557 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2558 Kind = CK_NullToPointer;
2559
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002560 return false;
2561}
2562
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002563/// IsMemberPointerConversion - Determines whether the conversion of the
2564/// expression From, which has the (possibly adjusted) type FromType, can be
2565/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2566/// If so, returns true and places the converted type (that might differ from
2567/// ToType in its cv-qualifiers at some level) into ConvertedType.
2568bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002569 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002570 bool InOverloadResolution,
2571 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002572 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002573 if (!ToTypePtr)
2574 return false;
2575
2576 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002577 if (From->isNullPointerConstant(Context,
2578 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2579 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002580 ConvertedType = ToType;
2581 return true;
2582 }
2583
2584 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002585 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002586 if (!FromTypePtr)
2587 return false;
2588
2589 // A pointer to member of B can be converted to a pointer to member of D,
2590 // where D is derived from B (C++ 4.11p2).
2591 QualType FromClass(FromTypePtr->getClass(), 0);
2592 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002593
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002594 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2595 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2596 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002597 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2598 ToClass.getTypePtr());
2599 return true;
2600 }
2601
2602 return false;
2603}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002604
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002605/// CheckMemberPointerConversion - Check the member pointer conversion from the
2606/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002607/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002608/// for which IsMemberPointerConversion has already returned true. It returns
2609/// true and produces a diagnostic if there was an error, or returns false
2610/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002611bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002612 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002613 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002614 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002615 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002616 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002617 if (!FromPtrType) {
2618 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002619 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002620 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002621 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002622 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002623 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002624 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002625
Ted Kremenek6217b802009-07-29 21:53:49 +00002626 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002627 assert(ToPtrType && "No member pointer cast has a target type "
2628 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002629
Sebastian Redl21593ac2009-01-28 18:33:18 +00002630 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2631 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002632
Sebastian Redl21593ac2009-01-28 18:33:18 +00002633 // FIXME: What about dependent types?
2634 assert(FromClass->isRecordType() && "Pointer into non-class.");
2635 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002636
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002637 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002638 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002639 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2640 assert(DerivationOkay &&
2641 "Should not have been called if derivation isn't OK.");
2642 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002643
Sebastian Redl21593ac2009-01-28 18:33:18 +00002644 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2645 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002646 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2647 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2648 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2649 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002650 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002651
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002652 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002653 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2654 << FromClass << ToClass << QualType(VBase, 0)
2655 << From->getSourceRange();
2656 return true;
2657 }
2658
John McCall6b2accb2010-02-10 09:31:12 +00002659 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002660 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2661 Paths.front(),
2662 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002663
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002664 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002665 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002666 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002667 return false;
2668}
2669
Douglas Gregor98cd5992008-10-21 23:43:52 +00002670/// IsQualificationConversion - Determines whether the conversion from
2671/// an rvalue of type FromType to ToType is a qualification conversion
2672/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002673///
2674/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2675/// when the qualification conversion involves a change in the Objective-C
2676/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002677bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002678Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002679 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002680 FromType = Context.getCanonicalType(FromType);
2681 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002682 ObjCLifetimeConversion = false;
2683
Douglas Gregor98cd5992008-10-21 23:43:52 +00002684 // If FromType and ToType are the same type, this is not a
2685 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002686 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002687 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002688
Douglas Gregor98cd5992008-10-21 23:43:52 +00002689 // (C++ 4.4p4):
2690 // A conversion can add cv-qualifiers at levels other than the first
2691 // in multi-level pointers, subject to the following rules: [...]
2692 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002693 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002694 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002695 // Within each iteration of the loop, we check the qualifiers to
2696 // determine if this still looks like a qualification
2697 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002698 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002699 // until there are no more pointers or pointers-to-members left to
2700 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002701 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002702
Douglas Gregor621c92a2011-04-25 18:40:17 +00002703 Qualifiers FromQuals = FromType.getQualifiers();
2704 Qualifiers ToQuals = ToType.getQualifiers();
2705
John McCallf85e1932011-06-15 23:02:42 +00002706 // Objective-C ARC:
2707 // Check Objective-C lifetime conversions.
2708 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2709 UnwrappedAnyPointer) {
2710 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2711 ObjCLifetimeConversion = true;
2712 FromQuals.removeObjCLifetime();
2713 ToQuals.removeObjCLifetime();
2714 } else {
2715 // Qualification conversions cannot cast between different
2716 // Objective-C lifetime qualifiers.
2717 return false;
2718 }
2719 }
2720
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002721 // Allow addition/removal of GC attributes but not changing GC attributes.
2722 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2723 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2724 FromQuals.removeObjCGCAttr();
2725 ToQuals.removeObjCGCAttr();
2726 }
2727
Douglas Gregor98cd5992008-10-21 23:43:52 +00002728 // -- for every j > 0, if const is in cv 1,j then const is in cv
2729 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002730 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002731 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002732
Douglas Gregor98cd5992008-10-21 23:43:52 +00002733 // -- if the cv 1,j and cv 2,j are different, then const is in
2734 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002735 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002736 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002737 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002738
Douglas Gregor98cd5992008-10-21 23:43:52 +00002739 // Keep track of whether all prior cv-qualifiers in the "to" type
2740 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002741 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002742 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002743 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002744
2745 // We are left with FromType and ToType being the pointee types
2746 // after unwrapping the original FromType and ToType the same number
2747 // of types. If we unwrapped any pointers, and if FromType and
2748 // ToType have the same unqualified type (since we checked
2749 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002750 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002751}
2752
Sebastian Redl56a04282012-02-11 23:51:08 +00002753static OverloadingResult
2754IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2755 CXXRecordDecl *To,
2756 UserDefinedConversionSequence &User,
2757 OverloadCandidateSet &CandidateSet,
2758 bool AllowExplicit) {
2759 DeclContext::lookup_iterator Con, ConEnd;
2760 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2761 Con != ConEnd; ++Con) {
2762 NamedDecl *D = *Con;
2763 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2764
2765 // Find the constructor (which may be a template).
2766 CXXConstructorDecl *Constructor = 0;
2767 FunctionTemplateDecl *ConstructorTmpl
2768 = dyn_cast<FunctionTemplateDecl>(D);
2769 if (ConstructorTmpl)
2770 Constructor
2771 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2772 else
2773 Constructor = cast<CXXConstructorDecl>(D);
2774
2775 bool Usable = !Constructor->isInvalidDecl() &&
2776 S.isInitListConstructor(Constructor) &&
2777 (AllowExplicit || !Constructor->isExplicit());
2778 if (Usable) {
2779 if (ConstructorTmpl)
2780 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2781 /*ExplicitArgs*/ 0,
2782 &From, 1, CandidateSet,
2783 /*SuppressUserConversions=*/true);
2784 else
2785 S.AddOverloadCandidate(Constructor, FoundDecl,
2786 &From, 1, CandidateSet,
2787 /*SuppressUserConversions=*/true);
2788 }
2789 }
2790
2791 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2792
2793 OverloadCandidateSet::iterator Best;
2794 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2795 case OR_Success: {
2796 // Record the standard conversion we used and the conversion function.
2797 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2798 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2799
2800 QualType ThisType = Constructor->getThisType(S.Context);
2801 // Initializer lists don't have conversions as such.
2802 User.Before.setAsIdentityConversion();
2803 User.HadMultipleCandidates = HadMultipleCandidates;
2804 User.ConversionFunction = Constructor;
2805 User.FoundConversionFunction = Best->FoundDecl;
2806 User.After.setAsIdentityConversion();
2807 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2808 User.After.setAllToTypes(ToType);
2809 return OR_Success;
2810 }
2811
2812 case OR_No_Viable_Function:
2813 return OR_No_Viable_Function;
2814 case OR_Deleted:
2815 return OR_Deleted;
2816 case OR_Ambiguous:
2817 return OR_Ambiguous;
2818 }
2819
2820 llvm_unreachable("Invalid OverloadResult!");
2821}
2822
Douglas Gregor734d9862009-01-30 23:27:23 +00002823/// Determines whether there is a user-defined conversion sequence
2824/// (C++ [over.ics.user]) that converts expression From to the type
2825/// ToType. If such a conversion exists, User will contain the
2826/// user-defined conversion sequence that performs such a conversion
2827/// and this routine will return true. Otherwise, this routine returns
2828/// false and User is unspecified.
2829///
Douglas Gregor734d9862009-01-30 23:27:23 +00002830/// \param AllowExplicit true if the conversion should consider C++0x
2831/// "explicit" conversion functions as well as non-explicit conversion
2832/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002833static OverloadingResult
2834IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002835 UserDefinedConversionSequence &User,
2836 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002837 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002838 // Whether we will only visit constructors.
2839 bool ConstructorsOnly = false;
2840
2841 // If the type we are conversion to is a class type, enumerate its
2842 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002843 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002844 // C++ [over.match.ctor]p1:
2845 // When objects of class type are direct-initialized (8.5), or
2846 // copy-initialized from an expression of the same or a
2847 // derived class type (8.5), overload resolution selects the
2848 // constructor. [...] For copy-initialization, the candidate
2849 // functions are all the converting constructors (12.3.1) of
2850 // that class. The argument list is the expression-list within
2851 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002852 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002853 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002854 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002855 ConstructorsOnly = true;
2856
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002857 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2858 // RequireCompleteType may have returned true due to some invalid decl
2859 // during template instantiation, but ToType may be complete enough now
2860 // to try to recover.
2861 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002862 // We're not going to find any constructors.
2863 } else if (CXXRecordDecl *ToRecordDecl
2864 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002865
2866 Expr **Args = &From;
2867 unsigned NumArgs = 1;
2868 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002869 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00002870 // But first, see if there is an init-list-contructor that will work.
2871 OverloadingResult Result = IsInitializerListConstructorConversion(
2872 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2873 if (Result != OR_No_Viable_Function)
2874 return Result;
2875 // Never mind.
2876 CandidateSet.clear();
2877
2878 // If we're list-initializing, we pass the individual elements as
2879 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002880 Args = InitList->getInits();
2881 NumArgs = InitList->getNumInits();
2882 ListInitializing = true;
2883 }
2884
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002885 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002886 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002887 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002888 NamedDecl *D = *Con;
2889 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2890
Douglas Gregordec06662009-08-21 18:42:58 +00002891 // Find the constructor (which may be a template).
2892 CXXConstructorDecl *Constructor = 0;
2893 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002894 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002895 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002896 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002897 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2898 else
John McCall9aa472c2010-03-19 07:35:19 +00002899 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002900
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002901 bool Usable = !Constructor->isInvalidDecl();
2902 if (ListInitializing)
2903 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2904 else
2905 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2906 if (Usable) {
Douglas Gregordec06662009-08-21 18:42:58 +00002907 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002908 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2909 /*ExplicitArgs*/ 0,
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002910 Args, NumArgs, CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002911 /*SuppressUserConversions=*/
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002912 !ConstructorsOnly &&
2913 !ListInitializing);
Douglas Gregordec06662009-08-21 18:42:58 +00002914 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002915 // Allow one user-defined conversion when user specifies a
2916 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002917 S.AddOverloadCandidate(Constructor, FoundDecl,
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002918 Args, NumArgs, CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002919 /*SuppressUserConversions=*/
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002920 !ConstructorsOnly && !ListInitializing);
Douglas Gregordec06662009-08-21 18:42:58 +00002921 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002922 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002923 }
2924 }
2925
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002926 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002927 if (ConstructorsOnly || isa<InitListExpr>(From)) {
John McCall120d63c2010-08-24 20:38:10 +00002928 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2929 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002930 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002931 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002932 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002933 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002934 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2935 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002936 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002937 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002938 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002939 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002940 DeclAccessPair FoundDecl = I.getPair();
2941 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002942 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2943 if (isa<UsingShadowDecl>(D))
2944 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2945
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002946 CXXConversionDecl *Conv;
2947 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002948 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2949 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002950 else
John McCall32daa422010-03-31 01:36:47 +00002951 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002952
2953 if (AllowExplicit || !Conv->isExplicit()) {
2954 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002955 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2956 ActingContext, From, ToType,
2957 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002958 else
John McCall120d63c2010-08-24 20:38:10 +00002959 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2960 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002961 }
2962 }
2963 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002964 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002965
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002966 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2967
Douglas Gregor60d62c22008-10-31 16:23:19 +00002968 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002969 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002970 case OR_Success:
2971 // Record the standard conversion we used and the conversion function.
2972 if (CXXConstructorDecl *Constructor
2973 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002974 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth25ca4212011-02-25 19:41:05 +00002975
John McCall120d63c2010-08-24 20:38:10 +00002976 // C++ [over.ics.user]p1:
2977 // If the user-defined conversion is specified by a
2978 // constructor (12.3.1), the initial standard conversion
2979 // sequence converts the source type to the type required by
2980 // the argument of the constructor.
2981 //
2982 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002983 if (isa<InitListExpr>(From)) {
2984 // Initializer lists don't have conversions as such.
2985 User.Before.setAsIdentityConversion();
2986 } else {
2987 if (Best->Conversions[0].isEllipsis())
2988 User.EllipsisConversion = true;
2989 else {
2990 User.Before = Best->Conversions[0].Standard;
2991 User.EllipsisConversion = false;
2992 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002993 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002994 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00002995 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00002996 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00002997 User.After.setAsIdentityConversion();
2998 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2999 User.After.setAllToTypes(ToType);
3000 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003001 }
3002 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003003 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003004 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003005
John McCall120d63c2010-08-24 20:38:10 +00003006 // C++ [over.ics.user]p1:
3007 //
3008 // [...] If the user-defined conversion is specified by a
3009 // conversion function (12.3.2), the initial standard
3010 // conversion sequence converts the source type to the
3011 // implicit object parameter of the conversion function.
3012 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003013 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003014 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003015 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003016 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003017
John McCall120d63c2010-08-24 20:38:10 +00003018 // C++ [over.ics.user]p2:
3019 // The second standard conversion sequence converts the
3020 // result of the user-defined conversion to the target type
3021 // for the sequence. Since an implicit conversion sequence
3022 // is an initialization, the special rules for
3023 // initialization by user-defined conversion apply when
3024 // selecting the best user-defined conversion for a
3025 // user-defined conversion sequence (see 13.3.3 and
3026 // 13.3.3.1).
3027 User.After = Best->FinalConversion;
3028 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003029 }
David Blaikie7530c032012-01-17 06:56:22 +00003030 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003031
John McCall120d63c2010-08-24 20:38:10 +00003032 case OR_No_Viable_Function:
3033 return OR_No_Viable_Function;
3034 case OR_Deleted:
3035 // No conversion here! We're done.
3036 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003037
John McCall120d63c2010-08-24 20:38:10 +00003038 case OR_Ambiguous:
3039 return OR_Ambiguous;
3040 }
3041
David Blaikie7530c032012-01-17 06:56:22 +00003042 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003043}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003044
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003045bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003046Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003047 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003048 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003049 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003050 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003051 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003052 if (OvResult == OR_Ambiguous)
3053 Diag(From->getSourceRange().getBegin(),
3054 diag::err_typecheck_ambiguous_condition)
3055 << From->getType() << ToType << From->getSourceRange();
3056 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
3057 Diag(From->getSourceRange().getBegin(),
3058 diag::err_typecheck_nonviable_condition)
3059 << From->getType() << ToType << From->getSourceRange();
3060 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003061 return false;
John McCall120d63c2010-08-24 20:38:10 +00003062 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003063 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003064}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003065
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003066/// CompareImplicitConversionSequences - Compare two implicit
3067/// conversion sequences to determine whether one is better than the
3068/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003069static ImplicitConversionSequence::CompareKind
3070CompareImplicitConversionSequences(Sema &S,
3071 const ImplicitConversionSequence& ICS1,
3072 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003073{
3074 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3075 // conversion sequences (as defined in 13.3.3.1)
3076 // -- a standard conversion sequence (13.3.3.1.1) is a better
3077 // conversion sequence than a user-defined conversion sequence or
3078 // an ellipsis conversion sequence, and
3079 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3080 // conversion sequence than an ellipsis conversion sequence
3081 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003082 //
John McCall1d318332010-01-12 00:44:57 +00003083 // C++0x [over.best.ics]p10:
3084 // For the purpose of ranking implicit conversion sequences as
3085 // described in 13.3.3.2, the ambiguous conversion sequence is
3086 // treated as a user-defined sequence that is indistinguishable
3087 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003088 if (ICS1.getKindRank() < ICS2.getKindRank())
3089 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003090 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003091 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003092
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003093 // The following checks require both conversion sequences to be of
3094 // the same kind.
3095 if (ICS1.getKind() != ICS2.getKind())
3096 return ImplicitConversionSequence::Indistinguishable;
3097
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003098 ImplicitConversionSequence::CompareKind Result =
3099 ImplicitConversionSequence::Indistinguishable;
3100
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003101 // Two implicit conversion sequences of the same form are
3102 // indistinguishable conversion sequences unless one of the
3103 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003104 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003105 Result = CompareStandardConversionSequences(S,
3106 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003107 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003108 // User-defined conversion sequence U1 is a better conversion
3109 // sequence than another user-defined conversion sequence U2 if
3110 // they contain the same user-defined conversion function or
3111 // constructor and if the second standard conversion sequence of
3112 // U1 is better than the second standard conversion sequence of
3113 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003114 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003115 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003116 Result = CompareStandardConversionSequences(S,
3117 ICS1.UserDefined.After,
3118 ICS2.UserDefined.After);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003119 }
3120
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003121 // List-initialization sequence L1 is a better conversion sequence than
3122 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3123 // for some X and L2 does not.
3124 if (Result == ImplicitConversionSequence::Indistinguishable &&
3125 ICS1.isListInitializationSequence() &&
3126 ICS2.isListInitializationSequence()) {
3127 // FIXME: Find out if ICS1 converts to initializer_list and ICS2 doesn't.
3128 }
3129
3130 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003131}
3132
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003133static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3134 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3135 Qualifiers Quals;
3136 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003137 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003138 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003139
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003140 return Context.hasSameUnqualifiedType(T1, T2);
3141}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003142
Douglas Gregorad323a82010-01-27 03:51:04 +00003143// Per 13.3.3.2p3, compare the given standard conversion sequences to
3144// determine if one is a proper subset of the other.
3145static ImplicitConversionSequence::CompareKind
3146compareStandardConversionSubsets(ASTContext &Context,
3147 const StandardConversionSequence& SCS1,
3148 const StandardConversionSequence& SCS2) {
3149 ImplicitConversionSequence::CompareKind Result
3150 = ImplicitConversionSequence::Indistinguishable;
3151
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003152 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003153 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003154 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3155 return ImplicitConversionSequence::Better;
3156 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3157 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003158
Douglas Gregorad323a82010-01-27 03:51:04 +00003159 if (SCS1.Second != SCS2.Second) {
3160 if (SCS1.Second == ICK_Identity)
3161 Result = ImplicitConversionSequence::Better;
3162 else if (SCS2.Second == ICK_Identity)
3163 Result = ImplicitConversionSequence::Worse;
3164 else
3165 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003166 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003167 return ImplicitConversionSequence::Indistinguishable;
3168
3169 if (SCS1.Third == SCS2.Third) {
3170 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3171 : ImplicitConversionSequence::Indistinguishable;
3172 }
3173
3174 if (SCS1.Third == ICK_Identity)
3175 return Result == ImplicitConversionSequence::Worse
3176 ? ImplicitConversionSequence::Indistinguishable
3177 : ImplicitConversionSequence::Better;
3178
3179 if (SCS2.Third == ICK_Identity)
3180 return Result == ImplicitConversionSequence::Better
3181 ? ImplicitConversionSequence::Indistinguishable
3182 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003183
Douglas Gregorad323a82010-01-27 03:51:04 +00003184 return ImplicitConversionSequence::Indistinguishable;
3185}
3186
Douglas Gregor440a4832011-01-26 14:52:12 +00003187/// \brief Determine whether one of the given reference bindings is better
3188/// than the other based on what kind of bindings they are.
3189static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3190 const StandardConversionSequence &SCS2) {
3191 // C++0x [over.ics.rank]p3b4:
3192 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3193 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003194 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003195 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003196 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003197 // reference*.
3198 //
3199 // FIXME: Rvalue references. We're going rogue with the above edits,
3200 // because the semantics in the current C++0x working paper (N3225 at the
3201 // time of this writing) break the standard definition of std::forward
3202 // and std::reference_wrapper when dealing with references to functions.
3203 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003204 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3205 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3206 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003207
Douglas Gregor440a4832011-01-26 14:52:12 +00003208 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3209 SCS2.IsLvalueReference) ||
3210 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3211 !SCS2.IsLvalueReference);
3212}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003213
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003214/// CompareStandardConversionSequences - Compare two standard
3215/// conversion sequences to determine whether one is better than the
3216/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003217static ImplicitConversionSequence::CompareKind
3218CompareStandardConversionSequences(Sema &S,
3219 const StandardConversionSequence& SCS1,
3220 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003221{
3222 // Standard conversion sequence S1 is a better conversion sequence
3223 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3224
3225 // -- S1 is a proper subsequence of S2 (comparing the conversion
3226 // sequences in the canonical form defined by 13.3.3.1.1,
3227 // excluding any Lvalue Transformation; the identity conversion
3228 // sequence is considered to be a subsequence of any
3229 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003230 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003231 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003232 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003233
3234 // -- the rank of S1 is better than the rank of S2 (by the rules
3235 // defined below), or, if not that,
3236 ImplicitConversionRank Rank1 = SCS1.getRank();
3237 ImplicitConversionRank Rank2 = SCS2.getRank();
3238 if (Rank1 < Rank2)
3239 return ImplicitConversionSequence::Better;
3240 else if (Rank2 < Rank1)
3241 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003242
Douglas Gregor57373262008-10-22 14:17:15 +00003243 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3244 // are indistinguishable unless one of the following rules
3245 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003246
Douglas Gregor57373262008-10-22 14:17:15 +00003247 // A conversion that is not a conversion of a pointer, or
3248 // pointer to member, to bool is better than another conversion
3249 // that is such a conversion.
3250 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3251 return SCS2.isPointerConversionToBool()
3252 ? ImplicitConversionSequence::Better
3253 : ImplicitConversionSequence::Worse;
3254
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003255 // C++ [over.ics.rank]p4b2:
3256 //
3257 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003258 // conversion of B* to A* is better than conversion of B* to
3259 // void*, and conversion of A* to void* is better than conversion
3260 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003261 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003262 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003263 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003264 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003265 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3266 // Exactly one of the conversion sequences is a conversion to
3267 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003268 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3269 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003270 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3271 // Neither conversion sequence converts to a void pointer; compare
3272 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003273 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003274 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003275 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003276 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3277 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003278 // Both conversion sequences are conversions to void
3279 // pointers. Compare the source types to determine if there's an
3280 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003281 QualType FromType1 = SCS1.getFromType();
3282 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003283
3284 // Adjust the types we're converting from via the array-to-pointer
3285 // conversion, if we need to.
3286 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003287 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003288 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003289 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003290
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003291 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3292 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003293
John McCall120d63c2010-08-24 20:38:10 +00003294 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003295 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003296 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003297 return ImplicitConversionSequence::Worse;
3298
3299 // Objective-C++: If one interface is more specific than the
3300 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003301 const ObjCObjectPointerType* FromObjCPtr1
3302 = FromType1->getAs<ObjCObjectPointerType>();
3303 const ObjCObjectPointerType* FromObjCPtr2
3304 = FromType2->getAs<ObjCObjectPointerType>();
3305 if (FromObjCPtr1 && FromObjCPtr2) {
3306 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3307 FromObjCPtr2);
3308 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3309 FromObjCPtr1);
3310 if (AssignLeft != AssignRight) {
3311 return AssignLeft? ImplicitConversionSequence::Better
3312 : ImplicitConversionSequence::Worse;
3313 }
Douglas Gregor01919692009-12-13 21:37:05 +00003314 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003315 }
Douglas Gregor57373262008-10-22 14:17:15 +00003316
3317 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3318 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003319 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003320 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003321 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003322
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003323 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003324 // Check for a better reference binding based on the kind of bindings.
3325 if (isBetterReferenceBindingKind(SCS1, SCS2))
3326 return ImplicitConversionSequence::Better;
3327 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3328 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003329
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003330 // C++ [over.ics.rank]p3b4:
3331 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3332 // which the references refer are the same type except for
3333 // top-level cv-qualifiers, and the type to which the reference
3334 // initialized by S2 refers is more cv-qualified than the type
3335 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003336 QualType T1 = SCS1.getToType(2);
3337 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003338 T1 = S.Context.getCanonicalType(T1);
3339 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003340 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003341 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3342 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003343 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003344 // Objective-C++ ARC: If the references refer to objects with different
3345 // lifetimes, prefer bindings that don't change lifetime.
3346 if (SCS1.ObjCLifetimeConversionBinding !=
3347 SCS2.ObjCLifetimeConversionBinding) {
3348 return SCS1.ObjCLifetimeConversionBinding
3349 ? ImplicitConversionSequence::Worse
3350 : ImplicitConversionSequence::Better;
3351 }
3352
Chandler Carruth6df868e2010-12-12 08:17:55 +00003353 // If the type is an array type, promote the element qualifiers to the
3354 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003355 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003356 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003357 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003358 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003359 if (T2.isMoreQualifiedThan(T1))
3360 return ImplicitConversionSequence::Better;
3361 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003362 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003363 }
3364 }
Douglas Gregor57373262008-10-22 14:17:15 +00003365
Francois Pichet1c98d622011-09-18 21:37:37 +00003366 // In Microsoft mode, prefer an integral conversion to a
3367 // floating-to-integral conversion if the integral conversion
3368 // is between types of the same size.
3369 // For example:
3370 // void f(float);
3371 // void f(int);
3372 // int main {
3373 // long a;
3374 // f(a);
3375 // }
3376 // Here, MSVC will call f(int) instead of generating a compile error
3377 // as clang will do in standard mode.
3378 if (S.getLangOptions().MicrosoftMode &&
3379 SCS1.Second == ICK_Integral_Conversion &&
3380 SCS2.Second == ICK_Floating_Integral &&
3381 S.Context.getTypeSize(SCS1.getFromType()) ==
3382 S.Context.getTypeSize(SCS1.getToType(2)))
3383 return ImplicitConversionSequence::Better;
3384
Douglas Gregor57373262008-10-22 14:17:15 +00003385 return ImplicitConversionSequence::Indistinguishable;
3386}
3387
3388/// CompareQualificationConversions - Compares two standard conversion
3389/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003390/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3391ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003392CompareQualificationConversions(Sema &S,
3393 const StandardConversionSequence& SCS1,
3394 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003395 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003396 // -- S1 and S2 differ only in their qualification conversion and
3397 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3398 // cv-qualification signature of type T1 is a proper subset of
3399 // the cv-qualification signature of type T2, and S1 is not the
3400 // deprecated string literal array-to-pointer conversion (4.2).
3401 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3402 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3403 return ImplicitConversionSequence::Indistinguishable;
3404
3405 // FIXME: the example in the standard doesn't use a qualification
3406 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003407 QualType T1 = SCS1.getToType(2);
3408 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003409 T1 = S.Context.getCanonicalType(T1);
3410 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003411 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003412 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3413 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003414
3415 // If the types are the same, we won't learn anything by unwrapped
3416 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003417 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003418 return ImplicitConversionSequence::Indistinguishable;
3419
Chandler Carruth28e318c2009-12-29 07:16:59 +00003420 // If the type is an array type, promote the element qualifiers to the type
3421 // for comparison.
3422 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003423 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003424 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003425 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003426
Mike Stump1eb44332009-09-09 15:08:12 +00003427 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003428 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003429
3430 // Objective-C++ ARC:
3431 // Prefer qualification conversions not involving a change in lifetime
3432 // to qualification conversions that do not change lifetime.
3433 if (SCS1.QualificationIncludesObjCLifetime !=
3434 SCS2.QualificationIncludesObjCLifetime) {
3435 Result = SCS1.QualificationIncludesObjCLifetime
3436 ? ImplicitConversionSequence::Worse
3437 : ImplicitConversionSequence::Better;
3438 }
3439
John McCall120d63c2010-08-24 20:38:10 +00003440 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003441 // Within each iteration of the loop, we check the qualifiers to
3442 // determine if this still looks like a qualification
3443 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003444 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003445 // until there are no more pointers or pointers-to-members left
3446 // to unwrap. This essentially mimics what
3447 // IsQualificationConversion does, but here we're checking for a
3448 // strict subset of qualifiers.
3449 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3450 // The qualifiers are the same, so this doesn't tell us anything
3451 // about how the sequences rank.
3452 ;
3453 else if (T2.isMoreQualifiedThan(T1)) {
3454 // T1 has fewer qualifiers, so it could be the better sequence.
3455 if (Result == ImplicitConversionSequence::Worse)
3456 // Neither has qualifiers that are a subset of the other's
3457 // qualifiers.
3458 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003459
Douglas Gregor57373262008-10-22 14:17:15 +00003460 Result = ImplicitConversionSequence::Better;
3461 } else if (T1.isMoreQualifiedThan(T2)) {
3462 // T2 has fewer qualifiers, so it could be the better sequence.
3463 if (Result == ImplicitConversionSequence::Better)
3464 // Neither has qualifiers that are a subset of the other's
3465 // qualifiers.
3466 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Douglas Gregor57373262008-10-22 14:17:15 +00003468 Result = ImplicitConversionSequence::Worse;
3469 } else {
3470 // Qualifiers are disjoint.
3471 return ImplicitConversionSequence::Indistinguishable;
3472 }
3473
3474 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003475 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003476 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003477 }
3478
Douglas Gregor57373262008-10-22 14:17:15 +00003479 // Check that the winning standard conversion sequence isn't using
3480 // the deprecated string literal array to pointer conversion.
3481 switch (Result) {
3482 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003483 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003484 Result = ImplicitConversionSequence::Indistinguishable;
3485 break;
3486
3487 case ImplicitConversionSequence::Indistinguishable:
3488 break;
3489
3490 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003491 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003492 Result = ImplicitConversionSequence::Indistinguishable;
3493 break;
3494 }
3495
3496 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003497}
3498
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003499/// CompareDerivedToBaseConversions - Compares two standard conversion
3500/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003501/// various kinds of derived-to-base conversions (C++
3502/// [over.ics.rank]p4b3). As part of these checks, we also look at
3503/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003504ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003505CompareDerivedToBaseConversions(Sema &S,
3506 const StandardConversionSequence& SCS1,
3507 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003508 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003509 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003510 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003511 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003512
3513 // Adjust the types we're converting from via the array-to-pointer
3514 // conversion, if we need to.
3515 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003516 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003517 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003518 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003519
3520 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003521 FromType1 = S.Context.getCanonicalType(FromType1);
3522 ToType1 = S.Context.getCanonicalType(ToType1);
3523 FromType2 = S.Context.getCanonicalType(FromType2);
3524 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003525
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003526 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003527 //
3528 // If class B is derived directly or indirectly from class A and
3529 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003530 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003531 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003532 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003533 SCS2.Second == ICK_Pointer_Conversion &&
3534 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3535 FromType1->isPointerType() && FromType2->isPointerType() &&
3536 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003537 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003538 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003539 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003540 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003541 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003542 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003543 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003544 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003545
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003546 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003547 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003548 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003549 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003550 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003551 return ImplicitConversionSequence::Worse;
3552 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003553
3554 // -- conversion of B* to A* is better than conversion of C* to A*,
3555 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003556 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003557 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003558 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003559 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003560 }
3561 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3562 SCS2.Second == ICK_Pointer_Conversion) {
3563 const ObjCObjectPointerType *FromPtr1
3564 = FromType1->getAs<ObjCObjectPointerType>();
3565 const ObjCObjectPointerType *FromPtr2
3566 = FromType2->getAs<ObjCObjectPointerType>();
3567 const ObjCObjectPointerType *ToPtr1
3568 = ToType1->getAs<ObjCObjectPointerType>();
3569 const ObjCObjectPointerType *ToPtr2
3570 = ToType2->getAs<ObjCObjectPointerType>();
3571
3572 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3573 // Apply the same conversion ranking rules for Objective-C pointer types
3574 // that we do for C++ pointers to class types. However, we employ the
3575 // Objective-C pseudo-subtyping relationship used for assignment of
3576 // Objective-C pointer types.
3577 bool FromAssignLeft
3578 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3579 bool FromAssignRight
3580 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3581 bool ToAssignLeft
3582 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3583 bool ToAssignRight
3584 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3585
3586 // A conversion to an a non-id object pointer type or qualified 'id'
3587 // type is better than a conversion to 'id'.
3588 if (ToPtr1->isObjCIdType() &&
3589 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3590 return ImplicitConversionSequence::Worse;
3591 if (ToPtr2->isObjCIdType() &&
3592 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3593 return ImplicitConversionSequence::Better;
3594
3595 // A conversion to a non-id object pointer type is better than a
3596 // conversion to a qualified 'id' type
3597 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3598 return ImplicitConversionSequence::Worse;
3599 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3600 return ImplicitConversionSequence::Better;
3601
3602 // A conversion to an a non-Class object pointer type or qualified 'Class'
3603 // type is better than a conversion to 'Class'.
3604 if (ToPtr1->isObjCClassType() &&
3605 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3606 return ImplicitConversionSequence::Worse;
3607 if (ToPtr2->isObjCClassType() &&
3608 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3609 return ImplicitConversionSequence::Better;
3610
3611 // A conversion to a non-Class object pointer type is better than a
3612 // conversion to a qualified 'Class' type.
3613 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3614 return ImplicitConversionSequence::Worse;
3615 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3616 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003617
Douglas Gregor395cc372011-01-31 18:51:41 +00003618 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3619 if (S.Context.hasSameType(FromType1, FromType2) &&
3620 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3621 (ToAssignLeft != ToAssignRight))
3622 return ToAssignLeft? ImplicitConversionSequence::Worse
3623 : ImplicitConversionSequence::Better;
3624
3625 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3626 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3627 (FromAssignLeft != FromAssignRight))
3628 return FromAssignLeft? ImplicitConversionSequence::Better
3629 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003630 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003631 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003632
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003633 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003634 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3635 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3636 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003637 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003638 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003639 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003640 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003641 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003642 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003643 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003644 ToType2->getAs<MemberPointerType>();
3645 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3646 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3647 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3648 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3649 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3650 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3651 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3652 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003653 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003654 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003655 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003656 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003657 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003658 return ImplicitConversionSequence::Better;
3659 }
3660 // conversion of B::* to C::* is better than conversion of A::* to C::*
3661 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003662 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003663 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003664 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003665 return ImplicitConversionSequence::Worse;
3666 }
3667 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003668
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003669 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003670 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003671 // -- binding of an expression of type C to a reference of type
3672 // B& is better than binding an expression of type C to a
3673 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003674 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3675 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3676 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003677 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003678 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003679 return ImplicitConversionSequence::Worse;
3680 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003681
Douglas Gregor225c41e2008-11-03 19:09:14 +00003682 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003683 // -- binding of an expression of type B to a reference of type
3684 // A& is better than binding an expression of type C to a
3685 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003686 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3687 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3688 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003689 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003690 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003691 return ImplicitConversionSequence::Worse;
3692 }
3693 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003694
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003695 return ImplicitConversionSequence::Indistinguishable;
3696}
3697
Douglas Gregorabe183d2010-04-13 16:31:36 +00003698/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3699/// determine whether they are reference-related,
3700/// reference-compatible, reference-compatible with added
3701/// qualification, or incompatible, for use in C++ initialization by
3702/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3703/// type, and the first type (T1) is the pointee type of the reference
3704/// type being initialized.
3705Sema::ReferenceCompareResult
3706Sema::CompareReferenceRelationship(SourceLocation Loc,
3707 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003708 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003709 bool &ObjCConversion,
3710 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003711 assert(!OrigT1->isReferenceType() &&
3712 "T1 must be the pointee type of the reference type");
3713 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3714
3715 QualType T1 = Context.getCanonicalType(OrigT1);
3716 QualType T2 = Context.getCanonicalType(OrigT2);
3717 Qualifiers T1Quals, T2Quals;
3718 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3719 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3720
3721 // C++ [dcl.init.ref]p4:
3722 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3723 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3724 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003725 DerivedToBase = false;
3726 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003727 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003728 if (UnqualT1 == UnqualT2) {
3729 // Nothing to do.
3730 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003731 IsDerivedFrom(UnqualT2, UnqualT1))
3732 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003733 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3734 UnqualT2->isObjCObjectOrInterfaceType() &&
3735 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3736 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003737 else
3738 return Ref_Incompatible;
3739
3740 // At this point, we know that T1 and T2 are reference-related (at
3741 // least).
3742
3743 // If the type is an array type, promote the element qualifiers to the type
3744 // for comparison.
3745 if (isa<ArrayType>(T1) && T1Quals)
3746 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3747 if (isa<ArrayType>(T2) && T2Quals)
3748 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3749
3750 // C++ [dcl.init.ref]p4:
3751 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3752 // reference-related to T2 and cv1 is the same cv-qualification
3753 // as, or greater cv-qualification than, cv2. For purposes of
3754 // overload resolution, cases for which cv1 is greater
3755 // cv-qualification than cv2 are identified as
3756 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003757 //
3758 // Note that we also require equivalence of Objective-C GC and address-space
3759 // qualifiers when performing these computations, so that e.g., an int in
3760 // address space 1 is not reference-compatible with an int in address
3761 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003762 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3763 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3764 T1Quals.removeObjCLifetime();
3765 T2Quals.removeObjCLifetime();
3766 ObjCLifetimeConversion = true;
3767 }
3768
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003769 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003770 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003771 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003772 return Ref_Compatible_With_Added_Qualification;
3773 else
3774 return Ref_Related;
3775}
3776
Douglas Gregor604eb652010-08-11 02:15:33 +00003777/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003778/// with DeclType. Return true if something definite is found.
3779static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003780FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3781 QualType DeclType, SourceLocation DeclLoc,
3782 Expr *Init, QualType T2, bool AllowRvalues,
3783 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003784 assert(T2->isRecordType() && "Can only find conversions of record types.");
3785 CXXRecordDecl *T2RecordDecl
3786 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3787
3788 OverloadCandidateSet CandidateSet(DeclLoc);
3789 const UnresolvedSetImpl *Conversions
3790 = T2RecordDecl->getVisibleConversionFunctions();
3791 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3792 E = Conversions->end(); I != E; ++I) {
3793 NamedDecl *D = *I;
3794 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3795 if (isa<UsingShadowDecl>(D))
3796 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3797
3798 FunctionTemplateDecl *ConvTemplate
3799 = dyn_cast<FunctionTemplateDecl>(D);
3800 CXXConversionDecl *Conv;
3801 if (ConvTemplate)
3802 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3803 else
3804 Conv = cast<CXXConversionDecl>(D);
3805
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003806 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003807 // explicit conversions, skip it.
3808 if (!AllowExplicit && Conv->isExplicit())
3809 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003810
Douglas Gregor604eb652010-08-11 02:15:33 +00003811 if (AllowRvalues) {
3812 bool DerivedToBase = false;
3813 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003814 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00003815
3816 // If we are initializing an rvalue reference, don't permit conversion
3817 // functions that return lvalues.
3818 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3819 const ReferenceType *RefType
3820 = Conv->getConversionType()->getAs<LValueReferenceType>();
3821 if (RefType && !RefType->getPointeeType()->isFunctionType())
3822 continue;
3823 }
3824
Douglas Gregor604eb652010-08-11 02:15:33 +00003825 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00003826 S.CompareReferenceRelationship(
3827 DeclLoc,
3828 Conv->getConversionType().getNonReferenceType()
3829 .getUnqualifiedType(),
3830 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00003831 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00003832 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00003833 continue;
3834 } else {
3835 // If the conversion function doesn't return a reference type,
3836 // it can't be considered for this conversion. An rvalue reference
3837 // is only acceptable if its referencee is a function type.
3838
3839 const ReferenceType *RefType =
3840 Conv->getConversionType()->getAs<ReferenceType>();
3841 if (!RefType ||
3842 (!RefType->isLValueReferenceType() &&
3843 !RefType->getPointeeType()->isFunctionType()))
3844 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003845 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003846
Douglas Gregor604eb652010-08-11 02:15:33 +00003847 if (ConvTemplate)
3848 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003849 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00003850 else
3851 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003852 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003853 }
3854
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003855 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3856
Sebastian Redl4680bf22010-06-30 18:13:39 +00003857 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003858 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003859 case OR_Success:
3860 // C++ [over.ics.ref]p1:
3861 //
3862 // [...] If the parameter binds directly to the result of
3863 // applying a conversion function to the argument
3864 // expression, the implicit conversion sequence is a
3865 // user-defined conversion sequence (13.3.3.1.2), with the
3866 // second standard conversion sequence either an identity
3867 // conversion or, if the conversion function returns an
3868 // entity of a type that is a derived class of the parameter
3869 // type, a derived-to-base Conversion.
3870 if (!Best->FinalConversion.DirectBinding)
3871 return false;
3872
Chandler Carruth25ca4212011-02-25 19:41:05 +00003873 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00003874 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003875 ICS.setUserDefined();
3876 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3877 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003878 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003879 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00003880 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003881 ICS.UserDefined.EllipsisConversion = false;
3882 assert(ICS.UserDefined.After.ReferenceBinding &&
3883 ICS.UserDefined.After.DirectBinding &&
3884 "Expected a direct reference binding!");
3885 return true;
3886
3887 case OR_Ambiguous:
3888 ICS.setAmbiguous();
3889 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3890 Cand != CandidateSet.end(); ++Cand)
3891 if (Cand->Viable)
3892 ICS.Ambiguous.addConversion(Cand->Function);
3893 return true;
3894
3895 case OR_No_Viable_Function:
3896 case OR_Deleted:
3897 // There was no suitable conversion, or we found a deleted
3898 // conversion; continue with other checks.
3899 return false;
3900 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003901
David Blaikie7530c032012-01-17 06:56:22 +00003902 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00003903}
3904
Douglas Gregorabe183d2010-04-13 16:31:36 +00003905/// \brief Compute an implicit conversion sequence for reference
3906/// initialization.
3907static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00003908TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003909 SourceLocation DeclLoc,
3910 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003911 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003912 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3913
3914 // Most paths end in a failed conversion.
3915 ImplicitConversionSequence ICS;
3916 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3917
3918 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3919 QualType T2 = Init->getType();
3920
3921 // If the initializer is the address of an overloaded function, try
3922 // to resolve the overloaded function. If all goes well, T2 is the
3923 // type of the resulting function.
3924 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3925 DeclAccessPair Found;
3926 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3927 false, Found))
3928 T2 = Fn->getType();
3929 }
3930
3931 // Compute some basic properties of the types and the initializer.
3932 bool isRValRef = DeclType->isRValueReferenceType();
3933 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003934 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003935 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003936 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003937 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003938 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003939 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003940
Douglas Gregorabe183d2010-04-13 16:31:36 +00003941
Sebastian Redl4680bf22010-06-30 18:13:39 +00003942 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00003943 // A reference to type "cv1 T1" is initialized by an expression
3944 // of type "cv2 T2" as follows:
3945
Sebastian Redl4680bf22010-06-30 18:13:39 +00003946 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003947 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003948 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3949 // reference-compatible with "cv2 T2," or
3950 //
3951 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3952 if (InitCategory.isLValue() &&
3953 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003954 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00003955 // When a parameter of reference type binds directly (8.5.3)
3956 // to an argument expression, the implicit conversion sequence
3957 // is the identity conversion, unless the argument expression
3958 // has a type that is a derived class of the parameter type,
3959 // in which case the implicit conversion sequence is a
3960 // derived-to-base Conversion (13.3.3.1).
3961 ICS.setStandard();
3962 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00003963 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3964 : ObjCConversion? ICK_Compatible_Conversion
3965 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003966 ICS.Standard.Third = ICK_Identity;
3967 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3968 ICS.Standard.setToType(0, T2);
3969 ICS.Standard.setToType(1, T1);
3970 ICS.Standard.setToType(2, T1);
3971 ICS.Standard.ReferenceBinding = true;
3972 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003973 ICS.Standard.IsLvalueReference = !isRValRef;
3974 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3975 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003976 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003977 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003978 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003979
Sebastian Redl4680bf22010-06-30 18:13:39 +00003980 // Nothing more to do: the inaccessibility/ambiguity check for
3981 // derived-to-base conversions is suppressed when we're
3982 // computing the implicit conversion sequence (C++
3983 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00003984 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003985 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00003986
Sebastian Redl4680bf22010-06-30 18:13:39 +00003987 // -- has a class type (i.e., T2 is a class type), where T1 is
3988 // not reference-related to T2, and can be implicitly
3989 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3990 // is reference-compatible with "cv3 T3" 92) (this
3991 // conversion is selected by enumerating the applicable
3992 // conversion functions (13.3.1.6) and choosing the best
3993 // one through overload resolution (13.3)),
3994 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003995 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00003996 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00003997 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3998 Init, T2, /*AllowRvalues=*/false,
3999 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004000 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004001 }
4002 }
4003
Sebastian Redl4680bf22010-06-30 18:13:39 +00004004 // -- Otherwise, the reference shall be an lvalue reference to a
4005 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004006 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004007 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004008 // We actually handle one oddity of C++ [over.ics.ref] at this
4009 // point, which is that, due to p2 (which short-circuits reference
4010 // binding by only attempting a simple conversion for non-direct
4011 // bindings) and p3's strange wording, we allow a const volatile
4012 // reference to bind to an rvalue. Hence the check for the presence
4013 // of "const" rather than checking for "const" being the only
4014 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004015 // This is also the point where rvalue references and lvalue inits no longer
4016 // go together.
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004017 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00004018 return ICS;
4019
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004020 // -- If the initializer expression
4021 //
4022 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004023 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004024 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4025 (InitCategory.isXValue() ||
4026 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4027 (InitCategory.isLValue() && T2->isFunctionType()))) {
4028 ICS.setStandard();
4029 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004030 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004031 : ObjCConversion? ICK_Compatible_Conversion
4032 : ICK_Identity;
4033 ICS.Standard.Third = ICK_Identity;
4034 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4035 ICS.Standard.setToType(0, T2);
4036 ICS.Standard.setToType(1, T1);
4037 ICS.Standard.setToType(2, T1);
4038 ICS.Standard.ReferenceBinding = true;
4039 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4040 // binding unless we're binding to a class prvalue.
4041 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4042 // allow the use of rvalue references in C++98/03 for the benefit of
4043 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004044 ICS.Standard.DirectBinding =
4045 S.getLangOptions().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004046 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004047 ICS.Standard.IsLvalueReference = !isRValRef;
4048 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004049 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004050 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004051 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004052 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004053 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004054 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004055
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004056 // -- has a class type (i.e., T2 is a class type), where T1 is not
4057 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004058 // an xvalue, class prvalue, or function lvalue of type
4059 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004060 // "cv3 T3",
4061 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004062 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004063 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004064 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004065 // class subobject).
4066 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004067 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004068 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4069 Init, T2, /*AllowRvalues=*/true,
4070 AllowExplicit)) {
4071 // In the second case, if the reference is an rvalue reference
4072 // and the second standard conversion sequence of the
4073 // user-defined conversion sequence includes an lvalue-to-rvalue
4074 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004075 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004076 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4077 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4078
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004079 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004080 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004081
Douglas Gregorabe183d2010-04-13 16:31:36 +00004082 // -- Otherwise, a temporary of type "cv1 T1" is created and
4083 // initialized from the initializer expression using the
4084 // rules for a non-reference copy initialization (8.5). The
4085 // reference is then bound to the temporary. If T1 is
4086 // reference-related to T2, cv1 must be the same
4087 // cv-qualification as, or greater cv-qualification than,
4088 // cv2; otherwise, the program is ill-formed.
4089 if (RefRelationship == Sema::Ref_Related) {
4090 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4091 // we would be reference-compatible or reference-compatible with
4092 // added qualification. But that wasn't the case, so the reference
4093 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004094 //
4095 // Note that we only want to check address spaces and cvr-qualifiers here.
4096 // ObjC GC and lifetime qualifiers aren't important.
4097 Qualifiers T1Quals = T1.getQualifiers();
4098 Qualifiers T2Quals = T2.getQualifiers();
4099 T1Quals.removeObjCGCAttr();
4100 T1Quals.removeObjCLifetime();
4101 T2Quals.removeObjCGCAttr();
4102 T2Quals.removeObjCLifetime();
4103 if (!T1Quals.compatiblyIncludes(T2Quals))
4104 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004105 }
4106
4107 // If at least one of the types is a class type, the types are not
4108 // related, and we aren't allowed any user conversions, the
4109 // reference binding fails. This case is important for breaking
4110 // recursion, since TryImplicitConversion below will attempt to
4111 // create a temporary through the use of a copy constructor.
4112 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4113 (T1->isRecordType() || T2->isRecordType()))
4114 return ICS;
4115
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004116 // If T1 is reference-related to T2 and the reference is an rvalue
4117 // reference, the initializer expression shall not be an lvalue.
4118 if (RefRelationship >= Sema::Ref_Related &&
4119 isRValRef && Init->Classify(S.Context).isLValue())
4120 return ICS;
4121
Douglas Gregorabe183d2010-04-13 16:31:36 +00004122 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004123 // When a parameter of reference type is not bound directly to
4124 // an argument expression, the conversion sequence is the one
4125 // required to convert the argument expression to the
4126 // underlying type of the reference according to
4127 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4128 // to copy-initializing a temporary of the underlying type with
4129 // the argument expression. Any difference in top-level
4130 // cv-qualification is subsumed by the initialization itself
4131 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004132 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4133 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004134 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004135 /*CStyle=*/false,
4136 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004137
4138 // Of course, that's still a reference binding.
4139 if (ICS.isStandard()) {
4140 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004141 ICS.Standard.IsLvalueReference = !isRValRef;
4142 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4143 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004144 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004145 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004146 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004147 // Don't allow rvalue references to bind to lvalues.
4148 if (DeclType->isRValueReferenceType()) {
4149 if (const ReferenceType *RefType
4150 = ICS.UserDefined.ConversionFunction->getResultType()
4151 ->getAs<LValueReferenceType>()) {
4152 if (!RefType->getPointeeType()->isFunctionType()) {
4153 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4154 DeclType);
4155 return ICS;
4156 }
4157 }
4158 }
4159
Douglas Gregorabe183d2010-04-13 16:31:36 +00004160 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004161 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4162 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4163 ICS.UserDefined.After.BindsToRvalue = true;
4164 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4165 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004166 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004167
Douglas Gregorabe183d2010-04-13 16:31:36 +00004168 return ICS;
4169}
4170
Sebastian Redl5405b812011-10-16 18:19:34 +00004171static ImplicitConversionSequence
4172TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4173 bool SuppressUserConversions,
4174 bool InOverloadResolution,
4175 bool AllowObjCWritebackConversion);
4176
4177/// TryListConversion - Try to copy-initialize a value of type ToType from the
4178/// initializer list From.
4179static ImplicitConversionSequence
4180TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4181 bool SuppressUserConversions,
4182 bool InOverloadResolution,
4183 bool AllowObjCWritebackConversion) {
4184 // C++11 [over.ics.list]p1:
4185 // When an argument is an initializer list, it is not an expression and
4186 // special rules apply for converting it to a parameter type.
4187
4188 ImplicitConversionSequence Result;
4189 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004190 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004191
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004192 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004193 // initialized from init lists.
4194 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()))
4195 return Result;
4196
Sebastian Redl5405b812011-10-16 18:19:34 +00004197 // C++11 [over.ics.list]p2:
4198 // If the parameter type is std::initializer_list<X> or "array of X" and
4199 // all the elements can be implicitly converted to X, the implicit
4200 // conversion sequence is the worst conversion necessary to convert an
4201 // element of the list to X.
Sebastian Redlfe592282012-01-17 22:49:48 +00004202 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004203 if (ToType->isArrayType())
Sebastian Redlfe592282012-01-17 22:49:48 +00004204 X = S.Context.getBaseElementType(ToType);
4205 else
4206 (void)S.isStdInitializerList(ToType, &X);
4207 if (!X.isNull()) {
4208 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4209 Expr *Init = From->getInit(i);
4210 ImplicitConversionSequence ICS =
4211 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4212 InOverloadResolution,
4213 AllowObjCWritebackConversion);
4214 // If a single element isn't convertible, fail.
4215 if (ICS.isBad()) {
4216 Result = ICS;
4217 break;
4218 }
4219 // Otherwise, look for the worst conversion.
4220 if (Result.isBad() ||
4221 CompareImplicitConversionSequences(S, ICS, Result) ==
4222 ImplicitConversionSequence::Worse)
4223 Result = ICS;
4224 }
4225 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004226 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004227 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004228
4229 // C++11 [over.ics.list]p3:
4230 // Otherwise, if the parameter is a non-aggregate class X and overload
4231 // resolution chooses a single best constructor [...] the implicit
4232 // conversion sequence is a user-defined conversion sequence. If multiple
4233 // constructors are viable but none is better than the others, the
4234 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004235 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4236 // This function can deal with initializer lists.
4237 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4238 /*AllowExplicit=*/false,
4239 InOverloadResolution, /*CStyle=*/false,
4240 AllowObjCWritebackConversion);
4241 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004242 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004243 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004244
4245 // C++11 [over.ics.list]p4:
4246 // Otherwise, if the parameter has an aggregate type which can be
4247 // initialized from the initializer list [...] the implicit conversion
4248 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004249 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004250 // Type is an aggregate, argument is an init list. At this point it comes
4251 // down to checking whether the initialization works.
4252 // FIXME: Find out whether this parameter is consumed or not.
4253 InitializedEntity Entity =
4254 InitializedEntity::InitializeParameter(S.Context, ToType,
4255 /*Consumed=*/false);
4256 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4257 Result.setUserDefined();
4258 Result.UserDefined.Before.setAsIdentityConversion();
4259 // Initializer lists don't have a type.
4260 Result.UserDefined.Before.setFromType(QualType());
4261 Result.UserDefined.Before.setAllToTypes(QualType());
4262
4263 Result.UserDefined.After.setAsIdentityConversion();
4264 Result.UserDefined.After.setFromType(ToType);
4265 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004266 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004267 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004268 return Result;
4269 }
4270
4271 // C++11 [over.ics.list]p5:
4272 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004273 if (ToType->isReferenceType()) {
4274 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4275 // mention initializer lists in any way. So we go by what list-
4276 // initialization would do and try to extrapolate from that.
4277
4278 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4279
4280 // If the initializer list has a single element that is reference-related
4281 // to the parameter type, we initialize the reference from that.
4282 if (From->getNumInits() == 1) {
4283 Expr *Init = From->getInit(0);
4284
4285 QualType T2 = Init->getType();
4286
4287 // If the initializer is the address of an overloaded function, try
4288 // to resolve the overloaded function. If all goes well, T2 is the
4289 // type of the resulting function.
4290 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4291 DeclAccessPair Found;
4292 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4293 Init, ToType, false, Found))
4294 T2 = Fn->getType();
4295 }
4296
4297 // Compute some basic properties of the types and the initializer.
4298 bool dummy1 = false;
4299 bool dummy2 = false;
4300 bool dummy3 = false;
4301 Sema::ReferenceCompareResult RefRelationship
4302 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4303 dummy2, dummy3);
4304
4305 if (RefRelationship >= Sema::Ref_Related)
4306 return TryReferenceInit(S, Init, ToType,
4307 /*FIXME:*/From->getLocStart(),
4308 SuppressUserConversions,
4309 /*AllowExplicit=*/false);
4310 }
4311
4312 // Otherwise, we bind the reference to a temporary created from the
4313 // initializer list.
4314 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4315 InOverloadResolution,
4316 AllowObjCWritebackConversion);
4317 if (Result.isFailure())
4318 return Result;
4319 assert(!Result.isEllipsis() &&
4320 "Sub-initialization cannot result in ellipsis conversion.");
4321
4322 // Can we even bind to a temporary?
4323 if (ToType->isRValueReferenceType() ||
4324 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4325 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4326 Result.UserDefined.After;
4327 SCS.ReferenceBinding = true;
4328 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4329 SCS.BindsToRvalue = true;
4330 SCS.BindsToFunctionLvalue = false;
4331 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4332 SCS.ObjCLifetimeConversionBinding = false;
4333 } else
4334 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4335 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004336 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004337 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004338
4339 // C++11 [over.ics.list]p6:
4340 // Otherwise, if the parameter type is not a class:
4341 if (!ToType->isRecordType()) {
4342 // - if the initializer list has one element, the implicit conversion
4343 // sequence is the one required to convert the element to the
4344 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004345 unsigned NumInits = From->getNumInits();
4346 if (NumInits == 1)
4347 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4348 SuppressUserConversions,
4349 InOverloadResolution,
4350 AllowObjCWritebackConversion);
4351 // - if the initializer list has no elements, the implicit conversion
4352 // sequence is the identity conversion.
4353 else if (NumInits == 0) {
4354 Result.setStandard();
4355 Result.Standard.setAsIdentityConversion();
4356 }
4357 return Result;
4358 }
4359
4360 // C++11 [over.ics.list]p7:
4361 // In all cases other than those enumerated above, no conversion is possible
4362 return Result;
4363}
4364
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004365/// TryCopyInitialization - Try to copy-initialize a value of type
4366/// ToType from the expression From. Return the implicit conversion
4367/// sequence required to pass this argument, which may be a bad
4368/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004369/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004370/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004371static ImplicitConversionSequence
4372TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004373 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004374 bool InOverloadResolution,
4375 bool AllowObjCWritebackConversion) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004376 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4377 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4378 InOverloadResolution,AllowObjCWritebackConversion);
4379
Douglas Gregorabe183d2010-04-13 16:31:36 +00004380 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004381 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004382 /*FIXME:*/From->getLocStart(),
4383 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004384 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004385
John McCall120d63c2010-08-24 20:38:10 +00004386 return TryImplicitConversion(S, From, ToType,
4387 SuppressUserConversions,
4388 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004389 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004390 /*CStyle=*/false,
4391 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004392}
4393
Anna Zaksf3546ee2011-07-28 19:46:48 +00004394static bool TryCopyInitialization(const CanQualType FromQTy,
4395 const CanQualType ToQTy,
4396 Sema &S,
4397 SourceLocation Loc,
4398 ExprValueKind FromVK) {
4399 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4400 ImplicitConversionSequence ICS =
4401 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4402
4403 return !ICS.isBad();
4404}
4405
Douglas Gregor96176b32008-11-18 23:14:02 +00004406/// TryObjectArgumentInitialization - Try to initialize the object
4407/// parameter of the given member function (@c Method) from the
4408/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004409static ImplicitConversionSequence
4410TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004411 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004412 CXXMethodDecl *Method,
4413 CXXRecordDecl *ActingContext) {
4414 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004415 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4416 // const volatile object.
4417 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4418 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004419 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004420
4421 // Set up the conversion sequence as a "bad" conversion, to allow us
4422 // to exit early.
4423 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004424
4425 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00004426 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004427 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004428 FromType = PT->getPointeeType();
4429
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004430 // When we had a pointer, it's implicitly dereferenced, so we
4431 // better have an lvalue.
4432 assert(FromClassification.isLValue());
4433 }
4434
Anders Carlssona552f7c2009-05-01 18:34:30 +00004435 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004436
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004437 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004438 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004439 // parameter is
4440 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004441 // - "lvalue reference to cv X" for functions declared without a
4442 // ref-qualifier or with the & ref-qualifier
4443 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004444 // ref-qualifier
4445 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004446 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004447 // cv-qualification on the member function declaration.
4448 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004449 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004450 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004451 // (C++ [over.match.funcs]p5). We perform a simplified version of
4452 // reference binding here, that allows class rvalues to bind to
4453 // non-constant references.
4454
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004455 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004456 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004457 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004458 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004459 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004460 ICS.setBad(BadConversionSequence::bad_qualifiers,
4461 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004462 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004463 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004464
4465 // Check that we have either the same type or a derived type. It
4466 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004467 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004468 ImplicitConversionKind SecondKind;
4469 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4470 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004471 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004472 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004473 else {
John McCallb1bdc622010-02-25 01:37:24 +00004474 ICS.setBad(BadConversionSequence::unrelated_class,
4475 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004476 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004477 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004478
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004479 // Check the ref-qualifier.
4480 switch (Method->getRefQualifier()) {
4481 case RQ_None:
4482 // Do nothing; we don't care about lvalueness or rvalueness.
4483 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004484
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004485 case RQ_LValue:
4486 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4487 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004488 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004489 ImplicitParamType);
4490 return ICS;
4491 }
4492 break;
4493
4494 case RQ_RValue:
4495 if (!FromClassification.isRValue()) {
4496 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004497 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004498 ImplicitParamType);
4499 return ICS;
4500 }
4501 break;
4502 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004503
Douglas Gregor96176b32008-11-18 23:14:02 +00004504 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004505 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004506 ICS.Standard.setAsIdentityConversion();
4507 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004508 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004509 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004510 ICS.Standard.ReferenceBinding = true;
4511 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004512 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004513 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004514 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4515 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4516 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004517 return ICS;
4518}
4519
4520/// PerformObjectArgumentInitialization - Perform initialization of
4521/// the implicit object parameter for the given Method with the given
4522/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004523ExprResult
4524Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004525 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004526 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004527 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004528 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004529 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004530 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004531
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004532 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004533 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004534 FromRecordType = PT->getPointeeType();
4535 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004536 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004537 } else {
4538 FromRecordType = From->getType();
4539 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004540 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004541 }
4542
John McCall701c89e2009-12-03 04:06:58 +00004543 // Note that we always use the true parent context when performing
4544 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004545 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004546 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4547 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004548 if (ICS.isBad()) {
4549 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4550 Qualifiers FromQs = FromRecordType.getQualifiers();
4551 Qualifiers ToQs = DestType.getQualifiers();
4552 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4553 if (CVR) {
4554 Diag(From->getSourceRange().getBegin(),
4555 diag::err_member_function_call_bad_cvr)
4556 << Method->getDeclName() << FromRecordType << (CVR - 1)
4557 << From->getSourceRange();
4558 Diag(Method->getLocation(), diag::note_previous_decl)
4559 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004560 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004561 }
4562 }
4563
Douglas Gregor96176b32008-11-18 23:14:02 +00004564 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004565 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004566 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004567 }
Mike Stump1eb44332009-09-09 15:08:12 +00004568
John Wiegley429bb272011-04-08 18:41:53 +00004569 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4570 ExprResult FromRes =
4571 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4572 if (FromRes.isInvalid())
4573 return ExprError();
4574 From = FromRes.take();
4575 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004576
Douglas Gregor5fccd362010-03-03 23:55:11 +00004577 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004578 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004579 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004580 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004581}
4582
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004583/// TryContextuallyConvertToBool - Attempt to contextually convert the
4584/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004585static ImplicitConversionSequence
4586TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004587 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004588 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004589 // FIXME: Are these flags correct?
4590 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004591 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004592 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004593 /*CStyle=*/false,
4594 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004595}
4596
4597/// PerformContextuallyConvertToBool - Perform a contextual conversion
4598/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004599ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004600 if (checkPlaceholderForOverload(*this, From))
4601 return ExprError();
4602
John McCall120d63c2010-08-24 20:38:10 +00004603 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004604 if (!ICS.isBad())
4605 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004606
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004607 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall864c0412011-04-26 20:42:42 +00004608 return Diag(From->getSourceRange().getBegin(),
4609 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004610 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004611 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004612}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004613
Richard Smith8ef7b202012-01-18 23:55:52 +00004614/// Check that the specified conversion is permitted in a converted constant
4615/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4616/// is acceptable.
4617static bool CheckConvertedConstantConversions(Sema &S,
4618 StandardConversionSequence &SCS) {
4619 // Since we know that the target type is an integral or unscoped enumeration
4620 // type, most conversion kinds are impossible. All possible First and Third
4621 // conversions are fine.
4622 switch (SCS.Second) {
4623 case ICK_Identity:
4624 case ICK_Integral_Promotion:
4625 case ICK_Integral_Conversion:
4626 return true;
4627
4628 case ICK_Boolean_Conversion:
4629 // Conversion from an integral or unscoped enumeration type to bool is
4630 // classified as ICK_Boolean_Conversion, but it's also an integral
4631 // conversion, so it's permitted in a converted constant expression.
4632 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4633 SCS.getToType(2)->isBooleanType();
4634
4635 case ICK_Floating_Integral:
4636 case ICK_Complex_Real:
4637 return false;
4638
4639 case ICK_Lvalue_To_Rvalue:
4640 case ICK_Array_To_Pointer:
4641 case ICK_Function_To_Pointer:
4642 case ICK_NoReturn_Adjustment:
4643 case ICK_Qualification:
4644 case ICK_Compatible_Conversion:
4645 case ICK_Vector_Conversion:
4646 case ICK_Vector_Splat:
4647 case ICK_Derived_To_Base:
4648 case ICK_Pointer_Conversion:
4649 case ICK_Pointer_Member:
4650 case ICK_Block_Pointer_Conversion:
4651 case ICK_Writeback_Conversion:
4652 case ICK_Floating_Promotion:
4653 case ICK_Complex_Promotion:
4654 case ICK_Complex_Conversion:
4655 case ICK_Floating_Conversion:
4656 case ICK_TransparentUnionConversion:
4657 llvm_unreachable("unexpected second conversion kind");
4658
4659 case ICK_Num_Conversion_Kinds:
4660 break;
4661 }
4662
4663 llvm_unreachable("unknown conversion kind");
4664}
4665
4666/// CheckConvertedConstantExpression - Check that the expression From is a
4667/// converted constant expression of type T, perform the conversion and produce
4668/// the converted expression, per C++11 [expr.const]p3.
4669ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4670 llvm::APSInt &Value,
4671 CCEKind CCE) {
4672 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4673 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4674
4675 if (checkPlaceholderForOverload(*this, From))
4676 return ExprError();
4677
4678 // C++11 [expr.const]p3 with proposed wording fixes:
4679 // A converted constant expression of type T is a core constant expression,
4680 // implicitly converted to a prvalue of type T, where the converted
4681 // expression is a literal constant expression and the implicit conversion
4682 // sequence contains only user-defined conversions, lvalue-to-rvalue
4683 // conversions, integral promotions, and integral conversions other than
4684 // narrowing conversions.
4685 ImplicitConversionSequence ICS =
4686 TryImplicitConversion(From, T,
4687 /*SuppressUserConversions=*/false,
4688 /*AllowExplicit=*/false,
4689 /*InOverloadResolution=*/false,
4690 /*CStyle=*/false,
4691 /*AllowObjcWritebackConversion=*/false);
4692 StandardConversionSequence *SCS = 0;
4693 switch (ICS.getKind()) {
4694 case ImplicitConversionSequence::StandardConversion:
4695 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4696 return Diag(From->getSourceRange().getBegin(),
4697 diag::err_typecheck_converted_constant_expression_disallowed)
4698 << From->getType() << From->getSourceRange() << T;
4699 SCS = &ICS.Standard;
4700 break;
4701 case ImplicitConversionSequence::UserDefinedConversion:
4702 // We are converting from class type to an integral or enumeration type, so
4703 // the Before sequence must be trivial.
4704 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4705 return Diag(From->getSourceRange().getBegin(),
4706 diag::err_typecheck_converted_constant_expression_disallowed)
4707 << From->getType() << From->getSourceRange() << T;
4708 SCS = &ICS.UserDefined.After;
4709 break;
4710 case ImplicitConversionSequence::AmbiguousConversion:
4711 case ImplicitConversionSequence::BadConversion:
4712 if (!DiagnoseMultipleUserDefinedConversion(From, T))
4713 return Diag(From->getSourceRange().getBegin(),
4714 diag::err_typecheck_converted_constant_expression)
4715 << From->getType() << From->getSourceRange() << T;
4716 return ExprError();
4717
4718 case ImplicitConversionSequence::EllipsisConversion:
4719 llvm_unreachable("ellipsis conversion in converted constant expression");
4720 }
4721
4722 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4723 if (Result.isInvalid())
4724 return Result;
4725
4726 // Check for a narrowing implicit conversion.
4727 APValue PreNarrowingValue;
Richard Smithf72fccf2012-01-30 22:27:01 +00004728 bool Diagnosed = false;
Richard Smith8ef7b202012-01-18 23:55:52 +00004729 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue)) {
4730 case NK_Variable_Narrowing:
4731 // Implicit conversion to a narrower type, and the value is not a constant
4732 // expression. We'll diagnose this in a moment.
4733 case NK_Not_Narrowing:
4734 break;
4735
4736 case NK_Constant_Narrowing:
4737 Diag(From->getSourceRange().getBegin(), diag::err_cce_narrowing)
4738 << CCE << /*Constant*/1
4739 << PreNarrowingValue.getAsString(Context, QualType()) << T;
Richard Smithf72fccf2012-01-30 22:27:01 +00004740 Diagnosed = true;
Richard Smith8ef7b202012-01-18 23:55:52 +00004741 break;
4742
4743 case NK_Type_Narrowing:
4744 Diag(From->getSourceRange().getBegin(), diag::err_cce_narrowing)
4745 << CCE << /*Constant*/0 << From->getType() << T;
Richard Smithf72fccf2012-01-30 22:27:01 +00004746 Diagnosed = true;
Richard Smith8ef7b202012-01-18 23:55:52 +00004747 break;
4748 }
4749
4750 // Check the expression is a constant expression.
4751 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4752 Expr::EvalResult Eval;
4753 Eval.Diag = &Notes;
4754
4755 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4756 // The expression can't be folded, so we can't keep it at this position in
4757 // the AST.
4758 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004759 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004760 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004761
4762 if (Notes.empty()) {
4763 // It's a constant expression.
4764 return Result;
4765 }
Richard Smith8ef7b202012-01-18 23:55:52 +00004766 }
4767
Richard Smithf72fccf2012-01-30 22:27:01 +00004768 // Only issue one narrowing diagnostic.
4769 if (Diagnosed)
4770 return Result;
4771
Richard Smith8ef7b202012-01-18 23:55:52 +00004772 // It's not a constant expression. Produce an appropriate diagnostic.
4773 if (Notes.size() == 1 &&
4774 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4775 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4776 else {
4777 Diag(From->getSourceRange().getBegin(), diag::err_expr_not_cce)
4778 << CCE << From->getSourceRange();
4779 for (unsigned I = 0; I < Notes.size(); ++I)
4780 Diag(Notes[I].first, Notes[I].second);
4781 }
Richard Smithf72fccf2012-01-30 22:27:01 +00004782 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00004783}
4784
John McCall0bcc9bc2011-09-09 06:11:02 +00004785/// dropPointerConversions - If the given standard conversion sequence
4786/// involves any pointer conversions, remove them. This may change
4787/// the result type of the conversion sequence.
4788static void dropPointerConversion(StandardConversionSequence &SCS) {
4789 if (SCS.Second == ICK_Pointer_Conversion) {
4790 SCS.Second = ICK_Identity;
4791 SCS.Third = ICK_Identity;
4792 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4793 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004794}
John McCall120d63c2010-08-24 20:38:10 +00004795
John McCall0bcc9bc2011-09-09 06:11:02 +00004796/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4797/// convert the expression From to an Objective-C pointer type.
4798static ImplicitConversionSequence
4799TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4800 // Do an implicit conversion to 'id'.
4801 QualType Ty = S.Context.getObjCIdType();
4802 ImplicitConversionSequence ICS
4803 = TryImplicitConversion(S, From, Ty,
4804 // FIXME: Are these flags correct?
4805 /*SuppressUserConversions=*/false,
4806 /*AllowExplicit=*/true,
4807 /*InOverloadResolution=*/false,
4808 /*CStyle=*/false,
4809 /*AllowObjCWritebackConversion=*/false);
4810
4811 // Strip off any final conversions to 'id'.
4812 switch (ICS.getKind()) {
4813 case ImplicitConversionSequence::BadConversion:
4814 case ImplicitConversionSequence::AmbiguousConversion:
4815 case ImplicitConversionSequence::EllipsisConversion:
4816 break;
4817
4818 case ImplicitConversionSequence::UserDefinedConversion:
4819 dropPointerConversion(ICS.UserDefined.After);
4820 break;
4821
4822 case ImplicitConversionSequence::StandardConversion:
4823 dropPointerConversion(ICS.Standard);
4824 break;
4825 }
4826
4827 return ICS;
4828}
4829
4830/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4831/// conversion of the expression From to an Objective-C pointer type.
4832ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004833 if (checkPlaceholderForOverload(*this, From))
4834 return ExprError();
4835
John McCallc12c5bb2010-05-15 11:32:37 +00004836 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00004837 ImplicitConversionSequence ICS =
4838 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004839 if (!ICS.isBad())
4840 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00004841 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004842}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004843
Richard Smithf39aec12012-02-04 07:07:42 +00004844/// Determine whether the provided type is an integral type, or an enumeration
4845/// type of a permitted flavor.
4846static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
4847 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
4848 : T->isIntegralOrUnscopedEnumerationType();
4849}
4850
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004851/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00004852/// enumeration type.
4853///
4854/// This routine will attempt to convert an expression of class type to an
4855/// integral or enumeration type, if that class type only has a single
4856/// conversion to an integral or enumeration type.
4857///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004858/// \param Loc The source location of the construct that requires the
4859/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00004860///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004861/// \param FromE The expression we're converting from.
4862///
4863/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4864/// have integral or enumeration type.
4865///
4866/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4867/// incomplete class type.
4868///
4869/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4870/// explicit conversion function (because no implicit conversion functions
4871/// were available). This is a recovery mode.
4872///
4873/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4874/// showing which conversion was picked.
4875///
4876/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4877/// conversion function that could convert to integral or enumeration type.
4878///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004879/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004880/// usable conversion function.
4881///
4882/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4883/// function, which may be an extension in this case.
4884///
Richard Smithf39aec12012-02-04 07:07:42 +00004885/// \param AllowScopedEnumerations Specifies whether conversions to scoped
4886/// enumerations should be considered.
4887///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004888/// \returns The expression, converted to an integral or enumeration type if
4889/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004890ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004891Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00004892 const PartialDiagnostic &NotIntDiag,
4893 const PartialDiagnostic &IncompleteDiag,
4894 const PartialDiagnostic &ExplicitConvDiag,
4895 const PartialDiagnostic &ExplicitConvNote,
4896 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004897 const PartialDiagnostic &AmbigNote,
Richard Smithf39aec12012-02-04 07:07:42 +00004898 const PartialDiagnostic &ConvDiag,
4899 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00004900 // We can't perform any more checking for type-dependent expressions.
4901 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00004902 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004903
Eli Friedmanceccab92012-01-26 00:26:18 +00004904 // Process placeholders immediately.
4905 if (From->hasPlaceholderType()) {
4906 ExprResult result = CheckPlaceholderExpr(From);
4907 if (result.isInvalid()) return result;
4908 From = result.take();
4909 }
4910
Douglas Gregorc30614b2010-06-29 23:17:37 +00004911 // If the expression already has integral or enumeration type, we're golden.
4912 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00004913 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00004914 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004915
4916 // FIXME: Check for missing '()' if T is a function type?
4917
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004918 // 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 +00004919 // expression of integral or enumeration type.
4920 const RecordType *RecordTy = T->getAs<RecordType>();
4921 if (!RecordTy || !getLangOptions().CPlusPlus) {
Richard Smith282e7e62012-02-04 09:53:13 +00004922 if (NotIntDiag.getDiagID())
4923 Diag(Loc, NotIntDiag) << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00004924 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004925 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004926
Douglas Gregorc30614b2010-06-29 23:17:37 +00004927 // We must have a complete class type.
4928 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00004929 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004930
Douglas Gregorc30614b2010-06-29 23:17:37 +00004931 // Look for a conversion to an integral or enumeration type.
4932 UnresolvedSet<4> ViableConversions;
4933 UnresolvedSet<4> ExplicitConversions;
4934 const UnresolvedSetImpl *Conversions
4935 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004936
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004937 bool HadMultipleCandidates = (Conversions->size() > 1);
4938
Douglas Gregorc30614b2010-06-29 23:17:37 +00004939 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004940 E = Conversions->end();
4941 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00004942 ++I) {
4943 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00004944 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
4945 if (isIntegralOrEnumerationType(
4946 Conversion->getConversionType().getNonReferenceType(),
4947 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00004948 if (Conversion->isExplicit())
4949 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4950 else
4951 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4952 }
Richard Smithf39aec12012-02-04 07:07:42 +00004953 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00004954 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004955
Douglas Gregorc30614b2010-06-29 23:17:37 +00004956 switch (ViableConversions.size()) {
4957 case 0:
Richard Smith282e7e62012-02-04 09:53:13 +00004958 if (ExplicitConversions.size() == 1 && ExplicitConvDiag.getDiagID()) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00004959 DeclAccessPair Found = ExplicitConversions[0];
4960 CXXConversionDecl *Conversion
4961 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004962
Douglas Gregorc30614b2010-06-29 23:17:37 +00004963 // The user probably meant to invoke the given explicit
4964 // conversion; use it.
4965 QualType ConvTy
4966 = Conversion->getConversionType().getNonReferenceType();
4967 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00004968 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004969
Douglas Gregorc30614b2010-06-29 23:17:37 +00004970 Diag(Loc, ExplicitConvDiag)
4971 << T << ConvTy
4972 << FixItHint::CreateInsertion(From->getLocStart(),
4973 "static_cast<" + TypeStr + ">(")
4974 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4975 ")");
4976 Diag(Conversion->getLocation(), ExplicitConvNote)
4977 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004978
4979 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00004980 // explicit conversion function.
4981 if (isSFINAEContext())
4982 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004983
Douglas Gregorc30614b2010-06-29 23:17:37 +00004984 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004985 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4986 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004987 if (Result.isInvalid())
4988 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00004989 // Record usage of conversion in an implicit cast.
4990 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4991 CK_UserDefinedConversion,
4992 Result.get(), 0,
4993 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00004994 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004995
Douglas Gregorc30614b2010-06-29 23:17:37 +00004996 // We'll complain below about a non-integral condition type.
4997 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004998
Douglas Gregorc30614b2010-06-29 23:17:37 +00004999 case 1: {
5000 // Apply this conversion.
5001 DeclAccessPair Found = ViableConversions[0];
5002 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005003
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005004 CXXConversionDecl *Conversion
5005 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5006 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005007 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005008 if (ConvDiag.getDiagID()) {
5009 if (isSFINAEContext())
5010 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005011
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005012 Diag(Loc, ConvDiag)
5013 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
5014 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005015
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005016 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5017 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005018 if (Result.isInvalid())
5019 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005020 // Record usage of conversion in an implicit cast.
5021 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5022 CK_UserDefinedConversion,
5023 Result.get(), 0,
5024 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005025 break;
5026 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005027
Douglas Gregorc30614b2010-06-29 23:17:37 +00005028 default:
Richard Smith282e7e62012-02-04 09:53:13 +00005029 if (!AmbigDiag.getDiagID())
5030 return Owned(From);
5031
Douglas Gregorc30614b2010-06-29 23:17:37 +00005032 Diag(Loc, AmbigDiag)
5033 << T << From->getSourceRange();
5034 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5035 CXXConversionDecl *Conv
5036 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5037 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5038 Diag(Conv->getLocation(), AmbigNote)
5039 << ConvTy->isEnumeralType() << ConvTy;
5040 }
John McCall9ae2f072010-08-23 23:25:46 +00005041 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005042 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005043
Richard Smith282e7e62012-02-04 09:53:13 +00005044 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5045 NotIntDiag.getDiagID())
5046 Diag(Loc, NotIntDiag) << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005047
Eli Friedmanceccab92012-01-26 00:26:18 +00005048 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005049}
5050
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005051/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005052/// candidate functions, using the given function call arguments. If
5053/// @p SuppressUserConversions, then don't allow user-defined
5054/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005055///
5056/// \para PartialOverloading true if we are performing "partial" overloading
5057/// based on an incomplete set of function arguments. This feature is used by
5058/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005059void
5060Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005061 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005062 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005063 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005064 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005065 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00005066 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005067 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005068 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005069 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005070 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005071
Douglas Gregor88a35142008-12-22 05:46:06 +00005072 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005073 if (!isa<CXXConstructorDecl>(Method)) {
5074 // If we get here, it's because we're calling a member function
5075 // that is named without a member access expression (e.g.,
5076 // "this->f") that was either written explicitly or created
5077 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005078 // function, e.g., X::f(). We use an empty type for the implied
5079 // object argument (C++ [over.call.func]p3), and the acting context
5080 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005081 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005082 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005083 Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005084 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005085 return;
5086 }
5087 // We treat a constructor like a non-member function, since its object
5088 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005089 }
5090
Douglas Gregorfd476482009-11-13 23:59:09 +00005091 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005092 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005093
Douglas Gregor7edfb692009-11-23 12:27:39 +00005094 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005095 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005096
Douglas Gregor66724ea2009-11-14 01:20:54 +00005097 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5098 // C++ [class.copy]p3:
5099 // A member function template is never instantiated to perform the copy
5100 // of a class object to an object of its class type.
5101 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005102 if (NumArgs == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005103 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005104 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5105 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005106 return;
5107 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005108
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005109 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005110 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00005111 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005112 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005113 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005114 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005115 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005116 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005117
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005118 unsigned NumArgsInProto = Proto->getNumArgs();
5119
5120 // (C++ 13.3.2p2): A candidate function having fewer than m
5121 // parameters is viable only if it has an ellipsis in its parameter
5122 // list (8.3.5).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005123 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005124 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005125 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005126 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005127 return;
5128 }
5129
5130 // (C++ 13.3.2p2): A candidate function having more than m parameters
5131 // is viable only if the (m+1)st parameter has a default argument
5132 // (8.3.6). For the purposes of overload resolution, the
5133 // parameter list is truncated on the right, so that there are
5134 // exactly m parameters.
5135 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005136 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005137 // Not enough arguments.
5138 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005139 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005140 return;
5141 }
5142
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005143 // (CUDA B.1): Check for invalid calls between targets.
5144 if (getLangOptions().CUDA)
5145 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5146 if (CheckCUDATarget(Caller, Function)) {
5147 Candidate.Viable = false;
5148 Candidate.FailureKind = ovl_fail_bad_target;
5149 return;
5150 }
5151
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005152 // Determine the implicit conversion sequences for each of the
5153 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005154 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5155 if (ArgIdx < NumArgsInProto) {
5156 // (C++ 13.3.2p3): for F to be a viable function, there shall
5157 // exist for each argument an implicit conversion sequence
5158 // (13.3.3.1) that converts that argument to the corresponding
5159 // parameter of F.
5160 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005161 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005162 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005163 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005164 /*InOverloadResolution=*/true,
5165 /*AllowObjCWritebackConversion=*/
5166 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005167 if (Candidate.Conversions[ArgIdx].isBad()) {
5168 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005169 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005170 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005171 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005172 } else {
5173 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5174 // argument for which there is no corresponding parameter is
5175 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005176 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005177 }
5178 }
5179}
5180
Douglas Gregor063daf62009-03-13 18:40:31 +00005181/// \brief Add all of the function declarations in the given function set to
5182/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005183void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00005184 Expr **Args, unsigned NumArgs,
5185 OverloadCandidateSet& CandidateSet,
5186 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00005187 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005188 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5189 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005190 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005191 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005192 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005193 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005194 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00005195 CandidateSet, SuppressUserConversions);
5196 else
John McCall9aa472c2010-03-19 07:35:19 +00005197 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005198 SuppressUserConversions);
5199 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005200 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005201 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5202 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005203 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005204 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00005205 /*FIXME: explicit args */ 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005206 Args[0]->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005207 Args[0]->Classify(Context),
5208 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00005209 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00005210 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005211 else
John McCall9aa472c2010-03-19 07:35:19 +00005212 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00005213 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00005214 Args, NumArgs, CandidateSet,
5215 SuppressUserConversions);
5216 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005217 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005218}
5219
John McCall314be4e2009-11-17 07:50:12 +00005220/// AddMethodCandidate - Adds a named decl (which is some kind of
5221/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005222void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005223 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005224 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005225 Expr **Args, unsigned NumArgs,
5226 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005227 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005228 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005229 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005230
5231 if (isa<UsingShadowDecl>(Decl))
5232 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005233
John McCall314be4e2009-11-17 07:50:12 +00005234 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5235 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5236 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005237 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5238 /*ExplicitArgs*/ 0,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005239 ObjectType, ObjectClassification, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00005240 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005241 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005242 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005243 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005244 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005245 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005246 }
5247}
5248
Douglas Gregor96176b32008-11-18 23:14:02 +00005249/// AddMethodCandidate - Adds the given C++ member function to the set
5250/// of candidate functions, using the given function call arguments
5251/// and the object argument (@c Object). For example, in a call
5252/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5253/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5254/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005255/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005256void
John McCall9aa472c2010-03-19 07:35:19 +00005257Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005258 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005259 Expr::Classification ObjectClassification,
John McCall86820f52010-01-26 01:37:31 +00005260 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00005261 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005262 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005263 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005264 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005265 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005266 assert(!isa<CXXConstructorDecl>(Method) &&
5267 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005268
Douglas Gregor3f396022009-09-28 04:47:19 +00005269 if (!CandidateSet.isNewCandidate(Method))
5270 return;
5271
Douglas Gregor7edfb692009-11-23 12:27:39 +00005272 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005273 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005274
Douglas Gregor96176b32008-11-18 23:14:02 +00005275 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005276 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005277 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005278 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005279 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005280 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005281 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor96176b32008-11-18 23:14:02 +00005282
5283 unsigned NumArgsInProto = Proto->getNumArgs();
5284
5285 // (C++ 13.3.2p2): A candidate function having fewer than m
5286 // parameters is viable only if it has an ellipsis in its parameter
5287 // list (8.3.5).
5288 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5289 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005290 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005291 return;
5292 }
5293
5294 // (C++ 13.3.2p2): A candidate function having more than m parameters
5295 // is viable only if the (m+1)st parameter has a default argument
5296 // (8.3.6). For the purposes of overload resolution, the
5297 // parameter list is truncated on the right, so that there are
5298 // exactly m parameters.
5299 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5300 if (NumArgs < MinRequiredArgs) {
5301 // Not enough arguments.
5302 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005303 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005304 return;
5305 }
5306
5307 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005308
John McCall701c89e2009-12-03 04:06:58 +00005309 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005310 // The implicit object argument is ignored.
5311 Candidate.IgnoreObjectArgument = true;
5312 else {
5313 // Determine the implicit conversion sequence for the object
5314 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005315 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005316 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5317 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005318 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005319 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005320 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005321 return;
5322 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005323 }
5324
5325 // Determine the implicit conversion sequences for each of the
5326 // arguments.
5327 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5328 if (ArgIdx < NumArgsInProto) {
5329 // (C++ 13.3.2p3): for F to be a viable function, there shall
5330 // exist for each argument an implicit conversion sequence
5331 // (13.3.3.1) that converts that argument to the corresponding
5332 // parameter of F.
5333 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005334 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005335 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005336 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005337 /*InOverloadResolution=*/true,
5338 /*AllowObjCWritebackConversion=*/
5339 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005340 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005341 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005342 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005343 break;
5344 }
5345 } else {
5346 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5347 // argument for which there is no corresponding parameter is
5348 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005349 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005350 }
5351 }
5352}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005353
Douglas Gregor6b906862009-08-21 00:16:32 +00005354/// \brief Add a C++ member function template as a candidate to the candidate
5355/// set, using template argument deduction to produce an appropriate member
5356/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005357void
Douglas Gregor6b906862009-08-21 00:16:32 +00005358Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005359 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005360 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005361 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005362 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005363 Expr::Classification ObjectClassification,
John McCall701c89e2009-12-03 04:06:58 +00005364 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00005365 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005366 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005367 if (!CandidateSet.isNewCandidate(MethodTmpl))
5368 return;
5369
Douglas Gregor6b906862009-08-21 00:16:32 +00005370 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005371 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005372 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005373 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005374 // candidate functions in the usual way.113) A given name can refer to one
5375 // or more function templates and also to a set of overloaded non-template
5376 // functions. In such a case, the candidate functions generated from each
5377 // function template are combined with the set of non-template candidate
5378 // functions.
John McCall5769d612010-02-08 23:07:23 +00005379 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005380 FunctionDecl *Specialization = 0;
5381 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00005382 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00005383 Args, NumArgs, Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005384 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005385 Candidate.FoundDecl = FoundDecl;
5386 Candidate.Function = MethodTmpl->getTemplatedDecl();
5387 Candidate.Viable = false;
5388 Candidate.FailureKind = ovl_fail_bad_deduction;
5389 Candidate.IsSurrogate = false;
5390 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005391 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005392 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005393 Info);
5394 return;
5395 }
Mike Stump1eb44332009-09-09 15:08:12 +00005396
Douglas Gregor6b906862009-08-21 00:16:32 +00005397 // Add the function template specialization produced by template argument
5398 // deduction as a candidate.
5399 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005400 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005401 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005402 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005403 ActingContext, ObjectType, ObjectClassification,
5404 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005405}
5406
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005407/// \brief Add a C++ function template specialization as a candidate
5408/// in the candidate set, using template argument deduction to produce
5409/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005410void
Douglas Gregore53060f2009-06-25 22:08:12 +00005411Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005412 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005413 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00005414 Expr **Args, unsigned NumArgs,
5415 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005416 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005417 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5418 return;
5419
Douglas Gregore53060f2009-06-25 22:08:12 +00005420 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005421 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005422 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005423 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005424 // candidate functions in the usual way.113) A given name can refer to one
5425 // or more function templates and also to a set of overloaded non-template
5426 // functions. In such a case, the candidate functions generated from each
5427 // function template are combined with the set of non-template candidate
5428 // functions.
John McCall5769d612010-02-08 23:07:23 +00005429 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005430 FunctionDecl *Specialization = 0;
5431 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00005432 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00005433 Args, NumArgs, Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005434 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005435 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005436 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5437 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005438 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005439 Candidate.IsSurrogate = false;
5440 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005441 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005442 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005443 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005444 return;
5445 }
Mike Stump1eb44332009-09-09 15:08:12 +00005446
Douglas Gregore53060f2009-06-25 22:08:12 +00005447 // Add the function template specialization produced by template argument
5448 // deduction as a candidate.
5449 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005450 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005451 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005452}
Mike Stump1eb44332009-09-09 15:08:12 +00005453
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005454/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005455/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005456/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005457/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005458/// (which may or may not be the same type as the type that the
5459/// conversion function produces).
5460void
5461Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005462 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005463 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005464 Expr *From, QualType ToType,
5465 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005466 assert(!Conversion->getDescribedFunctionTemplate() &&
5467 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005468 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005469 if (!CandidateSet.isNewCandidate(Conversion))
5470 return;
5471
Douglas Gregor7edfb692009-11-23 12:27:39 +00005472 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005473 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005474
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005475 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005476 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005477 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005478 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005479 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005480 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005481 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005482 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005483 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005484 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005485 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005486
Douglas Gregorbca39322010-08-19 15:37:02 +00005487 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005488 // For conversion functions, the function is considered to be a member of
5489 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005490 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005491 //
5492 // Determine the implicit conversion sequence for the implicit
5493 // object parameter.
5494 QualType ImplicitParamType = From->getType();
5495 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5496 ImplicitParamType = FromPtrType->getPointeeType();
5497 CXXRecordDecl *ConversionContext
5498 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005499
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005500 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005501 = TryObjectArgumentInitialization(*this, From->getType(),
5502 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005503 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005504
John McCall1d318332010-01-12 00:44:57 +00005505 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005506 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005507 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005508 return;
5509 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005510
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005511 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005512 // derived to base as such conversions are given Conversion Rank. They only
5513 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5514 QualType FromCanon
5515 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5516 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5517 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5518 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005519 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005520 return;
5521 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005522
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005523 // To determine what the conversion from the result of calling the
5524 // conversion function to the type we're eventually trying to
5525 // convert to (ToType), we need to synthesize a call to the
5526 // conversion function and attempt copy initialization from it. This
5527 // makes sure that we get the right semantics with respect to
5528 // lvalues/rvalues and the type. Fortunately, we can allocate this
5529 // call on the stack and we don't need its arguments to be
5530 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00005531 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005532 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005533 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5534 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005535 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005536 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005537
Richard Smith87c1f1f2011-07-13 22:53:21 +00005538 QualType ConversionType = Conversion->getConversionType();
5539 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005540 Candidate.Viable = false;
5541 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5542 return;
5543 }
5544
Richard Smith87c1f1f2011-07-13 22:53:21 +00005545 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005546
Mike Stump1eb44332009-09-09 15:08:12 +00005547 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005548 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5549 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005550 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00005551 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005552 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005553 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005554 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005555 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005556 /*InOverloadResolution=*/false,
5557 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005558
John McCall1d318332010-01-12 00:44:57 +00005559 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005560 case ImplicitConversionSequence::StandardConversion:
5561 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005562
Douglas Gregorc520c842010-04-12 23:42:09 +00005563 // C++ [over.ics.user]p3:
5564 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005565 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005566 // shall have exact match rank.
5567 if (Conversion->getPrimaryTemplate() &&
5568 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5569 Candidate.Viable = false;
5570 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5571 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005572
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005573 // C++0x [dcl.init.ref]p5:
5574 // In the second case, if the reference is an rvalue reference and
5575 // the second standard conversion sequence of the user-defined
5576 // conversion sequence includes an lvalue-to-rvalue conversion, the
5577 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005578 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005579 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5580 Candidate.Viable = false;
5581 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5582 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005583 break;
5584
5585 case ImplicitConversionSequence::BadConversion:
5586 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005587 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005588 break;
5589
5590 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005591 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005592 "Can only end up with a standard conversion sequence or failure");
5593 }
5594}
5595
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005596/// \brief Adds a conversion function template specialization
5597/// candidate to the overload set, using template argument deduction
5598/// to deduce the template arguments of the conversion function
5599/// template from the type that we are converting to (C++
5600/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005601void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005602Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005603 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005604 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005605 Expr *From, QualType ToType,
5606 OverloadCandidateSet &CandidateSet) {
5607 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5608 "Only conversion function templates permitted here");
5609
Douglas Gregor3f396022009-09-28 04:47:19 +00005610 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5611 return;
5612
John McCall5769d612010-02-08 23:07:23 +00005613 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005614 CXXConversionDecl *Specialization = 0;
5615 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005616 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005617 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005618 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005619 Candidate.FoundDecl = FoundDecl;
5620 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5621 Candidate.Viable = false;
5622 Candidate.FailureKind = ovl_fail_bad_deduction;
5623 Candidate.IsSurrogate = false;
5624 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005625 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005626 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005627 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005628 return;
5629 }
Mike Stump1eb44332009-09-09 15:08:12 +00005630
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005631 // Add the conversion function template specialization produced by
5632 // template argument deduction as a candidate.
5633 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005634 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005635 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005636}
5637
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005638/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5639/// converts the given @c Object to a function pointer via the
5640/// conversion function @c Conversion, and then attempts to call it
5641/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5642/// the type of function that we'll eventually be calling.
5643void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005644 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005645 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005646 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005647 Expr *Object,
John McCall701c89e2009-12-03 04:06:58 +00005648 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005649 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005650 if (!CandidateSet.isNewCandidate(Conversion))
5651 return;
5652
Douglas Gregor7edfb692009-11-23 12:27:39 +00005653 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005654 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005655
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005656 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005657 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005658 Candidate.Function = 0;
5659 Candidate.Surrogate = Conversion;
5660 Candidate.Viable = true;
5661 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005662 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005663 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005664
5665 // Determine the implicit conversion sequence for the implicit
5666 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005667 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005668 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005669 Object->Classify(Context),
5670 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005671 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005672 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005673 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005674 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005675 return;
5676 }
5677
5678 // The first conversion is actually a user-defined conversion whose
5679 // first conversion is ObjectInit's standard conversion (which is
5680 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005681 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005682 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005683 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005684 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005685 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005686 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005687 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005688 = Candidate.Conversions[0].UserDefined.Before;
5689 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5690
Mike Stump1eb44332009-09-09 15:08:12 +00005691 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005692 unsigned NumArgsInProto = Proto->getNumArgs();
5693
5694 // (C++ 13.3.2p2): A candidate function having fewer than m
5695 // parameters is viable only if it has an ellipsis in its parameter
5696 // list (8.3.5).
5697 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5698 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005699 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005700 return;
5701 }
5702
5703 // Function types don't have any default arguments, so just check if
5704 // we have enough arguments.
5705 if (NumArgs < NumArgsInProto) {
5706 // Not enough arguments.
5707 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005708 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005709 return;
5710 }
5711
5712 // Determine the implicit conversion sequences for each of the
5713 // arguments.
5714 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5715 if (ArgIdx < NumArgsInProto) {
5716 // (C++ 13.3.2p3): for F to be a viable function, there shall
5717 // exist for each argument an implicit conversion sequence
5718 // (13.3.3.1) that converts that argument to the corresponding
5719 // parameter of F.
5720 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005721 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005722 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005723 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005724 /*InOverloadResolution=*/false,
5725 /*AllowObjCWritebackConversion=*/
5726 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005727 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005728 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005729 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005730 break;
5731 }
5732 } else {
5733 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5734 // argument for which there is no corresponding parameter is
5735 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005736 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005737 }
5738 }
5739}
5740
Douglas Gregor063daf62009-03-13 18:40:31 +00005741/// \brief Add overload candidates for overloaded operators that are
5742/// member functions.
5743///
5744/// Add the overloaded operator candidates that are member functions
5745/// for the operator Op that was used in an operator expression such
5746/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5747/// CandidateSet will store the added overload candidates. (C++
5748/// [over.match.oper]).
5749void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5750 SourceLocation OpLoc,
5751 Expr **Args, unsigned NumArgs,
5752 OverloadCandidateSet& CandidateSet,
5753 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005754 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5755
5756 // C++ [over.match.oper]p3:
5757 // For a unary operator @ with an operand of a type whose
5758 // cv-unqualified version is T1, and for a binary operator @ with
5759 // a left operand of a type whose cv-unqualified version is T1 and
5760 // a right operand of a type whose cv-unqualified version is T2,
5761 // three sets of candidate functions, designated member
5762 // candidates, non-member candidates and built-in candidates, are
5763 // constructed as follows:
5764 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005765
5766 // -- If T1 is a class type, the set of member candidates is the
5767 // result of the qualified lookup of T1::operator@
5768 // (13.3.1.1.1); otherwise, the set of member candidates is
5769 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005770 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005771 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00005772 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005773 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005774
John McCalla24dc2e2009-11-17 02:14:36 +00005775 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5776 LookupQualifiedName(Operators, T1Rec->getDecl());
5777 Operators.suppressDiagnostics();
5778
Mike Stump1eb44332009-09-09 15:08:12 +00005779 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005780 OperEnd = Operators.end();
5781 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005782 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005783 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005784 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005785 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005786 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005787 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005788}
5789
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005790/// AddBuiltinCandidate - Add a candidate for a built-in
5791/// operator. ResultTy and ParamTys are the result and parameter types
5792/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005793/// arguments being passed to the candidate. IsAssignmentOperator
5794/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005795/// operator. NumContextualBoolArguments is the number of arguments
5796/// (at the beginning of the argument list) that will be contextually
5797/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005798void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005799 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005800 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005801 bool IsAssignmentOperator,
5802 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005803 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005804 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005805
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005806 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005807 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00005808 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005809 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005810 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005811 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005812 Candidate.BuiltinTypes.ResultTy = ResultTy;
5813 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5814 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5815
5816 // Determine the implicit conversion sequences for each of the
5817 // arguments.
5818 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005819 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005820 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005821 // C++ [over.match.oper]p4:
5822 // For the built-in assignment operators, conversions of the
5823 // left operand are restricted as follows:
5824 // -- no temporaries are introduced to hold the left operand, and
5825 // -- no user-defined conversions are applied to the left
5826 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00005827 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005828 //
5829 // We block these conversions by turning off user-defined
5830 // conversions, since that is the only way that initialization of
5831 // a reference to a non-class type can occur from something that
5832 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005833 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00005834 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005835 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00005836 Candidate.Conversions[ArgIdx]
5837 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005838 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005839 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005840 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00005841 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00005842 /*InOverloadResolution=*/false,
5843 /*AllowObjCWritebackConversion=*/
5844 getLangOptions().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005845 }
John McCall1d318332010-01-12 00:44:57 +00005846 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005847 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005848 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005849 break;
5850 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005851 }
5852}
5853
5854/// BuiltinCandidateTypeSet - A set of types that will be used for the
5855/// candidate operator functions for built-in operators (C++
5856/// [over.built]). The types are separated into pointer types and
5857/// enumeration types.
5858class BuiltinCandidateTypeSet {
5859 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005860 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005861
5862 /// PointerTypes - The set of pointer types that will be used in the
5863 /// built-in candidates.
5864 TypeSet PointerTypes;
5865
Sebastian Redl78eb8742009-04-19 21:53:20 +00005866 /// MemberPointerTypes - The set of member pointer types that will be
5867 /// used in the built-in candidates.
5868 TypeSet MemberPointerTypes;
5869
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005870 /// EnumerationTypes - The set of enumeration types that will be
5871 /// used in the built-in candidates.
5872 TypeSet EnumerationTypes;
5873
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005874 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00005875 /// candidates.
5876 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00005877
5878 /// \brief A flag indicating non-record types are viable candidates
5879 bool HasNonRecordTypes;
5880
5881 /// \brief A flag indicating whether either arithmetic or enumeration types
5882 /// were present in the candidate set.
5883 bool HasArithmeticOrEnumeralTypes;
5884
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005885 /// \brief A flag indicating whether the nullptr type was present in the
5886 /// candidate set.
5887 bool HasNullPtrType;
5888
Douglas Gregor5842ba92009-08-24 15:23:48 +00005889 /// Sema - The semantic analysis instance where we are building the
5890 /// candidate type set.
5891 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00005892
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005893 /// Context - The AST context in which we will build the type sets.
5894 ASTContext &Context;
5895
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005896 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5897 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00005898 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005899
5900public:
5901 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005902 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005903
Mike Stump1eb44332009-09-09 15:08:12 +00005904 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00005905 : HasNonRecordTypes(false),
5906 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005907 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00005908 SemaRef(SemaRef),
5909 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005910
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005911 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00005912 SourceLocation Loc,
5913 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005914 bool AllowExplicitConversions,
5915 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005916
5917 /// pointer_begin - First pointer type found;
5918 iterator pointer_begin() { return PointerTypes.begin(); }
5919
Sebastian Redl78eb8742009-04-19 21:53:20 +00005920 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005921 iterator pointer_end() { return PointerTypes.end(); }
5922
Sebastian Redl78eb8742009-04-19 21:53:20 +00005923 /// member_pointer_begin - First member pointer type found;
5924 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5925
5926 /// member_pointer_end - Past the last member pointer type found;
5927 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5928
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005929 /// enumeration_begin - First enumeration type found;
5930 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5931
Sebastian Redl78eb8742009-04-19 21:53:20 +00005932 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005933 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005934
Douglas Gregor26bcf672010-05-19 03:21:00 +00005935 iterator vector_begin() { return VectorTypes.begin(); }
5936 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00005937
5938 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5939 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005940 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005941};
5942
Sebastian Redl78eb8742009-04-19 21:53:20 +00005943/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005944/// the set of pointer types along with any more-qualified variants of
5945/// that type. For example, if @p Ty is "int const *", this routine
5946/// will add "int const *", "int const volatile *", "int const
5947/// restrict *", and "int const volatile restrict *" to the set of
5948/// pointer types. Returns true if the add of @p Ty itself succeeded,
5949/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00005950///
5951/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00005952bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00005953BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5954 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00005955
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005956 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005957 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005958 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005959
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005960 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00005961 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005962 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005963 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005964 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005965 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005966 buildObjCPtr = true;
5967 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005968 else
David Blaikieb219cfc2011-09-23 05:06:16 +00005969 llvm_unreachable("type was not a pointer type!");
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005970 }
5971 else
5972 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005973
Sebastian Redla9efada2009-11-18 20:39:26 +00005974 // Don't add qualified variants of arrays. For one, they're not allowed
5975 // (the qualifier would sink to the element type), and for another, the
5976 // only overload situation where it matters is subscript or pointer +- int,
5977 // and those shouldn't have qualifier variants anyway.
5978 if (PointeeTy->isArrayType())
5979 return true;
John McCall0953e762009-09-24 19:53:00 +00005980 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00005981 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00005982 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005983 bool hasVolatile = VisibleQuals.hasVolatile();
5984 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005985
John McCall0953e762009-09-24 19:53:00 +00005986 // Iterate through all strict supersets of BaseCVR.
5987 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5988 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005989 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5990 // in the types.
5991 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5992 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00005993 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005994 if (!buildObjCPtr)
5995 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5996 else
5997 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005998 }
5999
6000 return true;
6001}
6002
Sebastian Redl78eb8742009-04-19 21:53:20 +00006003/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6004/// to the set of pointer types along with any more-qualified variants of
6005/// that type. For example, if @p Ty is "int const *", this routine
6006/// will add "int const *", "int const volatile *", "int const
6007/// restrict *", and "int const volatile restrict *" to the set of
6008/// pointer types. Returns true if the add of @p Ty itself succeeded,
6009/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006010///
6011/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006012bool
6013BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6014 QualType Ty) {
6015 // Insert this type.
6016 if (!MemberPointerTypes.insert(Ty))
6017 return false;
6018
John McCall0953e762009-09-24 19:53:00 +00006019 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6020 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006021
John McCall0953e762009-09-24 19:53:00 +00006022 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006023 // Don't add qualified variants of arrays. For one, they're not allowed
6024 // (the qualifier would sink to the element type), and for another, the
6025 // only overload situation where it matters is subscript or pointer +- int,
6026 // and those shouldn't have qualifier variants anyway.
6027 if (PointeeTy->isArrayType())
6028 return true;
John McCall0953e762009-09-24 19:53:00 +00006029 const Type *ClassTy = PointerTy->getClass();
6030
6031 // Iterate through all strict supersets of the pointee type's CVR
6032 // qualifiers.
6033 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6034 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6035 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006036
John McCall0953e762009-09-24 19:53:00 +00006037 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006038 MemberPointerTypes.insert(
6039 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006040 }
6041
6042 return true;
6043}
6044
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006045/// AddTypesConvertedFrom - Add each of the types to which the type @p
6046/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006047/// primarily interested in pointer types and enumeration types. We also
6048/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006049/// AllowUserConversions is true if we should look at the conversion
6050/// functions of a class type, and AllowExplicitConversions if we
6051/// should also include the explicit conversion functions of a class
6052/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006053void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006054BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006055 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006056 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006057 bool AllowExplicitConversions,
6058 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006059 // Only deal with canonical types.
6060 Ty = Context.getCanonicalType(Ty);
6061
6062 // Look through reference types; they aren't part of the type of an
6063 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006064 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006065 Ty = RefTy->getPointeeType();
6066
John McCall3b657512011-01-19 10:06:00 +00006067 // If we're dealing with an array type, decay to the pointer.
6068 if (Ty->isArrayType())
6069 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6070
6071 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006072 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006073
Chandler Carruth6a577462010-12-13 01:44:01 +00006074 // Flag if we ever add a non-record type.
6075 const RecordType *TyRec = Ty->getAs<RecordType>();
6076 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6077
Chandler Carruth6a577462010-12-13 01:44:01 +00006078 // Flag if we encounter an arithmetic type.
6079 HasArithmeticOrEnumeralTypes =
6080 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6081
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006082 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6083 PointerTypes.insert(Ty);
6084 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006085 // Insert our type, and its more-qualified variants, into the set
6086 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006087 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006088 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006089 } else if (Ty->isMemberPointerType()) {
6090 // Member pointers are far easier, since the pointee can't be converted.
6091 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6092 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006093 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006094 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006095 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006096 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006097 // We treat vector types as arithmetic types in many contexts as an
6098 // extension.
6099 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006100 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006101 } else if (Ty->isNullPtrType()) {
6102 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006103 } else if (AllowUserConversions && TyRec) {
6104 // No conversion functions in incomplete types.
6105 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6106 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006107
Chandler Carruth6a577462010-12-13 01:44:01 +00006108 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6109 const UnresolvedSetImpl *Conversions
6110 = ClassDecl->getVisibleConversionFunctions();
6111 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6112 E = Conversions->end(); I != E; ++I) {
6113 NamedDecl *D = I.getDecl();
6114 if (isa<UsingShadowDecl>(D))
6115 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006116
Chandler Carruth6a577462010-12-13 01:44:01 +00006117 // Skip conversion function templates; they don't tell us anything
6118 // about which builtin types we can convert to.
6119 if (isa<FunctionTemplateDecl>(D))
6120 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006121
Chandler Carruth6a577462010-12-13 01:44:01 +00006122 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6123 if (AllowExplicitConversions || !Conv->isExplicit()) {
6124 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6125 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006126 }
6127 }
6128 }
6129}
6130
Douglas Gregor19b7b152009-08-24 13:43:27 +00006131/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6132/// the volatile- and non-volatile-qualified assignment operators for the
6133/// given type to the candidate set.
6134static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6135 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006136 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006137 unsigned NumArgs,
6138 OverloadCandidateSet &CandidateSet) {
6139 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006140
Douglas Gregor19b7b152009-08-24 13:43:27 +00006141 // T& operator=(T&, T)
6142 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6143 ParamTypes[1] = T;
6144 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6145 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006146
Douglas Gregor19b7b152009-08-24 13:43:27 +00006147 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6148 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006149 ParamTypes[0]
6150 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006151 ParamTypes[1] = T;
6152 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006153 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006154 }
6155}
Mike Stump1eb44332009-09-09 15:08:12 +00006156
Sebastian Redl9994a342009-10-25 17:03:50 +00006157/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6158/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006159static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6160 Qualifiers VRQuals;
6161 const RecordType *TyRec;
6162 if (const MemberPointerType *RHSMPType =
6163 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006164 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006165 else
6166 TyRec = ArgExpr->getType()->getAs<RecordType>();
6167 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006168 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006169 VRQuals.addVolatile();
6170 VRQuals.addRestrict();
6171 return VRQuals;
6172 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006173
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006174 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006175 if (!ClassDecl->hasDefinition())
6176 return VRQuals;
6177
John McCalleec51cf2010-01-20 00:46:10 +00006178 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00006179 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006180
John McCalleec51cf2010-01-20 00:46:10 +00006181 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006182 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006183 NamedDecl *D = I.getDecl();
6184 if (isa<UsingShadowDecl>(D))
6185 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6186 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006187 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6188 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6189 CanTy = ResTypeRef->getPointeeType();
6190 // Need to go down the pointer/mempointer chain and add qualifiers
6191 // as see them.
6192 bool done = false;
6193 while (!done) {
6194 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6195 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006196 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006197 CanTy->getAs<MemberPointerType>())
6198 CanTy = ResTypeMPtr->getPointeeType();
6199 else
6200 done = true;
6201 if (CanTy.isVolatileQualified())
6202 VRQuals.addVolatile();
6203 if (CanTy.isRestrictQualified())
6204 VRQuals.addRestrict();
6205 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6206 return VRQuals;
6207 }
6208 }
6209 }
6210 return VRQuals;
6211}
John McCall00071ec2010-11-13 05:51:15 +00006212
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006213namespace {
John McCall00071ec2010-11-13 05:51:15 +00006214
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006215/// \brief Helper class to manage the addition of builtin operator overload
6216/// candidates. It provides shared state and utility methods used throughout
6217/// the process, as well as a helper method to add each group of builtin
6218/// operator overloads from the standard to a candidate set.
6219class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006220 // Common instance state available to all overload candidate addition methods.
6221 Sema &S;
6222 Expr **Args;
6223 unsigned NumArgs;
6224 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006225 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006226 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006227 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006228
Chandler Carruth6d695582010-12-12 10:35:00 +00006229 // Define some constants used to index and iterate over the arithemetic types
6230 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006231 // The "promoted arithmetic types" are the arithmetic
6232 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006233 static const unsigned FirstIntegralType = 3;
6234 static const unsigned LastIntegralType = 18;
6235 static const unsigned FirstPromotedIntegralType = 3,
6236 LastPromotedIntegralType = 9;
6237 static const unsigned FirstPromotedArithmeticType = 0,
6238 LastPromotedArithmeticType = 9;
6239 static const unsigned NumArithmeticTypes = 18;
6240
Chandler Carruth6d695582010-12-12 10:35:00 +00006241 /// \brief Get the canonical type for a given arithmetic type index.
6242 CanQualType getArithmeticType(unsigned index) {
6243 assert(index < NumArithmeticTypes);
6244 static CanQualType ASTContext::* const
6245 ArithmeticTypes[NumArithmeticTypes] = {
6246 // Start of promoted types.
6247 &ASTContext::FloatTy,
6248 &ASTContext::DoubleTy,
6249 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006250
Chandler Carruth6d695582010-12-12 10:35:00 +00006251 // Start of integral types.
6252 &ASTContext::IntTy,
6253 &ASTContext::LongTy,
6254 &ASTContext::LongLongTy,
6255 &ASTContext::UnsignedIntTy,
6256 &ASTContext::UnsignedLongTy,
6257 &ASTContext::UnsignedLongLongTy,
6258 // End of promoted types.
6259
6260 &ASTContext::BoolTy,
6261 &ASTContext::CharTy,
6262 &ASTContext::WCharTy,
6263 &ASTContext::Char16Ty,
6264 &ASTContext::Char32Ty,
6265 &ASTContext::SignedCharTy,
6266 &ASTContext::ShortTy,
6267 &ASTContext::UnsignedCharTy,
6268 &ASTContext::UnsignedShortTy,
6269 // End of integral types.
6270 // FIXME: What about complex?
6271 };
6272 return S.Context.*ArithmeticTypes[index];
6273 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006274
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006275 /// \brief Gets the canonical type resulting from the usual arithemetic
6276 /// converions for the given arithmetic types.
6277 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6278 // Accelerator table for performing the usual arithmetic conversions.
6279 // The rules are basically:
6280 // - if either is floating-point, use the wider floating-point
6281 // - if same signedness, use the higher rank
6282 // - if same size, use unsigned of the higher rank
6283 // - use the larger type
6284 // These rules, together with the axiom that higher ranks are
6285 // never smaller, are sufficient to precompute all of these results
6286 // *except* when dealing with signed types of higher rank.
6287 // (we could precompute SLL x UI for all known platforms, but it's
6288 // better not to make any assumptions).
6289 enum PromotedType {
6290 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
6291 };
6292 static PromotedType ConversionsTable[LastPromotedArithmeticType]
6293 [LastPromotedArithmeticType] = {
6294 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
6295 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6296 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6297 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
6298 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
6299 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
6300 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
6301 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
6302 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
6303 };
6304
6305 assert(L < LastPromotedArithmeticType);
6306 assert(R < LastPromotedArithmeticType);
6307 int Idx = ConversionsTable[L][R];
6308
6309 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006310 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006311
6312 // Slow path: we need to compare widths.
6313 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006314 CanQualType LT = getArithmeticType(L),
6315 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006316 unsigned LW = S.Context.getIntWidth(LT),
6317 RW = S.Context.getIntWidth(RT);
6318
6319 // If they're different widths, use the signed type.
6320 if (LW > RW) return LT;
6321 else if (LW < RW) return RT;
6322
6323 // Otherwise, use the unsigned type of the signed type's rank.
6324 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6325 assert(L == SLL || R == SLL);
6326 return S.Context.UnsignedLongLongTy;
6327 }
6328
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006329 /// \brief Helper method to factor out the common pattern of adding overloads
6330 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006331 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6332 bool HasVolatile) {
6333 QualType ParamTypes[2] = {
6334 S.Context.getLValueReferenceType(CandidateTy),
6335 S.Context.IntTy
6336 };
6337
6338 // Non-volatile version.
6339 if (NumArgs == 1)
6340 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6341 else
6342 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6343
6344 // Use a heuristic to reduce number of builtin candidates in the set:
6345 // add volatile version only if there are conversions to a volatile type.
6346 if (HasVolatile) {
6347 ParamTypes[0] =
6348 S.Context.getLValueReferenceType(
6349 S.Context.getVolatileType(CandidateTy));
6350 if (NumArgs == 1)
6351 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6352 else
6353 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6354 }
6355 }
6356
6357public:
6358 BuiltinOperatorOverloadBuilder(
6359 Sema &S, Expr **Args, unsigned NumArgs,
6360 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006361 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006362 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006363 OverloadCandidateSet &CandidateSet)
6364 : S(S), Args(Args), NumArgs(NumArgs),
6365 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006366 HasArithmeticOrEnumeralCandidateType(
6367 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006368 CandidateTypes(CandidateTypes),
6369 CandidateSet(CandidateSet) {
6370 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006371 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006372 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006373 assert(getArithmeticType(LastPromotedIntegralType - 1)
6374 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006375 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006376 assert(getArithmeticType(FirstPromotedArithmeticType)
6377 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006378 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006379 assert(getArithmeticType(LastPromotedArithmeticType - 1)
6380 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006381 "Invalid last promoted arithmetic type");
6382 }
6383
6384 // C++ [over.built]p3:
6385 //
6386 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6387 // is either volatile or empty, there exist candidate operator
6388 // functions of the form
6389 //
6390 // VQ T& operator++(VQ T&);
6391 // T operator++(VQ T&, int);
6392 //
6393 // C++ [over.built]p4:
6394 //
6395 // For every pair (T, VQ), where T is an arithmetic type other
6396 // than bool, and VQ is either volatile or empty, there exist
6397 // candidate operator functions of the form
6398 //
6399 // VQ T& operator--(VQ T&);
6400 // T operator--(VQ T&, int);
6401 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006402 if (!HasArithmeticOrEnumeralCandidateType)
6403 return;
6404
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006405 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6406 Arith < NumArithmeticTypes; ++Arith) {
6407 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006408 getArithmeticType(Arith),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006409 VisibleTypeConversionsQuals.hasVolatile());
6410 }
6411 }
6412
6413 // C++ [over.built]p5:
6414 //
6415 // For every pair (T, VQ), where T is a cv-qualified or
6416 // cv-unqualified object type, and VQ is either volatile or
6417 // empty, there exist candidate operator functions of the form
6418 //
6419 // T*VQ& operator++(T*VQ&);
6420 // T*VQ& operator--(T*VQ&);
6421 // T* operator++(T*VQ&, int);
6422 // T* operator--(T*VQ&, int);
6423 void addPlusPlusMinusMinusPointerOverloads() {
6424 for (BuiltinCandidateTypeSet::iterator
6425 Ptr = CandidateTypes[0].pointer_begin(),
6426 PtrEnd = CandidateTypes[0].pointer_end();
6427 Ptr != PtrEnd; ++Ptr) {
6428 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006429 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006430 continue;
6431
6432 addPlusPlusMinusMinusStyleOverloads(*Ptr,
6433 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6434 VisibleTypeConversionsQuals.hasVolatile()));
6435 }
6436 }
6437
6438 // C++ [over.built]p6:
6439 // For every cv-qualified or cv-unqualified object type T, there
6440 // exist candidate operator functions of the form
6441 //
6442 // T& operator*(T*);
6443 //
6444 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006445 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006446 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006447 // T& operator*(T*);
6448 void addUnaryStarPointerOverloads() {
6449 for (BuiltinCandidateTypeSet::iterator
6450 Ptr = CandidateTypes[0].pointer_begin(),
6451 PtrEnd = CandidateTypes[0].pointer_end();
6452 Ptr != PtrEnd; ++Ptr) {
6453 QualType ParamTy = *Ptr;
6454 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006455 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6456 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006457
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006458 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6459 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6460 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006461
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006462 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6463 &ParamTy, Args, 1, CandidateSet);
6464 }
6465 }
6466
6467 // C++ [over.built]p9:
6468 // For every promoted arithmetic type T, there exist candidate
6469 // operator functions of the form
6470 //
6471 // T operator+(T);
6472 // T operator-(T);
6473 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006474 if (!HasArithmeticOrEnumeralCandidateType)
6475 return;
6476
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006477 for (unsigned Arith = FirstPromotedArithmeticType;
6478 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006479 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006480 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6481 }
6482
6483 // Extension: We also add these operators for vector types.
6484 for (BuiltinCandidateTypeSet::iterator
6485 Vec = CandidateTypes[0].vector_begin(),
6486 VecEnd = CandidateTypes[0].vector_end();
6487 Vec != VecEnd; ++Vec) {
6488 QualType VecTy = *Vec;
6489 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6490 }
6491 }
6492
6493 // C++ [over.built]p8:
6494 // For every type T, there exist candidate operator functions of
6495 // the form
6496 //
6497 // T* operator+(T*);
6498 void addUnaryPlusPointerOverloads() {
6499 for (BuiltinCandidateTypeSet::iterator
6500 Ptr = CandidateTypes[0].pointer_begin(),
6501 PtrEnd = CandidateTypes[0].pointer_end();
6502 Ptr != PtrEnd; ++Ptr) {
6503 QualType ParamTy = *Ptr;
6504 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6505 }
6506 }
6507
6508 // C++ [over.built]p10:
6509 // For every promoted integral type T, there exist candidate
6510 // operator functions of the form
6511 //
6512 // T operator~(T);
6513 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006514 if (!HasArithmeticOrEnumeralCandidateType)
6515 return;
6516
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006517 for (unsigned Int = FirstPromotedIntegralType;
6518 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006519 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006520 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6521 }
6522
6523 // Extension: We also add this operator for vector types.
6524 for (BuiltinCandidateTypeSet::iterator
6525 Vec = CandidateTypes[0].vector_begin(),
6526 VecEnd = CandidateTypes[0].vector_end();
6527 Vec != VecEnd; ++Vec) {
6528 QualType VecTy = *Vec;
6529 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6530 }
6531 }
6532
6533 // C++ [over.match.oper]p16:
6534 // For every pointer to member type T, there exist candidate operator
6535 // functions of the form
6536 //
6537 // bool operator==(T,T);
6538 // bool operator!=(T,T);
6539 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6540 /// Set of (canonical) types that we've already handled.
6541 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6542
6543 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6544 for (BuiltinCandidateTypeSet::iterator
6545 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6546 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6547 MemPtr != MemPtrEnd;
6548 ++MemPtr) {
6549 // Don't add the same builtin candidate twice.
6550 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6551 continue;
6552
6553 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6554 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6555 CandidateSet);
6556 }
6557 }
6558 }
6559
6560 // C++ [over.built]p15:
6561 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006562 // For every T, where T is an enumeration type, a pointer type, or
6563 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006564 //
6565 // bool operator<(T, T);
6566 // bool operator>(T, T);
6567 // bool operator<=(T, T);
6568 // bool operator>=(T, T);
6569 // bool operator==(T, T);
6570 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006571 void addRelationalPointerOrEnumeralOverloads() {
6572 // C++ [over.built]p1:
6573 // If there is a user-written candidate with the same name and parameter
6574 // types as a built-in candidate operator function, the built-in operator
6575 // function is hidden and is not included in the set of candidate
6576 // functions.
6577 //
6578 // The text is actually in a note, but if we don't implement it then we end
6579 // up with ambiguities when the user provides an overloaded operator for
6580 // an enumeration type. Note that only enumeration types have this problem,
6581 // so we track which enumeration types we've seen operators for. Also, the
6582 // only other overloaded operator with enumeration argumenst, operator=,
6583 // cannot be overloaded for enumeration types, so this is the only place
6584 // where we must suppress candidates like this.
6585 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6586 UserDefinedBinaryOperators;
6587
6588 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6589 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6590 CandidateTypes[ArgIdx].enumeration_end()) {
6591 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6592 CEnd = CandidateSet.end();
6593 C != CEnd; ++C) {
6594 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6595 continue;
6596
6597 QualType FirstParamType =
6598 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6599 QualType SecondParamType =
6600 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6601
6602 // Skip if either parameter isn't of enumeral type.
6603 if (!FirstParamType->isEnumeralType() ||
6604 !SecondParamType->isEnumeralType())
6605 continue;
6606
6607 // Add this operator to the set of known user-defined operators.
6608 UserDefinedBinaryOperators.insert(
6609 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6610 S.Context.getCanonicalType(SecondParamType)));
6611 }
6612 }
6613 }
6614
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006615 /// Set of (canonical) types that we've already handled.
6616 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6617
6618 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6619 for (BuiltinCandidateTypeSet::iterator
6620 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6621 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6622 Ptr != PtrEnd; ++Ptr) {
6623 // Don't add the same builtin candidate twice.
6624 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6625 continue;
6626
6627 QualType ParamTypes[2] = { *Ptr, *Ptr };
6628 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6629 CandidateSet);
6630 }
6631 for (BuiltinCandidateTypeSet::iterator
6632 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6633 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6634 Enum != EnumEnd; ++Enum) {
6635 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6636
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006637 // Don't add the same builtin candidate twice, or if a user defined
6638 // candidate exists.
6639 if (!AddedTypes.insert(CanonType) ||
6640 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6641 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006642 continue;
6643
6644 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006645 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6646 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006647 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006648
6649 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6650 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6651 if (AddedTypes.insert(NullPtrTy) &&
6652 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6653 NullPtrTy))) {
6654 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6655 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6656 CandidateSet);
6657 }
6658 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006659 }
6660 }
6661
6662 // C++ [over.built]p13:
6663 //
6664 // For every cv-qualified or cv-unqualified object type T
6665 // there exist candidate operator functions of the form
6666 //
6667 // T* operator+(T*, ptrdiff_t);
6668 // T& operator[](T*, ptrdiff_t); [BELOW]
6669 // T* operator-(T*, ptrdiff_t);
6670 // T* operator+(ptrdiff_t, T*);
6671 // T& operator[](ptrdiff_t, T*); [BELOW]
6672 //
6673 // C++ [over.built]p14:
6674 //
6675 // For every T, where T is a pointer to object type, there
6676 // exist candidate operator functions of the form
6677 //
6678 // ptrdiff_t operator-(T, T);
6679 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6680 /// Set of (canonical) types that we've already handled.
6681 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6682
6683 for (int Arg = 0; Arg < 2; ++Arg) {
6684 QualType AsymetricParamTypes[2] = {
6685 S.Context.getPointerDiffType(),
6686 S.Context.getPointerDiffType(),
6687 };
6688 for (BuiltinCandidateTypeSet::iterator
6689 Ptr = CandidateTypes[Arg].pointer_begin(),
6690 PtrEnd = CandidateTypes[Arg].pointer_end();
6691 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006692 QualType PointeeTy = (*Ptr)->getPointeeType();
6693 if (!PointeeTy->isObjectType())
6694 continue;
6695
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006696 AsymetricParamTypes[Arg] = *Ptr;
6697 if (Arg == 0 || Op == OO_Plus) {
6698 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6699 // T* operator+(ptrdiff_t, T*);
6700 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6701 CandidateSet);
6702 }
6703 if (Op == OO_Minus) {
6704 // ptrdiff_t operator-(T, T);
6705 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6706 continue;
6707
6708 QualType ParamTypes[2] = { *Ptr, *Ptr };
6709 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6710 Args, 2, CandidateSet);
6711 }
6712 }
6713 }
6714 }
6715
6716 // C++ [over.built]p12:
6717 //
6718 // For every pair of promoted arithmetic types L and R, there
6719 // exist candidate operator functions of the form
6720 //
6721 // LR operator*(L, R);
6722 // LR operator/(L, R);
6723 // LR operator+(L, R);
6724 // LR operator-(L, R);
6725 // bool operator<(L, R);
6726 // bool operator>(L, R);
6727 // bool operator<=(L, R);
6728 // bool operator>=(L, R);
6729 // bool operator==(L, R);
6730 // bool operator!=(L, R);
6731 //
6732 // where LR is the result of the usual arithmetic conversions
6733 // between types L and R.
6734 //
6735 // C++ [over.built]p24:
6736 //
6737 // For every pair of promoted arithmetic types L and R, there exist
6738 // candidate operator functions of the form
6739 //
6740 // LR operator?(bool, L, R);
6741 //
6742 // where LR is the result of the usual arithmetic conversions
6743 // between types L and R.
6744 // Our candidates ignore the first parameter.
6745 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006746 if (!HasArithmeticOrEnumeralCandidateType)
6747 return;
6748
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006749 for (unsigned Left = FirstPromotedArithmeticType;
6750 Left < LastPromotedArithmeticType; ++Left) {
6751 for (unsigned Right = FirstPromotedArithmeticType;
6752 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006753 QualType LandR[2] = { getArithmeticType(Left),
6754 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006755 QualType Result =
6756 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006757 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006758 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6759 }
6760 }
6761
6762 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6763 // conditional operator for vector types.
6764 for (BuiltinCandidateTypeSet::iterator
6765 Vec1 = CandidateTypes[0].vector_begin(),
6766 Vec1End = CandidateTypes[0].vector_end();
6767 Vec1 != Vec1End; ++Vec1) {
6768 for (BuiltinCandidateTypeSet::iterator
6769 Vec2 = CandidateTypes[1].vector_begin(),
6770 Vec2End = CandidateTypes[1].vector_end();
6771 Vec2 != Vec2End; ++Vec2) {
6772 QualType LandR[2] = { *Vec1, *Vec2 };
6773 QualType Result = S.Context.BoolTy;
6774 if (!isComparison) {
6775 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6776 Result = *Vec1;
6777 else
6778 Result = *Vec2;
6779 }
6780
6781 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6782 }
6783 }
6784 }
6785
6786 // C++ [over.built]p17:
6787 //
6788 // For every pair of promoted integral types L and R, there
6789 // exist candidate operator functions of the form
6790 //
6791 // LR operator%(L, R);
6792 // LR operator&(L, R);
6793 // LR operator^(L, R);
6794 // LR operator|(L, R);
6795 // L operator<<(L, R);
6796 // L operator>>(L, R);
6797 //
6798 // where LR is the result of the usual arithmetic conversions
6799 // between types L and R.
6800 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006801 if (!HasArithmeticOrEnumeralCandidateType)
6802 return;
6803
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006804 for (unsigned Left = FirstPromotedIntegralType;
6805 Left < LastPromotedIntegralType; ++Left) {
6806 for (unsigned Right = FirstPromotedIntegralType;
6807 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006808 QualType LandR[2] = { getArithmeticType(Left),
6809 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006810 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6811 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006812 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006813 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6814 }
6815 }
6816 }
6817
6818 // C++ [over.built]p20:
6819 //
6820 // For every pair (T, VQ), where T is an enumeration or
6821 // pointer to member type and VQ is either volatile or
6822 // empty, there exist candidate operator functions of the form
6823 //
6824 // VQ T& operator=(VQ T&, T);
6825 void addAssignmentMemberPointerOrEnumeralOverloads() {
6826 /// Set of (canonical) types that we've already handled.
6827 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6828
6829 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6830 for (BuiltinCandidateTypeSet::iterator
6831 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6832 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6833 Enum != EnumEnd; ++Enum) {
6834 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6835 continue;
6836
6837 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6838 CandidateSet);
6839 }
6840
6841 for (BuiltinCandidateTypeSet::iterator
6842 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6843 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6844 MemPtr != MemPtrEnd; ++MemPtr) {
6845 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6846 continue;
6847
6848 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6849 CandidateSet);
6850 }
6851 }
6852 }
6853
6854 // C++ [over.built]p19:
6855 //
6856 // For every pair (T, VQ), where T is any type and VQ is either
6857 // volatile or empty, there exist candidate operator functions
6858 // of the form
6859 //
6860 // T*VQ& operator=(T*VQ&, T*);
6861 //
6862 // C++ [over.built]p21:
6863 //
6864 // For every pair (T, VQ), where T is a cv-qualified or
6865 // cv-unqualified object type and VQ is either volatile or
6866 // empty, there exist candidate operator functions of the form
6867 //
6868 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6869 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6870 void addAssignmentPointerOverloads(bool isEqualOp) {
6871 /// Set of (canonical) types that we've already handled.
6872 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6873
6874 for (BuiltinCandidateTypeSet::iterator
6875 Ptr = CandidateTypes[0].pointer_begin(),
6876 PtrEnd = CandidateTypes[0].pointer_end();
6877 Ptr != PtrEnd; ++Ptr) {
6878 // If this is operator=, keep track of the builtin candidates we added.
6879 if (isEqualOp)
6880 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006881 else if (!(*Ptr)->getPointeeType()->isObjectType())
6882 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006883
6884 // non-volatile version
6885 QualType ParamTypes[2] = {
6886 S.Context.getLValueReferenceType(*Ptr),
6887 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6888 };
6889 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6890 /*IsAssigmentOperator=*/ isEqualOp);
6891
6892 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6893 VisibleTypeConversionsQuals.hasVolatile()) {
6894 // volatile version
6895 ParamTypes[0] =
6896 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6897 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6898 /*IsAssigmentOperator=*/isEqualOp);
6899 }
6900 }
6901
6902 if (isEqualOp) {
6903 for (BuiltinCandidateTypeSet::iterator
6904 Ptr = CandidateTypes[1].pointer_begin(),
6905 PtrEnd = CandidateTypes[1].pointer_end();
6906 Ptr != PtrEnd; ++Ptr) {
6907 // Make sure we don't add the same candidate twice.
6908 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6909 continue;
6910
Chandler Carruth6df868e2010-12-12 08:17:55 +00006911 QualType ParamTypes[2] = {
6912 S.Context.getLValueReferenceType(*Ptr),
6913 *Ptr,
6914 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006915
6916 // non-volatile version
6917 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6918 /*IsAssigmentOperator=*/true);
6919
6920 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6921 VisibleTypeConversionsQuals.hasVolatile()) {
6922 // volatile version
6923 ParamTypes[0] =
6924 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00006925 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6926 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006927 }
6928 }
6929 }
6930 }
6931
6932 // C++ [over.built]p18:
6933 //
6934 // For every triple (L, VQ, R), where L is an arithmetic type,
6935 // VQ is either volatile or empty, and R is a promoted
6936 // arithmetic type, there exist candidate operator functions of
6937 // the form
6938 //
6939 // VQ L& operator=(VQ L&, R);
6940 // VQ L& operator*=(VQ L&, R);
6941 // VQ L& operator/=(VQ L&, R);
6942 // VQ L& operator+=(VQ L&, R);
6943 // VQ L& operator-=(VQ L&, R);
6944 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006945 if (!HasArithmeticOrEnumeralCandidateType)
6946 return;
6947
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006948 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6949 for (unsigned Right = FirstPromotedArithmeticType;
6950 Right < LastPromotedArithmeticType; ++Right) {
6951 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00006952 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006953
6954 // Add this built-in operator as a candidate (VQ is empty).
6955 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006956 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006957 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6958 /*IsAssigmentOperator=*/isEqualOp);
6959
6960 // Add this built-in operator as a candidate (VQ is 'volatile').
6961 if (VisibleTypeConversionsQuals.hasVolatile()) {
6962 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006963 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006964 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006965 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6966 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006967 /*IsAssigmentOperator=*/isEqualOp);
6968 }
6969 }
6970 }
6971
6972 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6973 for (BuiltinCandidateTypeSet::iterator
6974 Vec1 = CandidateTypes[0].vector_begin(),
6975 Vec1End = CandidateTypes[0].vector_end();
6976 Vec1 != Vec1End; ++Vec1) {
6977 for (BuiltinCandidateTypeSet::iterator
6978 Vec2 = CandidateTypes[1].vector_begin(),
6979 Vec2End = CandidateTypes[1].vector_end();
6980 Vec2 != Vec2End; ++Vec2) {
6981 QualType ParamTypes[2];
6982 ParamTypes[1] = *Vec2;
6983 // Add this built-in operator as a candidate (VQ is empty).
6984 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6985 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6986 /*IsAssigmentOperator=*/isEqualOp);
6987
6988 // Add this built-in operator as a candidate (VQ is 'volatile').
6989 if (VisibleTypeConversionsQuals.hasVolatile()) {
6990 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6991 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006992 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6993 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006994 /*IsAssigmentOperator=*/isEqualOp);
6995 }
6996 }
6997 }
6998 }
6999
7000 // C++ [over.built]p22:
7001 //
7002 // For every triple (L, VQ, R), where L is an integral type, VQ
7003 // is either volatile or empty, and R is a promoted integral
7004 // type, there exist candidate operator functions of the form
7005 //
7006 // VQ L& operator%=(VQ L&, R);
7007 // VQ L& operator<<=(VQ L&, R);
7008 // VQ L& operator>>=(VQ L&, R);
7009 // VQ L& operator&=(VQ L&, R);
7010 // VQ L& operator^=(VQ L&, R);
7011 // VQ L& operator|=(VQ L&, R);
7012 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007013 if (!HasArithmeticOrEnumeralCandidateType)
7014 return;
7015
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007016 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7017 for (unsigned Right = FirstPromotedIntegralType;
7018 Right < LastPromotedIntegralType; ++Right) {
7019 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007020 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007021
7022 // Add this built-in operator as a candidate (VQ is empty).
7023 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007024 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007025 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7026 if (VisibleTypeConversionsQuals.hasVolatile()) {
7027 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007028 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007029 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7030 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7031 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7032 CandidateSet);
7033 }
7034 }
7035 }
7036 }
7037
7038 // C++ [over.operator]p23:
7039 //
7040 // There also exist candidate operator functions of the form
7041 //
7042 // bool operator!(bool);
7043 // bool operator&&(bool, bool);
7044 // bool operator||(bool, bool);
7045 void addExclaimOverload() {
7046 QualType ParamTy = S.Context.BoolTy;
7047 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7048 /*IsAssignmentOperator=*/false,
7049 /*NumContextualBoolArguments=*/1);
7050 }
7051 void addAmpAmpOrPipePipeOverload() {
7052 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7053 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7054 /*IsAssignmentOperator=*/false,
7055 /*NumContextualBoolArguments=*/2);
7056 }
7057
7058 // C++ [over.built]p13:
7059 //
7060 // For every cv-qualified or cv-unqualified object type T there
7061 // exist candidate operator functions of the form
7062 //
7063 // T* operator+(T*, ptrdiff_t); [ABOVE]
7064 // T& operator[](T*, ptrdiff_t);
7065 // T* operator-(T*, ptrdiff_t); [ABOVE]
7066 // T* operator+(ptrdiff_t, T*); [ABOVE]
7067 // T& operator[](ptrdiff_t, T*);
7068 void addSubscriptOverloads() {
7069 for (BuiltinCandidateTypeSet::iterator
7070 Ptr = CandidateTypes[0].pointer_begin(),
7071 PtrEnd = CandidateTypes[0].pointer_end();
7072 Ptr != PtrEnd; ++Ptr) {
7073 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7074 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007075 if (!PointeeType->isObjectType())
7076 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007077
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007078 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7079
7080 // T& operator[](T*, ptrdiff_t)
7081 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7082 }
7083
7084 for (BuiltinCandidateTypeSet::iterator
7085 Ptr = CandidateTypes[1].pointer_begin(),
7086 PtrEnd = CandidateTypes[1].pointer_end();
7087 Ptr != PtrEnd; ++Ptr) {
7088 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7089 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007090 if (!PointeeType->isObjectType())
7091 continue;
7092
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007093 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7094
7095 // T& operator[](ptrdiff_t, T*)
7096 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7097 }
7098 }
7099
7100 // C++ [over.built]p11:
7101 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7102 // C1 is the same type as C2 or is a derived class of C2, T is an object
7103 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7104 // there exist candidate operator functions of the form
7105 //
7106 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7107 //
7108 // where CV12 is the union of CV1 and CV2.
7109 void addArrowStarOverloads() {
7110 for (BuiltinCandidateTypeSet::iterator
7111 Ptr = CandidateTypes[0].pointer_begin(),
7112 PtrEnd = CandidateTypes[0].pointer_end();
7113 Ptr != PtrEnd; ++Ptr) {
7114 QualType C1Ty = (*Ptr);
7115 QualType C1;
7116 QualifierCollector Q1;
7117 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7118 if (!isa<RecordType>(C1))
7119 continue;
7120 // heuristic to reduce number of builtin candidates in the set.
7121 // Add volatile/restrict version only if there are conversions to a
7122 // volatile/restrict type.
7123 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7124 continue;
7125 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7126 continue;
7127 for (BuiltinCandidateTypeSet::iterator
7128 MemPtr = CandidateTypes[1].member_pointer_begin(),
7129 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7130 MemPtr != MemPtrEnd; ++MemPtr) {
7131 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7132 QualType C2 = QualType(mptr->getClass(), 0);
7133 C2 = C2.getUnqualifiedType();
7134 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7135 break;
7136 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7137 // build CV12 T&
7138 QualType T = mptr->getPointeeType();
7139 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7140 T.isVolatileQualified())
7141 continue;
7142 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7143 T.isRestrictQualified())
7144 continue;
7145 T = Q1.apply(S.Context, T);
7146 QualType ResultTy = S.Context.getLValueReferenceType(T);
7147 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7148 }
7149 }
7150 }
7151
7152 // Note that we don't consider the first argument, since it has been
7153 // contextually converted to bool long ago. The candidates below are
7154 // therefore added as binary.
7155 //
7156 // C++ [over.built]p25:
7157 // For every type T, where T is a pointer, pointer-to-member, or scoped
7158 // enumeration type, there exist candidate operator functions of the form
7159 //
7160 // T operator?(bool, T, T);
7161 //
7162 void addConditionalOperatorOverloads() {
7163 /// Set of (canonical) types that we've already handled.
7164 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7165
7166 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7167 for (BuiltinCandidateTypeSet::iterator
7168 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7169 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7170 Ptr != PtrEnd; ++Ptr) {
7171 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7172 continue;
7173
7174 QualType ParamTypes[2] = { *Ptr, *Ptr };
7175 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7176 }
7177
7178 for (BuiltinCandidateTypeSet::iterator
7179 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7180 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7181 MemPtr != MemPtrEnd; ++MemPtr) {
7182 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7183 continue;
7184
7185 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7186 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7187 }
7188
7189 if (S.getLangOptions().CPlusPlus0x) {
7190 for (BuiltinCandidateTypeSet::iterator
7191 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7192 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7193 Enum != EnumEnd; ++Enum) {
7194 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7195 continue;
7196
7197 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7198 continue;
7199
7200 QualType ParamTypes[2] = { *Enum, *Enum };
7201 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7202 }
7203 }
7204 }
7205 }
7206};
7207
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007208} // end anonymous namespace
7209
7210/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7211/// operator overloads to the candidate set (C++ [over.built]), based
7212/// on the operator @p Op and the arguments given. For example, if the
7213/// operator is a binary '+', this routine might add "int
7214/// operator+(int, int)" to cover integer addition.
7215void
7216Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7217 SourceLocation OpLoc,
7218 Expr **Args, unsigned NumArgs,
7219 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007220 // Find all of the types that the arguments can convert to, but only
7221 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007222 // that make use of these types. Also record whether we encounter non-record
7223 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007224 Qualifiers VisibleTypeConversionsQuals;
7225 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007226 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7227 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007228
7229 bool HasNonRecordCandidateType = false;
7230 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007231 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007232 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7233 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7234 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7235 OpLoc,
7236 true,
7237 (Op == OO_Exclaim ||
7238 Op == OO_AmpAmp ||
7239 Op == OO_PipePipe),
7240 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007241 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7242 CandidateTypes[ArgIdx].hasNonRecordTypes();
7243 HasArithmeticOrEnumeralCandidateType =
7244 HasArithmeticOrEnumeralCandidateType ||
7245 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007246 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007247
Chandler Carruth6a577462010-12-13 01:44:01 +00007248 // Exit early when no non-record types have been added to the candidate set
7249 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007250 //
7251 // We can't exit early for !, ||, or &&, since there we have always have
7252 // 'bool' overloads.
7253 if (!HasNonRecordCandidateType &&
7254 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007255 return;
7256
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007257 // Setup an object to manage the common state for building overloads.
7258 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7259 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007260 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007261 CandidateTypes, CandidateSet);
7262
7263 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007264 switch (Op) {
7265 case OO_None:
7266 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007267 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007268
Chandler Carruthabb71842010-12-12 08:51:33 +00007269 case OO_New:
7270 case OO_Delete:
7271 case OO_Array_New:
7272 case OO_Array_Delete:
7273 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007274 llvm_unreachable(
7275 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007276
7277 case OO_Comma:
7278 case OO_Arrow:
7279 // C++ [over.match.oper]p3:
7280 // -- For the operator ',', the unary operator '&', or the
7281 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007282 break;
7283
7284 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007285 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007286 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007287 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007288
7289 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007290 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007291 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007292 } else {
7293 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7294 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7295 }
Douglas Gregor74253732008-11-19 15:42:04 +00007296 break;
7297
Chandler Carruthabb71842010-12-12 08:51:33 +00007298 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007299 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007300 OpBuilder.addUnaryStarPointerOverloads();
7301 else
7302 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7303 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007304
Chandler Carruthabb71842010-12-12 08:51:33 +00007305 case OO_Slash:
7306 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007307 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007308
7309 case OO_PlusPlus:
7310 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007311 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7312 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007313 break;
7314
Douglas Gregor19b7b152009-08-24 13:43:27 +00007315 case OO_EqualEqual:
7316 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007317 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007318 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007319
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007320 case OO_Less:
7321 case OO_Greater:
7322 case OO_LessEqual:
7323 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007324 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007325 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7326 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007327
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007328 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007329 case OO_Caret:
7330 case OO_Pipe:
7331 case OO_LessLess:
7332 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007333 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007334 break;
7335
Chandler Carruthabb71842010-12-12 08:51:33 +00007336 case OO_Amp: // '&' is either unary or binary
7337 if (NumArgs == 1)
7338 // C++ [over.match.oper]p3:
7339 // -- For the operator ',', the unary operator '&', or the
7340 // operator '->', the built-in candidates set is empty.
7341 break;
7342
7343 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7344 break;
7345
7346 case OO_Tilde:
7347 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7348 break;
7349
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007350 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007351 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007352 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007353
7354 case OO_PlusEqual:
7355 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007356 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007357 // Fall through.
7358
7359 case OO_StarEqual:
7360 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007361 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007362 break;
7363
7364 case OO_PercentEqual:
7365 case OO_LessLessEqual:
7366 case OO_GreaterGreaterEqual:
7367 case OO_AmpEqual:
7368 case OO_CaretEqual:
7369 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007370 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007371 break;
7372
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007373 case OO_Exclaim:
7374 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007375 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007376
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007377 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007378 case OO_PipePipe:
7379 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007380 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007381
7382 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007383 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007384 break;
7385
7386 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007387 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007388 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007389
7390 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007391 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007392 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7393 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007394 }
7395}
7396
Douglas Gregorfa047642009-02-04 00:32:51 +00007397/// \brief Add function candidates found via argument-dependent lookup
7398/// to the set of overloading candidates.
7399///
7400/// This routine performs argument-dependent name lookup based on the
7401/// given function name (which may also be an operator name) and adds
7402/// all of the overload candidates found by ADL to the overload
7403/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007404void
Douglas Gregorfa047642009-02-04 00:32:51 +00007405Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00007406 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00007407 Expr **Args, unsigned NumArgs,
Douglas Gregor67714232011-03-03 02:41:12 +00007408 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007409 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00007410 bool PartialOverloading,
7411 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00007412 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007413
John McCalla113e722010-01-26 06:04:06 +00007414 // FIXME: This approach for uniquing ADL results (and removing
7415 // redundant candidates from the set) relies on pointer-equality,
7416 // which means we need to key off the canonical decl. However,
7417 // always going back to the canonical decl might not get us the
7418 // right set of default arguments. What default arguments are
7419 // we supposed to consider on ADL candidates, anyway?
7420
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007421 // FIXME: Pass in the explicit template arguments?
Richard Smithad762fc2011-04-14 22:09:26 +00007422 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
7423 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00007424
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007425 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007426 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7427 CandEnd = CandidateSet.end();
7428 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007429 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007430 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007431 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007432 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007433 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007434
7435 // For each of the ADL candidates we found, add it to the overload
7436 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007437 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007438 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007439 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007440 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007441 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007442
John McCall9aa472c2010-03-19 07:35:19 +00007443 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00007444 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007445 } else
John McCall6e266892010-01-26 03:27:55 +00007446 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007447 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00007448 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007449 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007450}
7451
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007452/// isBetterOverloadCandidate - Determines whether the first overload
7453/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007454bool
John McCall120d63c2010-08-24 20:38:10 +00007455isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007456 const OverloadCandidate &Cand1,
7457 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007458 SourceLocation Loc,
7459 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007460 // Define viable functions to be better candidates than non-viable
7461 // functions.
7462 if (!Cand2.Viable)
7463 return Cand1.Viable;
7464 else if (!Cand1.Viable)
7465 return false;
7466
Douglas Gregor88a35142008-12-22 05:46:06 +00007467 // C++ [over.match.best]p1:
7468 //
7469 // -- if F is a static member function, ICS1(F) is defined such
7470 // that ICS1(F) is neither better nor worse than ICS1(G) for
7471 // any function G, and, symmetrically, ICS1(G) is neither
7472 // better nor worse than ICS1(F).
7473 unsigned StartArg = 0;
7474 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7475 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007476
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007477 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007478 // A viable function F1 is defined to be a better function than another
7479 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007480 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007481 unsigned NumArgs = Cand1.NumConversions;
7482 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007483 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007484 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007485 switch (CompareImplicitConversionSequences(S,
7486 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007487 Cand2.Conversions[ArgIdx])) {
7488 case ImplicitConversionSequence::Better:
7489 // Cand1 has a better conversion sequence.
7490 HasBetterConversion = true;
7491 break;
7492
7493 case ImplicitConversionSequence::Worse:
7494 // Cand1 can't be better than Cand2.
7495 return false;
7496
7497 case ImplicitConversionSequence::Indistinguishable:
7498 // Do nothing.
7499 break;
7500 }
7501 }
7502
Mike Stump1eb44332009-09-09 15:08:12 +00007503 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007504 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007505 if (HasBetterConversion)
7506 return true;
7507
Mike Stump1eb44332009-09-09 15:08:12 +00007508 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007509 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007510 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007511 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7512 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007513
7514 // -- F1 and F2 are function template specializations, and the function
7515 // template for F1 is more specialized than the template for F2
7516 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007517 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007518 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007519 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007520 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007521 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7522 Cand2.Function->getPrimaryTemplate(),
7523 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007524 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007525 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007526 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007527 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007528 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007529
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007530 // -- the context is an initialization by user-defined conversion
7531 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7532 // from the return type of F1 to the destination type (i.e.,
7533 // the type of the entity being initialized) is a better
7534 // conversion sequence than the standard conversion sequence
7535 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007536 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007537 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007538 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00007539 switch (CompareStandardConversionSequences(S,
7540 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007541 Cand2.FinalConversion)) {
7542 case ImplicitConversionSequence::Better:
7543 // Cand1 has a better conversion sequence.
7544 return true;
7545
7546 case ImplicitConversionSequence::Worse:
7547 // Cand1 can't be better than Cand2.
7548 return false;
7549
7550 case ImplicitConversionSequence::Indistinguishable:
7551 // Do nothing
7552 break;
7553 }
7554 }
7555
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007556 return false;
7557}
7558
Mike Stump1eb44332009-09-09 15:08:12 +00007559/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007560/// within an overload candidate set.
7561///
7562/// \param CandidateSet the set of candidate functions.
7563///
7564/// \param Loc the location of the function name (or operator symbol) for
7565/// which overload resolution occurs.
7566///
Mike Stump1eb44332009-09-09 15:08:12 +00007567/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00007568/// function, Best points to the candidate function found.
7569///
7570/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007571OverloadingResult
7572OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007573 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007574 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007575 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007576 Best = end();
7577 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7578 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007579 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007580 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007581 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007582 }
7583
7584 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007585 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007586 return OR_No_Viable_Function;
7587
7588 // Make sure that this function is better than every other viable
7589 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007590 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007591 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007592 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007593 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007594 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007595 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007596 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007597 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007598 }
Mike Stump1eb44332009-09-09 15:08:12 +00007599
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007600 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007601 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007602 (Best->Function->isDeleted() ||
7603 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007604 return OR_Deleted;
7605
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007606 return OR_Success;
7607}
7608
John McCall3c80f572010-01-12 02:15:36 +00007609namespace {
7610
7611enum OverloadCandidateKind {
7612 oc_function,
7613 oc_method,
7614 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007615 oc_function_template,
7616 oc_method_template,
7617 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007618 oc_implicit_default_constructor,
7619 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007620 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007621 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007622 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007623 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007624};
7625
John McCall220ccbf2010-01-13 00:25:19 +00007626OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7627 FunctionDecl *Fn,
7628 std::string &Description) {
7629 bool isTemplate = false;
7630
7631 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7632 isTemplate = true;
7633 Description = S.getTemplateArgumentBindingsText(
7634 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7635 }
John McCallb1622a12010-01-06 09:43:14 +00007636
7637 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007638 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007639 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007640
Sebastian Redlf677ea32011-02-05 19:23:19 +00007641 if (Ctor->getInheritedConstructor())
7642 return oc_implicit_inherited_constructor;
7643
Sean Hunt82713172011-05-25 23:16:36 +00007644 if (Ctor->isDefaultConstructor())
7645 return oc_implicit_default_constructor;
7646
7647 if (Ctor->isMoveConstructor())
7648 return oc_implicit_move_constructor;
7649
7650 assert(Ctor->isCopyConstructor() &&
7651 "unexpected sort of implicit constructor");
7652 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007653 }
7654
7655 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7656 // This actually gets spelled 'candidate function' for now, but
7657 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007658 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007659 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007660
Sean Hunt82713172011-05-25 23:16:36 +00007661 if (Meth->isMoveAssignmentOperator())
7662 return oc_implicit_move_assignment;
7663
Douglas Gregoref7d78b2012-02-10 08:36:38 +00007664 if (Meth->isCopyAssignmentOperator())
7665 return oc_implicit_copy_assignment;
7666
7667 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7668 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00007669 }
7670
John McCall220ccbf2010-01-13 00:25:19 +00007671 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007672}
7673
Sebastian Redlf677ea32011-02-05 19:23:19 +00007674void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7675 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7676 if (!Ctor) return;
7677
7678 Ctor = Ctor->getInheritedConstructor();
7679 if (!Ctor) return;
7680
7681 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7682}
7683
John McCall3c80f572010-01-12 02:15:36 +00007684} // end anonymous namespace
7685
7686// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00007687void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00007688 std::string FnDesc;
7689 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00007690 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7691 << (unsigned) K << FnDesc;
7692 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7693 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007694 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007695}
7696
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007697//Notes the location of all overload candidates designated through
7698// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00007699void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007700 assert(OverloadedExpr->getType() == Context.OverloadTy);
7701
7702 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7703 OverloadExpr *OvlExpr = Ovl.Expression;
7704
7705 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7706 IEnd = OvlExpr->decls_end();
7707 I != IEnd; ++I) {
7708 if (FunctionTemplateDecl *FunTmpl =
7709 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007710 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007711 } else if (FunctionDecl *Fun
7712 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007713 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007714 }
7715 }
7716}
7717
John McCall1d318332010-01-12 00:44:57 +00007718/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7719/// "lead" diagnostic; it will be given two arguments, the source and
7720/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00007721void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7722 Sema &S,
7723 SourceLocation CaretLoc,
7724 const PartialDiagnostic &PDiag) const {
7725 S.Diag(CaretLoc, PDiag)
7726 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00007727 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00007728 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7729 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00007730 }
John McCall81201622010-01-08 04:41:39 +00007731}
7732
John McCall1d318332010-01-12 00:44:57 +00007733namespace {
7734
John McCalladbb8f82010-01-13 09:16:55 +00007735void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7736 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7737 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00007738 assert(Cand->Function && "for now, candidate must be a function");
7739 FunctionDecl *Fn = Cand->Function;
7740
7741 // There's a conversion slot for the object argument if this is a
7742 // non-constructor method. Note that 'I' corresponds the
7743 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00007744 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00007745 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00007746 if (I == 0)
7747 isObjectArgument = true;
7748 else
7749 I--;
John McCall220ccbf2010-01-13 00:25:19 +00007750 }
7751
John McCall220ccbf2010-01-13 00:25:19 +00007752 std::string FnDesc;
7753 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7754
John McCalladbb8f82010-01-13 09:16:55 +00007755 Expr *FromExpr = Conv.Bad.FromExpr;
7756 QualType FromTy = Conv.Bad.getFromType();
7757 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00007758
John McCall5920dbb2010-02-02 02:42:52 +00007759 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00007760 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00007761 Expr *E = FromExpr->IgnoreParens();
7762 if (isa<UnaryOperator>(E))
7763 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00007764 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00007765
7766 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7767 << (unsigned) FnKind << FnDesc
7768 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7769 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007770 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00007771 return;
7772 }
7773
John McCall258b2032010-01-23 08:10:49 +00007774 // Do some hand-waving analysis to see if the non-viability is due
7775 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00007776 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7777 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7778 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7779 CToTy = RT->getPointeeType();
7780 else {
7781 // TODO: detect and diagnose the full richness of const mismatches.
7782 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7783 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7784 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7785 }
7786
7787 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7788 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7789 // It is dumb that we have to do this here.
7790 while (isa<ArrayType>(CFromTy))
7791 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7792 while (isa<ArrayType>(CToTy))
7793 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7794
7795 Qualifiers FromQs = CFromTy.getQualifiers();
7796 Qualifiers ToQs = CToTy.getQualifiers();
7797
7798 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7799 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7800 << (unsigned) FnKind << FnDesc
7801 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7802 << FromTy
7803 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7804 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007805 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007806 return;
7807 }
7808
John McCallf85e1932011-06-15 23:02:42 +00007809 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00007810 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00007811 << (unsigned) FnKind << FnDesc
7812 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7813 << FromTy
7814 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7815 << (unsigned) isObjectArgument << I+1;
7816 MaybeEmitInheritedConstructorNote(S, Fn);
7817 return;
7818 }
7819
Douglas Gregor028ea4b2011-04-26 23:16:46 +00007820 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7821 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7822 << (unsigned) FnKind << FnDesc
7823 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7824 << FromTy
7825 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7826 << (unsigned) isObjectArgument << I+1;
7827 MaybeEmitInheritedConstructorNote(S, Fn);
7828 return;
7829 }
7830
John McCall651f3ee2010-01-14 03:28:57 +00007831 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7832 assert(CVR && "unexpected qualifiers mismatch");
7833
7834 if (isObjectArgument) {
7835 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7836 << (unsigned) FnKind << FnDesc
7837 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7838 << FromTy << (CVR - 1);
7839 } else {
7840 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7841 << (unsigned) FnKind << FnDesc
7842 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7843 << FromTy << (CVR - 1) << I+1;
7844 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00007845 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007846 return;
7847 }
7848
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00007849 // Special diagnostic for failure to convert an initializer list, since
7850 // telling the user that it has type void is not useful.
7851 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7852 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7853 << (unsigned) FnKind << FnDesc
7854 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7855 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7856 MaybeEmitInheritedConstructorNote(S, Fn);
7857 return;
7858 }
7859
John McCall258b2032010-01-23 08:10:49 +00007860 // Diagnose references or pointers to incomplete types differently,
7861 // since it's far from impossible that the incompleteness triggered
7862 // the failure.
7863 QualType TempFromTy = FromTy.getNonReferenceType();
7864 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7865 TempFromTy = PTy->getPointeeType();
7866 if (TempFromTy->isIncompleteType()) {
7867 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7868 << (unsigned) FnKind << FnDesc
7869 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7870 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007871 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00007872 return;
7873 }
7874
Douglas Gregor85789812010-06-30 23:01:39 +00007875 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007876 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00007877 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7878 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7879 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7880 FromPtrTy->getPointeeType()) &&
7881 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7882 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007883 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00007884 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007885 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00007886 }
7887 } else if (const ObjCObjectPointerType *FromPtrTy
7888 = FromTy->getAs<ObjCObjectPointerType>()) {
7889 if (const ObjCObjectPointerType *ToPtrTy
7890 = ToTy->getAs<ObjCObjectPointerType>())
7891 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7892 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7893 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7894 FromPtrTy->getPointeeType()) &&
7895 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007896 BaseToDerivedConversion = 2;
7897 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7898 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7899 !FromTy->isIncompleteType() &&
7900 !ToRefTy->getPointeeType()->isIncompleteType() &&
7901 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7902 BaseToDerivedConversion = 3;
7903 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007904
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007905 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007906 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007907 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00007908 << (unsigned) FnKind << FnDesc
7909 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007910 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007911 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007912 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00007913 return;
7914 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007915
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00007916 if (isa<ObjCObjectPointerType>(CFromTy) &&
7917 isa<PointerType>(CToTy)) {
7918 Qualifiers FromQs = CFromTy.getQualifiers();
7919 Qualifiers ToQs = CToTy.getQualifiers();
7920 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7921 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7922 << (unsigned) FnKind << FnDesc
7923 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7924 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7925 MaybeEmitInheritedConstructorNote(S, Fn);
7926 return;
7927 }
7928 }
7929
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007930 // Emit the generic diagnostic and, optionally, add the hints to it.
7931 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7932 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00007933 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007934 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7935 << (unsigned) (Cand->Fix.Kind);
7936
7937 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00007938 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
7939 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007940 FDiag << *HI;
7941 S.Diag(Fn->getLocation(), FDiag);
7942
Sebastian Redlf677ea32011-02-05 19:23:19 +00007943 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00007944}
7945
7946void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7947 unsigned NumFormalArgs) {
7948 // TODO: treat calls to a missing default constructor as a special case
7949
7950 FunctionDecl *Fn = Cand->Function;
7951 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7952
7953 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007954
Douglas Gregor439d3c32011-05-05 00:13:13 +00007955 // With invalid overloaded operators, it's possible that we think we
7956 // have an arity mismatch when it fact it looks like we have the
7957 // right number of arguments, because only overloaded operators have
7958 // the weird behavior of overloading member and non-member functions.
7959 // Just don't report anything.
7960 if (Fn->isInvalidDecl() &&
7961 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7962 return;
7963
John McCalladbb8f82010-01-13 09:16:55 +00007964 // at least / at most / exactly
7965 unsigned mode, modeCount;
7966 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00007967 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7968 (Cand->FailureKind == ovl_fail_bad_deduction &&
7969 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007970 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00007971 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00007972 mode = 0; // "at least"
7973 else
7974 mode = 2; // "exactly"
7975 modeCount = MinParams;
7976 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00007977 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7978 (Cand->FailureKind == ovl_fail_bad_deduction &&
7979 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00007980 if (MinParams != FnTy->getNumArgs())
7981 mode = 1; // "at most"
7982 else
7983 mode = 2; // "exactly"
7984 modeCount = FnTy->getNumArgs();
7985 }
7986
7987 std::string Description;
7988 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7989
7990 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007991 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregora18592e2010-05-08 18:13:28 +00007992 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007993 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00007994}
7995
John McCall342fec42010-02-01 18:53:26 +00007996/// Diagnose a failed template-argument deduction.
7997void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7998 Expr **Args, unsigned NumArgs) {
7999 FunctionDecl *Fn = Cand->Function; // pattern
8000
Douglas Gregora9333192010-05-08 17:41:32 +00008001 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008002 NamedDecl *ParamD;
8003 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8004 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8005 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008006 switch (Cand->DeductionFailure.Result) {
8007 case Sema::TDK_Success:
8008 llvm_unreachable("TDK_success while diagnosing bad deduction");
8009
8010 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008011 assert(ParamD && "no parameter found for incomplete deduction result");
8012 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8013 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008014 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008015 return;
8016 }
8017
John McCall57e97782010-08-05 09:05:08 +00008018 case Sema::TDK_Underqualified: {
8019 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8020 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8021
8022 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8023
8024 // Param will have been canonicalized, but it should just be a
8025 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008026 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008027 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008028 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008029 assert(S.Context.hasSameType(Param, NonCanonParam));
8030
8031 // Arg has also been canonicalized, but there's nothing we can do
8032 // about that. It also doesn't matter as much, because it won't
8033 // have any template parameters in it (because deduction isn't
8034 // done on dependent types).
8035 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8036
8037 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8038 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008039 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008040 return;
8041 }
8042
8043 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008044 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008045 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008046 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008047 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008048 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008049 which = 1;
8050 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008051 which = 2;
8052 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008053
Douglas Gregora9333192010-05-08 17:41:32 +00008054 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008055 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008056 << *Cand->DeductionFailure.getFirstArg()
8057 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008058 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008059 return;
8060 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008061
Douglas Gregorf1a84452010-05-08 19:15:54 +00008062 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008063 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008064 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008065 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008066 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8067 << ParamD->getDeclName();
8068 else {
8069 int index = 0;
8070 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8071 index = TTP->getIndex();
8072 else if (NonTypeTemplateParmDecl *NTTP
8073 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8074 index = NTTP->getIndex();
8075 else
8076 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008077 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008078 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8079 << (index + 1);
8080 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008081 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008082 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008083
Douglas Gregora18592e2010-05-08 18:13:28 +00008084 case Sema::TDK_TooManyArguments:
8085 case Sema::TDK_TooFewArguments:
8086 DiagnoseArityMismatch(S, Cand, NumArgs);
8087 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008088
8089 case Sema::TDK_InstantiationDepth:
8090 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008091 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008092 return;
8093
8094 case Sema::TDK_SubstitutionFailure: {
8095 std::string ArgString;
8096 if (TemplateArgumentList *Args
8097 = Cand->DeductionFailure.getTemplateArgumentList())
8098 ArgString = S.getTemplateArgumentBindingsText(
8099 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
8100 *Args);
8101 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8102 << ArgString;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008103 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008104 return;
8105 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008106
John McCall342fec42010-02-01 18:53:26 +00008107 // TODO: diagnose these individually, then kill off
8108 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00008109 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00008110 case Sema::TDK_FailedOverloadResolution:
8111 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008112 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008113 return;
8114 }
8115}
8116
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008117/// CUDA: diagnose an invalid call across targets.
8118void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8119 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8120 FunctionDecl *Callee = Cand->Function;
8121
8122 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8123 CalleeTarget = S.IdentifyCUDATarget(Callee);
8124
8125 std::string FnDesc;
8126 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8127
8128 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8129 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8130}
8131
John McCall342fec42010-02-01 18:53:26 +00008132/// Generates a 'note' diagnostic for an overload candidate. We've
8133/// already generated a primary error at the call site.
8134///
8135/// It really does need to be a single diagnostic with its caret
8136/// pointed at the candidate declaration. Yes, this creates some
8137/// major challenges of technical writing. Yes, this makes pointing
8138/// out problems with specific arguments quite awkward. It's still
8139/// better than generating twenty screens of text for every failed
8140/// overload.
8141///
8142/// It would be great to be able to express per-candidate problems
8143/// more richly for those diagnostic clients that cared, but we'd
8144/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008145void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8146 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008147 FunctionDecl *Fn = Cand->Function;
8148
John McCall81201622010-01-08 04:41:39 +00008149 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008150 if (Cand->Viable && (Fn->isDeleted() ||
8151 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008152 std::string FnDesc;
8153 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008154
8155 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00008156 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008157 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008158 return;
John McCall81201622010-01-08 04:41:39 +00008159 }
8160
John McCall220ccbf2010-01-13 00:25:19 +00008161 // We don't really have anything else to say about viable candidates.
8162 if (Cand->Viable) {
8163 S.NoteOverloadCandidate(Fn);
8164 return;
8165 }
John McCall1d318332010-01-12 00:44:57 +00008166
John McCalladbb8f82010-01-13 09:16:55 +00008167 switch (Cand->FailureKind) {
8168 case ovl_fail_too_many_arguments:
8169 case ovl_fail_too_few_arguments:
8170 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008171
John McCalladbb8f82010-01-13 09:16:55 +00008172 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00008173 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
8174
John McCall717e8912010-01-23 05:17:32 +00008175 case ovl_fail_trivial_conversion:
8176 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008177 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008178 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008179
John McCallb1bdc622010-02-25 01:37:24 +00008180 case ovl_fail_bad_conversion: {
8181 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008182 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008183 if (Cand->Conversions[I].isBad())
8184 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008185
John McCalladbb8f82010-01-13 09:16:55 +00008186 // FIXME: this currently happens when we're called from SemaInit
8187 // when user-conversion overload fails. Figure out how to handle
8188 // those conditions and diagnose them well.
8189 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008190 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008191
8192 case ovl_fail_bad_target:
8193 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008194 }
John McCalla1d7d622010-01-08 00:58:21 +00008195}
8196
8197void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8198 // Desugar the type of the surrogate down to a function type,
8199 // retaining as many typedefs as possible while still showing
8200 // the function type (and, therefore, its parameter types).
8201 QualType FnType = Cand->Surrogate->getConversionType();
8202 bool isLValueReference = false;
8203 bool isRValueReference = false;
8204 bool isPointer = false;
8205 if (const LValueReferenceType *FnTypeRef =
8206 FnType->getAs<LValueReferenceType>()) {
8207 FnType = FnTypeRef->getPointeeType();
8208 isLValueReference = true;
8209 } else if (const RValueReferenceType *FnTypeRef =
8210 FnType->getAs<RValueReferenceType>()) {
8211 FnType = FnTypeRef->getPointeeType();
8212 isRValueReference = true;
8213 }
8214 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8215 FnType = FnTypePtr->getPointeeType();
8216 isPointer = true;
8217 }
8218 // Desugar down to a function type.
8219 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8220 // Reconstruct the pointer/reference as appropriate.
8221 if (isPointer) FnType = S.Context.getPointerType(FnType);
8222 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8223 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8224
8225 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8226 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008227 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008228}
8229
8230void NoteBuiltinOperatorCandidate(Sema &S,
8231 const char *Opc,
8232 SourceLocation OpLoc,
8233 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008234 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008235 std::string TypeStr("operator");
8236 TypeStr += Opc;
8237 TypeStr += "(";
8238 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008239 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008240 TypeStr += ")";
8241 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8242 } else {
8243 TypeStr += ", ";
8244 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8245 TypeStr += ")";
8246 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8247 }
8248}
8249
8250void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8251 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008252 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008253 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8254 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008255 if (ICS.isBad()) break; // all meaningless after first invalid
8256 if (!ICS.isAmbiguous()) continue;
8257
John McCall120d63c2010-08-24 20:38:10 +00008258 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008259 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008260 }
8261}
8262
John McCall1b77e732010-01-15 23:32:50 +00008263SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8264 if (Cand->Function)
8265 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008266 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008267 return Cand->Surrogate->getLocation();
8268 return SourceLocation();
8269}
8270
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008271static unsigned
8272RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008273 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008274 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008275 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008276
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008277 case Sema::TDK_Incomplete:
8278 return 1;
8279
8280 case Sema::TDK_Underqualified:
8281 case Sema::TDK_Inconsistent:
8282 return 2;
8283
8284 case Sema::TDK_SubstitutionFailure:
8285 case Sema::TDK_NonDeducedMismatch:
8286 return 3;
8287
8288 case Sema::TDK_InstantiationDepth:
8289 case Sema::TDK_FailedOverloadResolution:
8290 return 4;
8291
8292 case Sema::TDK_InvalidExplicitArguments:
8293 return 5;
8294
8295 case Sema::TDK_TooManyArguments:
8296 case Sema::TDK_TooFewArguments:
8297 return 6;
8298 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008299 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008300}
8301
John McCallbf65c0b2010-01-12 00:48:53 +00008302struct CompareOverloadCandidatesForDisplay {
8303 Sema &S;
8304 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008305
8306 bool operator()(const OverloadCandidate *L,
8307 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008308 // Fast-path this check.
8309 if (L == R) return false;
8310
John McCall81201622010-01-08 04:41:39 +00008311 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008312 if (L->Viable) {
8313 if (!R->Viable) return true;
8314
8315 // TODO: introduce a tri-valued comparison for overload
8316 // candidates. Would be more worthwhile if we had a sort
8317 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008318 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8319 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008320 } else if (R->Viable)
8321 return false;
John McCall81201622010-01-08 04:41:39 +00008322
John McCall1b77e732010-01-15 23:32:50 +00008323 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008324
John McCall1b77e732010-01-15 23:32:50 +00008325 // Criteria by which we can sort non-viable candidates:
8326 if (!L->Viable) {
8327 // 1. Arity mismatches come after other candidates.
8328 if (L->FailureKind == ovl_fail_too_many_arguments ||
8329 L->FailureKind == ovl_fail_too_few_arguments)
8330 return false;
8331 if (R->FailureKind == ovl_fail_too_many_arguments ||
8332 R->FailureKind == ovl_fail_too_few_arguments)
8333 return true;
John McCall81201622010-01-08 04:41:39 +00008334
John McCall717e8912010-01-23 05:17:32 +00008335 // 2. Bad conversions come first and are ordered by the number
8336 // of bad conversions and quality of good conversions.
8337 if (L->FailureKind == ovl_fail_bad_conversion) {
8338 if (R->FailureKind != ovl_fail_bad_conversion)
8339 return true;
8340
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008341 // The conversion that can be fixed with a smaller number of changes,
8342 // comes first.
8343 unsigned numLFixes = L->Fix.NumConversionsFixed;
8344 unsigned numRFixes = R->Fix.NumConversionsFixed;
8345 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8346 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008347 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008348 if (numLFixes < numRFixes)
8349 return true;
8350 else
8351 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008352 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008353
John McCall717e8912010-01-23 05:17:32 +00008354 // If there's any ordering between the defined conversions...
8355 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008356 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008357
8358 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008359 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008360 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008361 switch (CompareImplicitConversionSequences(S,
8362 L->Conversions[I],
8363 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008364 case ImplicitConversionSequence::Better:
8365 leftBetter++;
8366 break;
8367
8368 case ImplicitConversionSequence::Worse:
8369 leftBetter--;
8370 break;
8371
8372 case ImplicitConversionSequence::Indistinguishable:
8373 break;
8374 }
8375 }
8376 if (leftBetter > 0) return true;
8377 if (leftBetter < 0) return false;
8378
8379 } else if (R->FailureKind == ovl_fail_bad_conversion)
8380 return false;
8381
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008382 if (L->FailureKind == ovl_fail_bad_deduction) {
8383 if (R->FailureKind != ovl_fail_bad_deduction)
8384 return true;
8385
8386 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8387 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008388 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008389 } else if (R->FailureKind == ovl_fail_bad_deduction)
8390 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008391
John McCall1b77e732010-01-15 23:32:50 +00008392 // TODO: others?
8393 }
8394
8395 // Sort everything else by location.
8396 SourceLocation LLoc = GetLocationForCandidate(L);
8397 SourceLocation RLoc = GetLocationForCandidate(R);
8398
8399 // Put candidates without locations (e.g. builtins) at the end.
8400 if (LLoc.isInvalid()) return false;
8401 if (RLoc.isInvalid()) return true;
8402
8403 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008404 }
8405};
8406
John McCall717e8912010-01-23 05:17:32 +00008407/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008408/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008409void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8410 Expr **Args, unsigned NumArgs) {
8411 assert(!Cand->Viable);
8412
8413 // Don't do anything on failures other than bad conversion.
8414 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8415
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008416 // We only want the FixIts if all the arguments can be corrected.
8417 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008418 // Use a implicit copy initialization to check conversion fixes.
8419 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008420
John McCall717e8912010-01-23 05:17:32 +00008421 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008422 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008423 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008424 while (true) {
8425 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8426 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008427 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008428 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008429 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008430 }
John McCall717e8912010-01-23 05:17:32 +00008431 }
8432
8433 if (ConvIdx == ConvCount)
8434 return;
8435
John McCallb1bdc622010-02-25 01:37:24 +00008436 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8437 "remaining conversion is initialized?");
8438
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008439 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008440 // operation somehow.
8441 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008442
8443 const FunctionProtoType* Proto;
8444 unsigned ArgIdx = ConvIdx;
8445
8446 if (Cand->IsSurrogate) {
8447 QualType ConvType
8448 = Cand->Surrogate->getConversionType().getNonReferenceType();
8449 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8450 ConvType = ConvPtrType->getPointeeType();
8451 Proto = ConvType->getAs<FunctionProtoType>();
8452 ArgIdx--;
8453 } else if (Cand->Function) {
8454 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8455 if (isa<CXXMethodDecl>(Cand->Function) &&
8456 !isa<CXXConstructorDecl>(Cand->Function))
8457 ArgIdx--;
8458 } else {
8459 // Builtin binary operator with a bad first conversion.
8460 assert(ConvCount <= 3);
8461 for (; ConvIdx != ConvCount; ++ConvIdx)
8462 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008463 = TryCopyInitialization(S, Args[ConvIdx],
8464 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008465 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008466 /*InOverloadResolution*/ true,
8467 /*AllowObjCWritebackConversion=*/
8468 S.getLangOptions().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008469 return;
8470 }
8471
8472 // Fill in the rest of the conversions.
8473 unsigned NumArgsInProto = Proto->getNumArgs();
8474 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008475 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008476 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008477 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008478 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008479 /*InOverloadResolution=*/true,
8480 /*AllowObjCWritebackConversion=*/
8481 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008482 // Store the FixIt in the candidate if it exists.
8483 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008484 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008485 }
John McCall717e8912010-01-23 05:17:32 +00008486 else
8487 Cand->Conversions[ConvIdx].setEllipsis();
8488 }
8489}
8490
John McCalla1d7d622010-01-08 00:58:21 +00008491} // end anonymous namespace
8492
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008493/// PrintOverloadCandidates - When overload resolution fails, prints
8494/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008495/// set.
John McCall120d63c2010-08-24 20:38:10 +00008496void OverloadCandidateSet::NoteCandidates(Sema &S,
8497 OverloadCandidateDisplayKind OCD,
8498 Expr **Args, unsigned NumArgs,
8499 const char *Opc,
8500 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008501 // Sort the candidates by viability and position. Sorting directly would
8502 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008503 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008504 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8505 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008506 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008507 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008508 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00008509 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008510 if (Cand->Function || Cand->IsSurrogate)
8511 Cands.push_back(Cand);
8512 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8513 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008514 }
8515 }
8516
John McCallbf65c0b2010-01-12 00:48:53 +00008517 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008518 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008519
John McCall1d318332010-01-12 00:44:57 +00008520 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008521
Chris Lattner5f9e2722011-07-23 10:55:15 +00008522 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikied6471f72011-09-25 23:23:43 +00008523 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8524 S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008525 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008526 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8527 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008528
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008529 // Set an arbitrary limit on the number of candidate functions we'll spam
8530 // the user with. FIXME: This limit should depend on details of the
8531 // candidate list.
David Blaikied6471f72011-09-25 23:23:43 +00008532 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008533 break;
8534 }
8535 ++CandsShown;
8536
John McCalla1d7d622010-01-08 00:58:21 +00008537 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00008538 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00008539 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008540 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008541 else {
8542 assert(Cand->Viable &&
8543 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008544 // Generally we only see ambiguities including viable builtin
8545 // operators if overload resolution got screwed up by an
8546 // ambiguous user-defined conversion.
8547 //
8548 // FIXME: It's quite possible for different conversions to see
8549 // different ambiguities, though.
8550 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008551 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008552 ReportedAmbiguousConversions = true;
8553 }
John McCalla1d7d622010-01-08 00:58:21 +00008554
John McCall1d318332010-01-12 00:44:57 +00008555 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008556 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008557 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008558 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008559
8560 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008561 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008562}
8563
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008564// [PossiblyAFunctionType] --> [Return]
8565// NonFunctionType --> NonFunctionType
8566// R (A) --> R(A)
8567// R (*)(A) --> R (A)
8568// R (&)(A) --> R (A)
8569// R (S::*)(A) --> R (A)
8570QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8571 QualType Ret = PossiblyAFunctionType;
8572 if (const PointerType *ToTypePtr =
8573 PossiblyAFunctionType->getAs<PointerType>())
8574 Ret = ToTypePtr->getPointeeType();
8575 else if (const ReferenceType *ToTypeRef =
8576 PossiblyAFunctionType->getAs<ReferenceType>())
8577 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008578 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008579 PossiblyAFunctionType->getAs<MemberPointerType>())
8580 Ret = MemTypePtr->getPointeeType();
8581 Ret =
8582 Context.getCanonicalType(Ret).getUnqualifiedType();
8583 return Ret;
8584}
Douglas Gregor904eed32008-11-10 20:40:00 +00008585
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008586// A helper class to help with address of function resolution
8587// - allows us to avoid passing around all those ugly parameters
8588class AddressOfFunctionResolver
8589{
8590 Sema& S;
8591 Expr* SourceExpr;
8592 const QualType& TargetType;
8593 QualType TargetFunctionType; // Extracted function type from target type
8594
8595 bool Complain;
8596 //DeclAccessPair& ResultFunctionAccessPair;
8597 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008598
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008599 bool TargetTypeIsNonStaticMemberFunction;
8600 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008601
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008602 OverloadExpr::FindResult OvlExprInfo;
8603 OverloadExpr *OvlExpr;
8604 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008605 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008606
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008607public:
8608 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8609 const QualType& TargetType, bool Complain)
8610 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8611 Complain(Complain), Context(S.getASTContext()),
8612 TargetTypeIsNonStaticMemberFunction(
8613 !!TargetType->getAs<MemberPointerType>()),
8614 FoundNonTemplateFunction(false),
8615 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8616 OvlExpr(OvlExprInfo.Expression)
8617 {
8618 ExtractUnqualifiedFunctionTypeFromTargetType();
8619
8620 if (!TargetFunctionType->isFunctionType()) {
8621 if (OvlExpr->hasExplicitTemplateArgs()) {
8622 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00008623 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008624 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00008625
8626 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8627 if (!Method->isStatic()) {
8628 // If the target type is a non-function type and the function
8629 // found is a non-static member function, pretend as if that was
8630 // the target, it's the only possible type to end up with.
8631 TargetTypeIsNonStaticMemberFunction = true;
8632
8633 // And skip adding the function if its not in the proper form.
8634 // We'll diagnose this due to an empty set of functions.
8635 if (!OvlExprInfo.HasFormOfMemberPointer)
8636 return;
8637 }
8638 }
8639
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008640 Matches.push_back(std::make_pair(dap,Fn));
8641 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00008642 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008643 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00008644 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008645
8646 if (OvlExpr->hasExplicitTemplateArgs())
8647 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00008648
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008649 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8650 // C++ [over.over]p4:
8651 // If more than one function is selected, [...]
8652 if (Matches.size() > 1) {
8653 if (FoundNonTemplateFunction)
8654 EliminateAllTemplateMatches();
8655 else
8656 EliminateAllExceptMostSpecializedTemplate();
8657 }
8658 }
8659 }
8660
8661private:
8662 bool isTargetTypeAFunction() const {
8663 return TargetFunctionType->isFunctionType();
8664 }
8665
8666 // [ToType] [Return]
8667
8668 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8669 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8670 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8671 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8672 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8673 }
8674
8675 // return true if any matching specializations were found
8676 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8677 const DeclAccessPair& CurAccessFunPair) {
8678 if (CXXMethodDecl *Method
8679 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8680 // Skip non-static function templates when converting to pointer, and
8681 // static when converting to member pointer.
8682 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8683 return false;
8684 }
8685 else if (TargetTypeIsNonStaticMemberFunction)
8686 return false;
8687
8688 // C++ [over.over]p2:
8689 // If the name is a function template, template argument deduction is
8690 // done (14.8.2.2), and if the argument deduction succeeds, the
8691 // resulting template argument list is used to generate a single
8692 // function template specialization, which is added to the set of
8693 // overloaded functions considered.
8694 FunctionDecl *Specialization = 0;
8695 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8696 if (Sema::TemplateDeductionResult Result
8697 = S.DeduceTemplateArguments(FunctionTemplate,
8698 &OvlExplicitTemplateArgs,
8699 TargetFunctionType, Specialization,
8700 Info)) {
8701 // FIXME: make a note of the failed deduction for diagnostics.
8702 (void)Result;
8703 return false;
8704 }
8705
8706 // Template argument deduction ensures that we have an exact match.
8707 // This function template specicalization works.
8708 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8709 assert(TargetFunctionType
8710 == Context.getCanonicalType(Specialization->getType()));
8711 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8712 return true;
8713 }
8714
8715 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8716 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00008717 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00008718 // Skip non-static functions when converting to pointer, and static
8719 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008720 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8721 return false;
8722 }
8723 else if (TargetTypeIsNonStaticMemberFunction)
8724 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00008725
Chandler Carruthbd647292009-12-29 06:17:27 +00008726 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008727 if (S.getLangOptions().CUDA)
8728 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8729 if (S.CheckCUDATarget(Caller, FunDecl))
8730 return false;
8731
Douglas Gregor43c79c22009-12-09 00:47:37 +00008732 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008733 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8734 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00008735 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8736 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008737 Matches.push_back(std::make_pair(CurAccessFunPair,
8738 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00008739 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008740 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00008741 }
Mike Stump1eb44332009-09-09 15:08:12 +00008742 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008743
8744 return false;
8745 }
8746
8747 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8748 bool Ret = false;
8749
8750 // If the overload expression doesn't have the form of a pointer to
8751 // member, don't try to convert it to a pointer-to-member type.
8752 if (IsInvalidFormOfPointerToMemberFunction())
8753 return false;
8754
8755 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8756 E = OvlExpr->decls_end();
8757 I != E; ++I) {
8758 // Look through any using declarations to find the underlying function.
8759 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8760
8761 // C++ [over.over]p3:
8762 // Non-member functions and static member functions match
8763 // targets of type "pointer-to-function" or "reference-to-function."
8764 // Nonstatic member functions match targets of
8765 // type "pointer-to-member-function."
8766 // Note that according to DR 247, the containing class does not matter.
8767 if (FunctionTemplateDecl *FunctionTemplate
8768 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8769 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8770 Ret = true;
8771 }
8772 // If we have explicit template arguments supplied, skip non-templates.
8773 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8774 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8775 Ret = true;
8776 }
8777 assert(Ret || Matches.empty());
8778 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00008779 }
8780
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008781 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00008782 // [...] and any given function template specialization F1 is
8783 // eliminated if the set contains a second function template
8784 // specialization whose function template is more specialized
8785 // than the function template of F1 according to the partial
8786 // ordering rules of 14.5.5.2.
8787
8788 // The algorithm specified above is quadratic. We instead use a
8789 // two-pass algorithm (similar to the one used to identify the
8790 // best viable function in an overload set) that identifies the
8791 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00008792
8793 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8794 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8795 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008796
John McCallc373d482010-01-27 01:50:18 +00008797 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008798 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8799 TPOC_Other, 0, SourceExpr->getLocStart(),
8800 S.PDiag(),
8801 S.PDiag(diag::err_addr_ovl_ambiguous)
8802 << Matches[0].second->getDeclName(),
8803 S.PDiag(diag::note_ovl_candidate)
8804 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00008805 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008806
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008807 if (Result != MatchesCopy.end()) {
8808 // Make it the first and only element
8809 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8810 Matches[0].second = cast<FunctionDecl>(*Result);
8811 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00008812 }
8813 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008814
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008815 void EliminateAllTemplateMatches() {
8816 // [...] any function template specializations in the set are
8817 // eliminated if the set also contains a non-template function, [...]
8818 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8819 if (Matches[I].second->getPrimaryTemplate() == 0)
8820 ++I;
8821 else {
8822 Matches[I] = Matches[--N];
8823 Matches.set_size(N);
8824 }
8825 }
8826 }
8827
8828public:
8829 void ComplainNoMatchesFound() const {
8830 assert(Matches.empty());
8831 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8832 << OvlExpr->getName() << TargetFunctionType
8833 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00008834 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008835 }
8836
8837 bool IsInvalidFormOfPointerToMemberFunction() const {
8838 return TargetTypeIsNonStaticMemberFunction &&
8839 !OvlExprInfo.HasFormOfMemberPointer;
8840 }
8841
8842 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8843 // TODO: Should we condition this on whether any functions might
8844 // have matched, or is it more appropriate to do that in callers?
8845 // TODO: a fixit wouldn't hurt.
8846 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8847 << TargetType << OvlExpr->getSourceRange();
8848 }
8849
8850 void ComplainOfInvalidConversion() const {
8851 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8852 << OvlExpr->getName() << TargetType;
8853 }
8854
8855 void ComplainMultipleMatchesFound() const {
8856 assert(Matches.size() > 1);
8857 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8858 << OvlExpr->getName()
8859 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00008860 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008861 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008862
8863 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8864
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008865 int getNumMatches() const { return Matches.size(); }
8866
8867 FunctionDecl* getMatchingFunctionDecl() const {
8868 if (Matches.size() != 1) return 0;
8869 return Matches[0].second;
8870 }
8871
8872 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8873 if (Matches.size() != 1) return 0;
8874 return &Matches[0].first;
8875 }
8876};
8877
8878/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8879/// an overloaded function (C++ [over.over]), where @p From is an
8880/// expression with overloaded function type and @p ToType is the type
8881/// we're trying to resolve to. For example:
8882///
8883/// @code
8884/// int f(double);
8885/// int f(int);
8886///
8887/// int (*pfd)(double) = f; // selects f(double)
8888/// @endcode
8889///
8890/// This routine returns the resulting FunctionDecl if it could be
8891/// resolved, and NULL otherwise. When @p Complain is true, this
8892/// routine will emit diagnostics if there is an error.
8893FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008894Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8895 QualType TargetType,
8896 bool Complain,
8897 DeclAccessPair &FoundResult,
8898 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008899 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008900
8901 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8902 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008903 int NumMatches = Resolver.getNumMatches();
8904 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008905 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008906 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8907 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8908 else
8909 Resolver.ComplainNoMatchesFound();
8910 }
8911 else if (NumMatches > 1 && Complain)
8912 Resolver.ComplainMultipleMatchesFound();
8913 else if (NumMatches == 1) {
8914 Fn = Resolver.getMatchingFunctionDecl();
8915 assert(Fn);
8916 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedman5f2987c2012-02-02 03:46:19 +00008917 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00008918 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008919 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00008920 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008921
8922 if (pHadMultipleCandidates)
8923 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008924 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00008925}
8926
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008927/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00008928/// resolve that overloaded function expression down to a single function.
8929///
8930/// This routine can only resolve template-ids that refer to a single function
8931/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008932/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00008933/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00008934FunctionDecl *
8935Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8936 bool Complain,
8937 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00008938 // C++ [over.over]p1:
8939 // [...] [Note: any redundant set of parentheses surrounding the
8940 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00008941 // C++ [over.over]p1:
8942 // [...] The overloaded function name can be preceded by the &
8943 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008944
Douglas Gregor4b52e252009-12-21 23:17:24 +00008945 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00008946 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00008947 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00008948
8949 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00008950 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008951
Douglas Gregor4b52e252009-12-21 23:17:24 +00008952 // Look through all of the overloaded functions, searching for one
8953 // whose type matches exactly.
8954 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00008955 for (UnresolvedSetIterator I = ovl->decls_begin(),
8956 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00008957 // C++0x [temp.arg.explicit]p3:
8958 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008959 // where deduction is not done, if a template argument list is
8960 // specified and it, along with any default template arguments,
8961 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00008962 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00008963 FunctionTemplateDecl *FunctionTemplate
8964 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008965
Douglas Gregor4b52e252009-12-21 23:17:24 +00008966 // C++ [over.over]p2:
8967 // If the name is a function template, template argument deduction is
8968 // done (14.8.2.2), and if the argument deduction succeeds, the
8969 // resulting template argument list is used to generate a single
8970 // function template specialization, which is added to the set of
8971 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00008972 FunctionDecl *Specialization = 0;
John McCall864c0412011-04-26 20:42:42 +00008973 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00008974 if (TemplateDeductionResult Result
8975 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8976 Specialization, Info)) {
8977 // FIXME: make a note of the failed deduction for diagnostics.
8978 (void)Result;
8979 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008980 }
8981
John McCall864c0412011-04-26 20:42:42 +00008982 assert(Specialization && "no specialization and no error?");
8983
Douglas Gregor4b52e252009-12-21 23:17:24 +00008984 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008985 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008986 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00008987 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8988 << ovl->getName();
8989 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008990 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00008991 return 0;
John McCall864c0412011-04-26 20:42:42 +00008992 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008993
John McCall864c0412011-04-26 20:42:42 +00008994 Matched = Specialization;
8995 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00008996 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008997
Douglas Gregor4b52e252009-12-21 23:17:24 +00008998 return Matched;
8999}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009000
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009001
9002
9003
John McCall6dbba4f2011-10-11 23:14:30 +00009004// Resolve and fix an overloaded expression that can be resolved
9005// because it identifies a single function template specialization.
9006//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009007// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009008//
9009// Return true if it was logically possible to so resolve the
9010// expression, regardless of whether or not it succeeded. Always
9011// returns true if 'complain' is set.
9012bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9013 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9014 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009015 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009016 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009017 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009018
John McCall6dbba4f2011-10-11 23:14:30 +00009019 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009020
John McCall864c0412011-04-26 20:42:42 +00009021 DeclAccessPair found;
9022 ExprResult SingleFunctionExpression;
9023 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9024 ovl.Expression, /*complain*/ false, &found)) {
John McCall6dbba4f2011-10-11 23:14:30 +00009025 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
9026 SrcExpr = ExprError();
9027 return true;
9028 }
John McCall864c0412011-04-26 20:42:42 +00009029
9030 // It is only correct to resolve to an instance method if we're
9031 // resolving a form that's permitted to be a pointer to member.
9032 // Otherwise we'll end up making a bound member expression, which
9033 // is illegal in all the contexts we resolve like this.
9034 if (!ovl.HasFormOfMemberPointer &&
9035 isa<CXXMethodDecl>(fn) &&
9036 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009037 if (!complain) return false;
9038
9039 Diag(ovl.Expression->getExprLoc(),
9040 diag::err_bound_member_function)
9041 << 0 << ovl.Expression->getSourceRange();
9042
9043 // TODO: I believe we only end up here if there's a mix of
9044 // static and non-static candidates (otherwise the expression
9045 // would have 'bound member' type, not 'overload' type).
9046 // Ideally we would note which candidate was chosen and why
9047 // the static candidates were rejected.
9048 SrcExpr = ExprError();
9049 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009050 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009051
John McCall864c0412011-04-26 20:42:42 +00009052 // Fix the expresion to refer to 'fn'.
9053 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009054 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009055
9056 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009057 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009058 SingleFunctionExpression =
9059 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009060 if (SingleFunctionExpression.isInvalid()) {
9061 SrcExpr = ExprError();
9062 return true;
9063 }
9064 }
John McCall864c0412011-04-26 20:42:42 +00009065 }
9066
9067 if (!SingleFunctionExpression.isUsable()) {
9068 if (complain) {
9069 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9070 << ovl.Expression->getName()
9071 << DestTypeForComplaining
9072 << OpRangeForComplaining
9073 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009074 NoteAllOverloadCandidates(SrcExpr.get());
9075
9076 SrcExpr = ExprError();
9077 return true;
9078 }
9079
9080 return false;
John McCall864c0412011-04-26 20:42:42 +00009081 }
9082
John McCall6dbba4f2011-10-11 23:14:30 +00009083 SrcExpr = SingleFunctionExpression;
9084 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009085}
9086
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009087/// \brief Add a single candidate to the overload set.
9088static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009089 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009090 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009091 Expr **Args, unsigned NumArgs,
9092 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009093 bool PartialOverloading,
9094 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009095 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009096 if (isa<UsingShadowDecl>(Callee))
9097 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9098
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009099 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009100 if (ExplicitTemplateArgs) {
9101 assert(!KnownValid && "Explicit template arguments?");
9102 return;
9103 }
John McCall9aa472c2010-03-19 07:35:19 +00009104 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00009105 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009106 return;
John McCallba135432009-11-21 08:51:07 +00009107 }
9108
9109 if (FunctionTemplateDecl *FuncTemplate
9110 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009111 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9112 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00009113 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009114 return;
9115 }
9116
Richard Smith2ced0442011-06-26 22:19:54 +00009117 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009118}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009119
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009120/// \brief Add the overload candidates named by callee and/or found by argument
9121/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009122void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009123 Expr **Args, unsigned NumArgs,
9124 OverloadCandidateSet &CandidateSet,
9125 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009126
9127#ifndef NDEBUG
9128 // Verify that ArgumentDependentLookup is consistent with the rules
9129 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009130 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009131 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9132 // and let Y be the lookup set produced by argument dependent
9133 // lookup (defined as follows). If X contains
9134 //
9135 // -- a declaration of a class member, or
9136 //
9137 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009138 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009139 //
9140 // -- a declaration that is neither a function or a function
9141 // template
9142 //
9143 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009144
John McCall3b4294e2009-12-16 12:17:52 +00009145 if (ULE->requiresADL()) {
9146 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9147 E = ULE->decls_end(); I != E; ++I) {
9148 assert(!(*I)->getDeclContext()->isRecord());
9149 assert(isa<UsingShadowDecl>(*I) ||
9150 !(*I)->getDeclContext()->isFunctionOrMethod());
9151 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009152 }
9153 }
9154#endif
9155
John McCall3b4294e2009-12-16 12:17:52 +00009156 // It would be nice to avoid this copy.
9157 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009158 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009159 if (ULE->hasExplicitTemplateArgs()) {
9160 ULE->copyTemplateArgumentsInto(TABuffer);
9161 ExplicitTemplateArgs = &TABuffer;
9162 }
9163
9164 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9165 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00009166 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009167 Args, NumArgs, CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009168 PartialOverloading, /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009169
John McCall3b4294e2009-12-16 12:17:52 +00009170 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009171 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9172 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009173 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009174 CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00009175 PartialOverloading,
9176 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009177}
John McCall578b69b2009-12-16 08:11:27 +00009178
Richard Smithf50e88a2011-06-05 22:42:48 +00009179/// Attempt to recover from an ill-formed use of a non-dependent name in a
9180/// template, where the non-dependent name was declared after the template
9181/// was defined. This is common in code written for a compilers which do not
9182/// correctly implement two-stage name lookup.
9183///
9184/// Returns true if a viable candidate was found and a diagnostic was issued.
9185static bool
9186DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9187 const CXXScopeSpec &SS, LookupResult &R,
9188 TemplateArgumentListInfo *ExplicitTemplateArgs,
9189 Expr **Args, unsigned NumArgs) {
9190 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9191 return false;
9192
9193 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9194 SemaRef.LookupQualifiedName(R, DC);
9195
9196 if (!R.empty()) {
9197 R.suppressDiagnostics();
9198
9199 if (isa<CXXRecordDecl>(DC)) {
9200 // Don't diagnose names we find in classes; we get much better
9201 // diagnostics for these from DiagnoseEmptyLookup.
9202 R.clear();
9203 return false;
9204 }
9205
9206 OverloadCandidateSet Candidates(FnLoc);
9207 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9208 AddOverloadedCallCandidate(SemaRef, I.getPair(),
9209 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith2ced0442011-06-26 22:19:54 +00009210 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009211
9212 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009213 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009214 // No viable functions. Don't bother the user with notes for functions
9215 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009216 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009217 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009218 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009219
9220 // Find the namespaces where ADL would have looked, and suggest
9221 // declaring the function there instead.
9222 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9223 Sema::AssociatedClassSet AssociatedClasses;
9224 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
9225 AssociatedNamespaces,
9226 AssociatedClasses);
9227 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00009228 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009229 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009230 for (Sema::AssociatedNamespaceSet::iterator
9231 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00009232 end = AssociatedNamespaces.end(); it != end; ++it) {
9233 if (!Std->Encloses(*it))
9234 SuggestedNamespaces.insert(*it);
9235 }
Chandler Carruth45cad4a2011-06-08 10:13:17 +00009236 } else {
9237 // Lacking the 'std::' namespace, use all of the associated namespaces.
9238 SuggestedNamespaces = AssociatedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009239 }
9240
9241 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9242 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009243 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009244 SemaRef.Diag(Best->Function->getLocation(),
9245 diag::note_not_found_by_two_phase_lookup)
9246 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009247 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009248 SemaRef.Diag(Best->Function->getLocation(),
9249 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009250 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009251 } else {
9252 // FIXME: It would be useful to list the associated namespaces here,
9253 // but the diagnostics infrastructure doesn't provide a way to produce
9254 // a localized representation of a list of items.
9255 SemaRef.Diag(Best->Function->getLocation(),
9256 diag::note_not_found_by_two_phase_lookup)
9257 << R.getLookupName() << 2;
9258 }
9259
9260 // Try to recover by calling this function.
9261 return true;
9262 }
9263
9264 R.clear();
9265 }
9266
9267 return false;
9268}
9269
9270/// Attempt to recover from ill-formed use of a non-dependent operator in a
9271/// template, where the non-dependent operator was declared after the template
9272/// was defined.
9273///
9274/// Returns true if a viable candidate was found and a diagnostic was issued.
9275static bool
9276DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9277 SourceLocation OpLoc,
9278 Expr **Args, unsigned NumArgs) {
9279 DeclarationName OpName =
9280 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9281 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9282 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9283 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
9284}
9285
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009286namespace {
9287// Callback to limit the allowed keywords and to only accept typo corrections
9288// that are keywords or whose decls refer to functions (or template functions)
9289// that accept the given number of arguments.
9290class RecoveryCallCCC : public CorrectionCandidateCallback {
9291 public:
9292 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9293 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
9294 WantTypeSpecifiers = SemaRef.getLangOptions().CPlusPlus;
9295 WantRemainingKeywords = false;
9296 }
9297
9298 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9299 if (!candidate.getCorrectionDecl())
9300 return candidate.isKeyword();
9301
9302 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9303 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9304 FunctionDecl *FD = 0;
9305 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9306 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9307 FD = FTD->getTemplatedDecl();
9308 if (!HasExplicitTemplateArgs && !FD) {
9309 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9310 // If the Decl is neither a function nor a template function,
9311 // determine if it is a pointer or reference to a function. If so,
9312 // check against the number of arguments expected for the pointee.
9313 QualType ValType = cast<ValueDecl>(ND)->getType();
9314 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9315 ValType = ValType->getPointeeType();
9316 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9317 if (FPT->getNumArgs() == NumArgs)
9318 return true;
9319 }
9320 }
9321 if (FD && FD->getNumParams() >= NumArgs &&
9322 FD->getMinRequiredArguments() <= NumArgs)
9323 return true;
9324 }
9325 return false;
9326 }
9327
9328 private:
9329 unsigned NumArgs;
9330 bool HasExplicitTemplateArgs;
9331};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009332
9333// Callback that effectively disabled typo correction
9334class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9335 public:
9336 NoTypoCorrectionCCC() {
9337 WantTypeSpecifiers = false;
9338 WantExpressionKeywords = false;
9339 WantCXXNamedCasts = false;
9340 WantRemainingKeywords = false;
9341 }
9342
9343 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9344 return false;
9345 }
9346};
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009347}
9348
John McCall578b69b2009-12-16 08:11:27 +00009349/// Attempts to recover from a call where no functions were found.
9350///
9351/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009352static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009353BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009354 UnresolvedLookupExpr *ULE,
9355 SourceLocation LParenLoc,
9356 Expr **Args, unsigned NumArgs,
Richard Smithf50e88a2011-06-05 22:42:48 +00009357 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009358 bool EmptyLookup, bool AllowTypoCorrection) {
John McCall578b69b2009-12-16 08:11:27 +00009359
9360 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009361 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009362 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009363
John McCall3b4294e2009-12-16 12:17:52 +00009364 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009365 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009366 if (ULE->hasExplicitTemplateArgs()) {
9367 ULE->copyTemplateArgumentsInto(TABuffer);
9368 ExplicitTemplateArgs = &TABuffer;
9369 }
9370
John McCall578b69b2009-12-16 08:11:27 +00009371 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9372 Sema::LookupOrdinaryName);
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009373 RecoveryCallCCC Validator(SemaRef, NumArgs, ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009374 NoTypoCorrectionCCC RejectAll;
9375 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9376 (CorrectionCandidateCallback*)&Validator :
9377 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009378 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
9379 ExplicitTemplateArgs, Args, NumArgs) &&
9380 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009381 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00009382 ExplicitTemplateArgs, Args, NumArgs)))
John McCallf312b1e2010-08-26 23:41:50 +00009383 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009384
John McCall3b4294e2009-12-16 12:17:52 +00009385 assert(!R.empty() && "lookup results empty despite recovery");
9386
9387 // Build an implicit member call if appropriate. Just drop the
9388 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009389 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009390 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009391 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9392 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009393 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009394 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009395 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009396 else
9397 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9398
9399 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009400 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009401
9402 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009403 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009404 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009405 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00009406 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009407}
Douglas Gregord7a95972010-06-08 17:35:15 +00009408
Douglas Gregorf6b89692008-11-26 05:54:23 +00009409/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00009410/// (which eventually refers to the declaration Func) and the call
9411/// arguments Args/NumArgs, attempt to resolve the function call down
9412/// to a specific function. If overload resolution succeeds, returns
9413/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00009414/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00009415/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00009416ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009417Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00009418 SourceLocation LParenLoc,
9419 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00009420 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009421 Expr *ExecConfig,
9422 bool AllowTypoCorrection) {
John McCall3b4294e2009-12-16 12:17:52 +00009423#ifndef NDEBUG
9424 if (ULE->requiresADL()) {
9425 // To do ADL, we must have found an unqualified name.
9426 assert(!ULE->getQualifier() && "qualified name with ADL");
9427
9428 // We don't perform ADL for implicit declarations of builtins.
9429 // Verify that this was correctly set up.
9430 FunctionDecl *F;
9431 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9432 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9433 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009434 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009435
John McCall3b4294e2009-12-16 12:17:52 +00009436 // We don't perform ADL in C.
9437 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00009438 } else
9439 assert(!ULE->isStdAssociatedNamespace() &&
9440 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00009441#endif
9442
John McCall5acb0c92011-10-17 18:40:02 +00009443 UnbridgedCastsSet UnbridgedCasts;
9444 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9445 return ExprError();
9446
John McCall5769d612010-02-08 23:07:23 +00009447 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00009448
John McCall3b4294e2009-12-16 12:17:52 +00009449 // Add the functions denoted by the callee to the set of candidate
9450 // functions, including those from argument-dependent lookup.
9451 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009452
9453 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009454 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9455 // out if it fails.
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009456 if (CandidateSet.empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009457 // In Microsoft mode, if we are inside a template class member function then
9458 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009459 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009460 // classes.
Francois Pichetef04ecf2011-11-11 00:12:11 +00009461 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009462 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009463 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9464 Context.DependentTy, VK_RValue,
9465 RParenLoc);
9466 CE->setTypeDependent(true);
9467 return Owned(CE);
9468 }
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009469 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009470 RParenLoc, /*EmptyLookup=*/true,
9471 AllowTypoCorrection);
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009472 }
John McCall578b69b2009-12-16 08:11:27 +00009473
John McCall5acb0c92011-10-17 18:40:02 +00009474 UnbridgedCasts.restore();
9475
Douglas Gregorf6b89692008-11-26 05:54:23 +00009476 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009477 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00009478 case OR_Success: {
9479 FunctionDecl *FDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00009480 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCall9aa472c2010-03-19 07:35:19 +00009481 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall5acb0c92011-10-17 18:40:02 +00009482 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00009483 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00009484 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9485 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009486 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009487
Richard Smithf50e88a2011-06-05 22:42:48 +00009488 case OR_No_Viable_Function: {
9489 // Try to recover by looking for viable functions which the user might
9490 // have meant to call.
9491 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9492 Args, NumArgs, RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009493 /*EmptyLookup=*/false,
9494 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009495 if (!Recovery.isInvalid())
9496 return Recovery;
9497
Chris Lattner4330d652009-02-17 07:29:20 +00009498 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009499 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009500 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009501 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00009502 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009503 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009504
9505 case OR_Ambiguous:
9506 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009507 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009508 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00009509 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009510
9511 case OR_Deleted:
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009512 {
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009513 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
9514 << Best->Function->isDeleted()
9515 << ULE->getName()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009516 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009517 << Fn->getSourceRange();
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009518 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009519
9520 // We emitted an error for the unvailable/deleted function call but keep
9521 // the call in the AST.
9522 FunctionDecl *FDecl = Best->Function;
9523 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9524 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9525 RParenLoc, ExecConfig);
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009526 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009527 }
9528
Douglas Gregorff331c12010-07-25 18:17:45 +00009529 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009530 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009531}
9532
John McCall6e266892010-01-26 03:27:55 +00009533static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009534 return Functions.size() > 1 ||
9535 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9536}
9537
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009538/// \brief Create a unary operation that may resolve to an overloaded
9539/// operator.
9540///
9541/// \param OpLoc The location of the operator itself (e.g., '*').
9542///
9543/// \param OpcIn The UnaryOperator::Opcode that describes this
9544/// operator.
9545///
9546/// \param Functions The set of non-member functions that will be
9547/// considered by overload resolution. The caller needs to build this
9548/// set based on the context using, e.g.,
9549/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9550/// set should not contain any member functions; those will be added
9551/// by CreateOverloadedUnaryOp().
9552///
9553/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009554ExprResult
John McCall6e266892010-01-26 03:27:55 +00009555Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9556 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00009557 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009558 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009559
9560 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9561 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9562 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00009563 // TODO: provide better source location info.
9564 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009565
John McCall5acb0c92011-10-17 18:40:02 +00009566 if (checkPlaceholderForOverload(*this, Input))
9567 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009568
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009569 Expr *Args[2] = { Input, 0 };
9570 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00009571
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009572 // For post-increment and post-decrement, add the implicit '0' as
9573 // the second argument, so that we know this is a post-increment or
9574 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00009575 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009576 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009577 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9578 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009579 NumArgs = 2;
9580 }
9581
9582 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009583 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00009584 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009585 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009586 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009587 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009588 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009589
John McCallc373d482010-01-27 01:50:18 +00009590 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00009591 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009592 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009593 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009594 /*ADL*/ true, IsOverloaded(Fns),
9595 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009596 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009597 &Args[0], NumArgs,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009598 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009599 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009600 OpLoc));
9601 }
9602
9603 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009604 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009605
9606 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00009607 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009608
9609 // Add operator candidates that are member functions.
9610 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9611
John McCall6e266892010-01-26 03:27:55 +00009612 // Add candidates from ADL.
9613 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00009614 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00009615 /*ExplicitTemplateArgs*/ 0,
9616 CandidateSet);
9617
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009618 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009619 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009620
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009621 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9622
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009623 // Perform overload resolution.
9624 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009625 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009626 case OR_Success: {
9627 // We found a built-in operator or an overloaded operator.
9628 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00009629
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009630 if (FnDecl) {
9631 // We matched an overloaded operator. Build a call to that
9632 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00009633
Eli Friedman5f2987c2012-02-02 03:46:19 +00009634 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009635
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009636 // Convert the arguments.
9637 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00009638 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009639
John Wiegley429bb272011-04-08 18:41:53 +00009640 ExprResult InputRes =
9641 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9642 Best->FoundDecl, Method);
9643 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009644 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009645 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009646 } else {
9647 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00009648 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00009649 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009650 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00009651 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009652 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00009653 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00009654 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009655 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00009656 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009657 }
9658
John McCallb697e082010-05-06 18:15:07 +00009659 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9660
John McCallf89e55a2010-11-18 06:31:45 +00009661 // Determine the result type.
9662 QualType ResultTy = FnDecl->getResultType();
9663 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9664 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00009665
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009666 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009667 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +00009668 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009669 if (FnExpr.isInvalid())
9670 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00009671
Eli Friedman4c3b8962009-11-18 03:58:17 +00009672 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00009673 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009674 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009675 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00009676
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009677 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00009678 FnDecl))
9679 return ExprError();
9680
John McCall9ae2f072010-08-23 23:25:46 +00009681 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009682 } else {
9683 // We matched a built-in operator. Convert the arguments, then
9684 // break out so that we will build the appropriate built-in
9685 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009686 ExprResult InputRes =
9687 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9688 Best->Conversions[0], AA_Passing);
9689 if (InputRes.isInvalid())
9690 return ExprError();
9691 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009692 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009693 }
John Wiegley429bb272011-04-08 18:41:53 +00009694 }
9695
9696 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +00009697 // This is an erroneous use of an operator which can be overloaded by
9698 // a non-member function. Check for non-member operators which were
9699 // defined too late to be candidates.
9700 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
9701 // FIXME: Recover by calling the found function.
9702 return ExprError();
9703
John Wiegley429bb272011-04-08 18:41:53 +00009704 // No viable function; fall through to handling this as a
9705 // built-in operator, which will produce an error message for us.
9706 break;
9707
9708 case OR_Ambiguous:
9709 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9710 << UnaryOperator::getOpcodeStr(Opc)
9711 << Input->getType()
9712 << Input->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00009713 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley429bb272011-04-08 18:41:53 +00009714 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9715 return ExprError();
9716
9717 case OR_Deleted:
9718 Diag(OpLoc, diag::err_ovl_deleted_oper)
9719 << Best->Function->isDeleted()
9720 << UnaryOperator::getOpcodeStr(Opc)
9721 << getDeletedOrUnavailableSuffix(Best->Function)
9722 << Input->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00009723 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
9724 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009725 return ExprError();
9726 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009727
9728 // Either we found no viable overloaded operator or we matched a
9729 // built-in operator. In either case, fall through to trying to
9730 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00009731 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009732}
9733
Douglas Gregor063daf62009-03-13 18:40:31 +00009734/// \brief Create a binary operation that may resolve to an overloaded
9735/// operator.
9736///
9737/// \param OpLoc The location of the operator itself (e.g., '+').
9738///
9739/// \param OpcIn The BinaryOperator::Opcode that describes this
9740/// operator.
9741///
9742/// \param Functions The set of non-member functions that will be
9743/// considered by overload resolution. The caller needs to build this
9744/// set based on the context using, e.g.,
9745/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9746/// set should not contain any member functions; those will be added
9747/// by CreateOverloadedBinOp().
9748///
9749/// \param LHS Left-hand argument.
9750/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009751ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00009752Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00009753 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00009754 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00009755 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00009756 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009757 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00009758
9759 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9760 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9761 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9762
9763 // If either side is type-dependent, create an appropriate dependent
9764 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009765 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00009766 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009767 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009768 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00009769 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009770 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +00009771 Context.DependentTy,
9772 VK_RValue, OK_Ordinary,
9773 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009774
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009775 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9776 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009777 VK_LValue,
9778 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009779 Context.DependentTy,
9780 Context.DependentTy,
9781 OpLoc));
9782 }
John McCall6e266892010-01-26 03:27:55 +00009783
9784 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00009785 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00009786 // TODO: provide better source location info in DNLoc component.
9787 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00009788 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +00009789 = UnresolvedLookupExpr::Create(Context, NamingClass,
9790 NestedNameSpecifierLoc(), OpNameInfo,
9791 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009792 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00009793 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00009794 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00009795 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009796 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +00009797 OpLoc));
9798 }
9799
John McCall5acb0c92011-10-17 18:40:02 +00009800 // Always do placeholder-like conversions on the RHS.
9801 if (checkPlaceholderForOverload(*this, Args[1]))
9802 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009803
John McCall3c3b7f92011-10-25 17:37:35 +00009804 // Do placeholder-like conversion on the LHS; note that we should
9805 // not get here with a PseudoObject LHS.
9806 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +00009807 if (checkPlaceholderForOverload(*this, Args[0]))
9808 return ExprError();
9809
Sebastian Redl275c2b42009-11-18 23:10:33 +00009810 // If this is the assignment operator, we only perform overload resolution
9811 // if the left-hand side is a class or enumeration type. This is actually
9812 // a hack. The standard requires that we do overload resolution between the
9813 // various built-in candidates, but as DR507 points out, this can lead to
9814 // problems. So we do it this way, which pretty much follows what GCC does.
9815 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00009816 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009817 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00009818
John McCall0e800c92010-12-04 08:14:53 +00009819 // If this is the .* operator, which is not overloadable, just
9820 // create a built-in binary operator.
9821 if (Opc == BO_PtrMemD)
9822 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9823
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009824 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009825 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009826
9827 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00009828 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00009829
9830 // Add operator candidates that are member functions.
9831 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9832
John McCall6e266892010-01-26 03:27:55 +00009833 // Add candidates from ADL.
9834 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9835 Args, 2,
9836 /*ExplicitTemplateArgs*/ 0,
9837 CandidateSet);
9838
Douglas Gregor063daf62009-03-13 18:40:31 +00009839 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009840 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00009841
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009842 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9843
Douglas Gregor063daf62009-03-13 18:40:31 +00009844 // Perform overload resolution.
9845 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009846 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00009847 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00009848 // We found a built-in operator or an overloaded operator.
9849 FunctionDecl *FnDecl = Best->Function;
9850
9851 if (FnDecl) {
9852 // We matched an overloaded operator. Build a call to that
9853 // operator.
9854
Eli Friedman5f2987c2012-02-02 03:46:19 +00009855 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009856
Douglas Gregor063daf62009-03-13 18:40:31 +00009857 // Convert the arguments.
9858 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00009859 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00009860 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009861
Chandler Carruth6df868e2010-12-12 08:17:55 +00009862 ExprResult Arg1 =
9863 PerformCopyInitialization(
9864 InitializedEntity::InitializeParameter(Context,
9865 FnDecl->getParamDecl(0)),
9866 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009867 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009868 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009869
John Wiegley429bb272011-04-08 18:41:53 +00009870 ExprResult Arg0 =
9871 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9872 Best->FoundDecl, Method);
9873 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009874 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009875 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009876 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00009877 } else {
9878 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +00009879 ExprResult Arg0 = PerformCopyInitialization(
9880 InitializedEntity::InitializeParameter(Context,
9881 FnDecl->getParamDecl(0)),
9882 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009883 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009884 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009885
Chandler Carruth6df868e2010-12-12 08:17:55 +00009886 ExprResult Arg1 =
9887 PerformCopyInitialization(
9888 InitializedEntity::InitializeParameter(Context,
9889 FnDecl->getParamDecl(1)),
9890 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009891 if (Arg1.isInvalid())
9892 return ExprError();
9893 Args[0] = LHS = Arg0.takeAs<Expr>();
9894 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00009895 }
9896
John McCallb697e082010-05-06 18:15:07 +00009897 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9898
John McCallf89e55a2010-11-18 06:31:45 +00009899 // Determine the result type.
9900 QualType ResultTy = FnDecl->getResultType();
9901 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9902 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00009903
9904 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009905 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9906 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009907 if (FnExpr.isInvalid())
9908 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +00009909
John McCall9ae2f072010-08-23 23:25:46 +00009910 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009911 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009912 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009913
9914 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00009915 FnDecl))
9916 return ExprError();
9917
John McCall9ae2f072010-08-23 23:25:46 +00009918 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00009919 } else {
9920 // We matched a built-in operator. Convert the arguments, then
9921 // break out so that we will build the appropriate built-in
9922 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009923 ExprResult ArgsRes0 =
9924 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9925 Best->Conversions[0], AA_Passing);
9926 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009927 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009928 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00009929
John Wiegley429bb272011-04-08 18:41:53 +00009930 ExprResult ArgsRes1 =
9931 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9932 Best->Conversions[1], AA_Passing);
9933 if (ArgsRes1.isInvalid())
9934 return ExprError();
9935 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00009936 break;
9937 }
9938 }
9939
Douglas Gregor33074752009-09-30 21:46:01 +00009940 case OR_No_Viable_Function: {
9941 // C++ [over.match.oper]p9:
9942 // If the operator is the operator , [...] and there are no
9943 // viable functions, then the operator is assumed to be the
9944 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00009945 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00009946 break;
9947
Chandler Carruth6df868e2010-12-12 08:17:55 +00009948 // For class as left operand for assignment or compound assigment
9949 // operator do not fall through to handling in built-in, but report that
9950 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00009951 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009952 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00009953 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00009954 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9955 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009956 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00009957 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +00009958 // This is an erroneous use of an operator which can be overloaded by
9959 // a non-member function. Check for non-member operators which were
9960 // defined too late to be candidates.
9961 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9962 // FIXME: Recover by calling the found function.
9963 return ExprError();
9964
Douglas Gregor33074752009-09-30 21:46:01 +00009965 // No viable function; try to create a built-in operation, which will
9966 // produce an error. Then, show the non-viable candidates.
9967 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00009968 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009969 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +00009970 "C++ binary operator overloading is missing candidates!");
9971 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00009972 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9973 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00009974 return move(Result);
9975 }
Douglas Gregor063daf62009-03-13 18:40:31 +00009976
9977 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00009978 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +00009979 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00009980 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009981 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009982 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9983 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009984 return ExprError();
9985
9986 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +00009987 if (isImplicitlyDeleted(Best->Function)) {
9988 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
9989 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
9990 << getSpecialMember(Method)
9991 << BinaryOperator::getOpcodeStr(Opc)
9992 << getDeletedOrUnavailableSuffix(Best->Function);
9993
9994 if (Method->getParent()->isLambda()) {
9995 Diag(Method->getParent()->getLocation(), diag::note_lambda_decl);
9996 return ExprError();
9997 }
9998 } else {
9999 Diag(OpLoc, diag::err_ovl_deleted_oper)
10000 << Best->Function->isDeleted()
10001 << BinaryOperator::getOpcodeStr(Opc)
10002 << getDeletedOrUnavailableSuffix(Best->Function)
10003 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10004 }
Eli Friedman1795d372011-08-26 19:46:22 +000010005 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10006 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010007 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010008 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010009
Douglas Gregor33074752009-09-30 21:46:01 +000010010 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010011 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010012}
10013
John McCall60d7b3a2010-08-24 06:29:42 +000010014ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010015Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10016 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010017 Expr *Base, Expr *Idx) {
10018 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010019 DeclarationName OpName =
10020 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10021
10022 // If either side is type-dependent, create an appropriate dependent
10023 // expression.
10024 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10025
John McCallc373d482010-01-27 01:50:18 +000010026 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010027 // CHECKME: no 'operator' keyword?
10028 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10029 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010030 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010031 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010032 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010033 /*ADL*/ true, /*Overloaded*/ false,
10034 UnresolvedSetIterator(),
10035 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010036 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010037
Sebastian Redlf322ed62009-10-29 20:17:01 +000010038 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10039 Args, 2,
10040 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010041 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010042 RLoc));
10043 }
10044
John McCall5acb0c92011-10-17 18:40:02 +000010045 // Handle placeholders on both operands.
10046 if (checkPlaceholderForOverload(*this, Args[0]))
10047 return ExprError();
10048 if (checkPlaceholderForOverload(*this, Args[1]))
10049 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010050
Sebastian Redlf322ed62009-10-29 20:17:01 +000010051 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010052 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010053
10054 // Subscript can only be overloaded as a member function.
10055
10056 // Add operator candidates that are member functions.
10057 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10058
10059 // Add builtin operator candidates.
10060 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10061
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010062 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10063
Sebastian Redlf322ed62009-10-29 20:17:01 +000010064 // Perform overload resolution.
10065 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010066 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010067 case OR_Success: {
10068 // We found a built-in operator or an overloaded operator.
10069 FunctionDecl *FnDecl = Best->Function;
10070
10071 if (FnDecl) {
10072 // We matched an overloaded operator. Build a call to that
10073 // operator.
10074
Eli Friedman5f2987c2012-02-02 03:46:19 +000010075 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010076
John McCall9aa472c2010-03-19 07:35:19 +000010077 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010078 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +000010079
Sebastian Redlf322ed62009-10-29 20:17:01 +000010080 // Convert the arguments.
10081 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010082 ExprResult Arg0 =
10083 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10084 Best->FoundDecl, Method);
10085 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010086 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010087 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010088
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010089 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010090 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010091 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010092 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010093 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010094 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010095 Owned(Args[1]));
10096 if (InputInit.isInvalid())
10097 return ExprError();
10098
10099 Args[1] = InputInit.takeAs<Expr>();
10100
Sebastian Redlf322ed62009-10-29 20:17:01 +000010101 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010102 QualType ResultTy = FnDecl->getResultType();
10103 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10104 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010105
10106 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010107 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10108 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010109 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10110 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010111 OpLocInfo.getLoc(),
10112 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010113 if (FnExpr.isInvalid())
10114 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010115
John McCall9ae2f072010-08-23 23:25:46 +000010116 CXXOperatorCallExpr *TheCall =
10117 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley429bb272011-04-08 18:41:53 +000010118 FnExpr.take(), Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +000010119 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010120
John McCall9ae2f072010-08-23 23:25:46 +000010121 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010122 FnDecl))
10123 return ExprError();
10124
John McCall9ae2f072010-08-23 23:25:46 +000010125 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010126 } else {
10127 // We matched a built-in operator. Convert the arguments, then
10128 // break out so that we will build the appropriate built-in
10129 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010130 ExprResult ArgsRes0 =
10131 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10132 Best->Conversions[0], AA_Passing);
10133 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010134 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010135 Args[0] = ArgsRes0.take();
10136
10137 ExprResult ArgsRes1 =
10138 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10139 Best->Conversions[1], AA_Passing);
10140 if (ArgsRes1.isInvalid())
10141 return ExprError();
10142 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010143
10144 break;
10145 }
10146 }
10147
10148 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010149 if (CandidateSet.empty())
10150 Diag(LLoc, diag::err_ovl_no_oper)
10151 << Args[0]->getType() << /*subscript*/ 0
10152 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10153 else
10154 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10155 << Args[0]->getType()
10156 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010157 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10158 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010159 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010160 }
10161
10162 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010163 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010164 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010165 << Args[0]->getType() << Args[1]->getType()
10166 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010167 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
10168 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010169 return ExprError();
10170
10171 case OR_Deleted:
10172 Diag(LLoc, diag::err_ovl_deleted_oper)
10173 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010174 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010175 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010176 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
10177 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010178 return ExprError();
10179 }
10180
10181 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010182 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010183}
10184
Douglas Gregor88a35142008-12-22 05:46:06 +000010185/// BuildCallToMemberFunction - Build a call to a member
10186/// function. MemExpr is the expression that refers to the member
10187/// function (and includes the object parameter), Args/NumArgs are the
10188/// arguments to the function call (not including the object
10189/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010190/// expression refers to a non-static member function or an overloaded
10191/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010192ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010193Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10194 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010195 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010196 assert(MemExprE->getType() == Context.BoundMemberTy ||
10197 MemExprE->getType() == Context.OverloadTy);
10198
Douglas Gregor88a35142008-12-22 05:46:06 +000010199 // Dig out the member expression. This holds both the object
10200 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010201 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010202
John McCall864c0412011-04-26 20:42:42 +000010203 // Determine whether this is a call to a pointer-to-member function.
10204 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10205 assert(op->getType() == Context.BoundMemberTy);
10206 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10207
10208 QualType fnType =
10209 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10210
10211 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10212 QualType resultType = proto->getCallResultType(Context);
10213 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10214
10215 // Check that the object type isn't more qualified than the
10216 // member function we're calling.
10217 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10218
10219 QualType objectType = op->getLHS()->getType();
10220 if (op->getOpcode() == BO_PtrMemI)
10221 objectType = objectType->castAs<PointerType>()->getPointeeType();
10222 Qualifiers objectQuals = objectType.getQualifiers();
10223
10224 Qualifiers difference = objectQuals - funcQuals;
10225 difference.removeObjCGCAttr();
10226 difference.removeAddressSpace();
10227 if (difference) {
10228 std::string qualsString = difference.getAsString();
10229 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10230 << fnType.getUnqualifiedType()
10231 << qualsString
10232 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10233 }
10234
10235 CXXMemberCallExpr *call
10236 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10237 resultType, valueKind, RParenLoc);
10238
10239 if (CheckCallReturnType(proto->getResultType(),
10240 op->getRHS()->getSourceRange().getBegin(),
10241 call, 0))
10242 return ExprError();
10243
10244 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10245 return ExprError();
10246
10247 return MaybeBindToTemporary(call);
10248 }
10249
John McCall5acb0c92011-10-17 18:40:02 +000010250 UnbridgedCastsSet UnbridgedCasts;
10251 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10252 return ExprError();
10253
John McCall129e2df2009-11-30 22:42:35 +000010254 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010255 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010256 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010257 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010258 if (isa<MemberExpr>(NakedMemExpr)) {
10259 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010260 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010261 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010262 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010263 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010264 } else {
10265 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010266 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010267
John McCall701c89e2009-12-03 04:06:58 +000010268 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010269 Expr::Classification ObjectClassification
10270 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10271 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010272
Douglas Gregor88a35142008-12-22 05:46:06 +000010273 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010274 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010275
John McCallaa81e162009-12-01 22:10:20 +000010276 // FIXME: avoid copy.
10277 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10278 if (UnresExpr->hasExplicitTemplateArgs()) {
10279 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10280 TemplateArgs = &TemplateArgsBuffer;
10281 }
10282
John McCall129e2df2009-11-30 22:42:35 +000010283 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10284 E = UnresExpr->decls_end(); I != E; ++I) {
10285
John McCall701c89e2009-12-03 04:06:58 +000010286 NamedDecl *Func = *I;
10287 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10288 if (isa<UsingShadowDecl>(Func))
10289 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10290
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010291
Francois Pichetdbee3412011-01-18 05:04:39 +000010292 // Microsoft supports direct constructor calls.
Francois Pichet62ec1f22011-09-17 17:15:52 +000010293 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichetdbee3412011-01-18 05:04:39 +000010294 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
10295 CandidateSet);
10296 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010297 // If explicit template arguments were provided, we can't call a
10298 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010299 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010300 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010301
John McCall9aa472c2010-03-19 07:35:19 +000010302 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010303 ObjectClassification,
10304 Args, NumArgs, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010305 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010306 } else {
John McCall129e2df2009-11-30 22:42:35 +000010307 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010308 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010309 ObjectType, ObjectClassification,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010310 Args, NumArgs, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010311 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010312 }
Douglas Gregordec06662009-08-21 18:42:58 +000010313 }
Mike Stump1eb44332009-09-09 15:08:12 +000010314
John McCall129e2df2009-11-30 22:42:35 +000010315 DeclarationName DeclName = UnresExpr->getMemberName();
10316
John McCall5acb0c92011-10-17 18:40:02 +000010317 UnbridgedCasts.restore();
10318
Douglas Gregor88a35142008-12-22 05:46:06 +000010319 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010320 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010321 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010322 case OR_Success:
10323 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010324 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +000010325 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010326 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010327 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010328 break;
10329
10330 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010331 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010332 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010333 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010334 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +000010335 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010336 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010337
10338 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010339 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010340 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010341 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +000010342 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010343 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010344
10345 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010346 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010347 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010348 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010349 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010350 << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010351 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010352 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010353 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010354 }
10355
John McCall6bb80172010-03-30 21:47:33 +000010356 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010357
John McCallaa81e162009-12-01 22:10:20 +000010358 // If overload resolution picked a static member, build a
10359 // non-member call based on that function.
10360 if (Method->isStatic()) {
10361 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10362 Args, NumArgs, RParenLoc);
10363 }
10364
John McCall129e2df2009-11-30 22:42:35 +000010365 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010366 }
10367
John McCallf89e55a2010-11-18 06:31:45 +000010368 QualType ResultType = Method->getResultType();
10369 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10370 ResultType = ResultType.getNonLValueExprType(Context);
10371
Douglas Gregor88a35142008-12-22 05:46:06 +000010372 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010373 CXXMemberCallExpr *TheCall =
John McCall9ae2f072010-08-23 23:25:46 +000010374 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +000010375 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010376
Anders Carlssoneed3e692009-10-10 00:06:20 +000010377 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010378 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010379 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010380 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010381
Douglas Gregor88a35142008-12-22 05:46:06 +000010382 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010383 // We only need to do this if there was actually an overload; otherwise
10384 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010385 if (!Method->isStatic()) {
10386 ExprResult ObjectArg =
10387 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10388 FoundDecl, Method);
10389 if (ObjectArg.isInvalid())
10390 return ExprError();
10391 MemExpr->setBase(ObjectArg.take());
10392 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010393
10394 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010395 const FunctionProtoType *Proto =
10396 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010397 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010398 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010399 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010400
Eli Friedmane61eb042012-02-18 04:48:30 +000010401 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10402
John McCall9ae2f072010-08-23 23:25:46 +000010403 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +000010404 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010405
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010406 if ((isa<CXXConstructorDecl>(CurContext) ||
10407 isa<CXXDestructorDecl>(CurContext)) &&
10408 TheCall->getMethodDecl()->isPure()) {
10409 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10410
Chandler Carruthae198062011-06-27 08:31:58 +000010411 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010412 Diag(MemExpr->getLocStart(),
10413 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10414 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10415 << MD->getParent()->getDeclName();
10416
10417 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010418 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010419 }
John McCall9ae2f072010-08-23 23:25:46 +000010420 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010421}
10422
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010423/// BuildCallToObjectOfClassType - Build a call to an object of class
10424/// type (C++ [over.call.object]), which can end up invoking an
10425/// overloaded function call operator (@c operator()) or performing a
10426/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010427ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010428Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010429 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010430 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010431 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010432 if (checkPlaceholderForOverload(*this, Obj))
10433 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010434 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010435
10436 UnbridgedCastsSet UnbridgedCasts;
10437 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10438 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010439
John Wiegley429bb272011-04-08 18:41:53 +000010440 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10441 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010442
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010443 // C++ [over.call.object]p1:
10444 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010445 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010446 // candidate functions includes at least the function call
10447 // operators of T. The function call operators of T are obtained by
10448 // ordinary lookup of the name operator() in the context of
10449 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010450 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010451 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010452
John Wiegley429bb272011-04-08 18:41:53 +000010453 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +000010454 PDiag(diag::err_incomplete_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010455 << Object.get()->getSourceRange()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010456 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010457
John McCalla24dc2e2009-11-17 02:14:36 +000010458 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10459 LookupQualifiedName(R, Record->getDecl());
10460 R.suppressDiagnostics();
10461
Douglas Gregor593564b2009-11-15 07:48:03 +000010462 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010463 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010464 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10465 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010466 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010467 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010468
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010469 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010470 // In addition, for each (non-explicit in C++0x) conversion function
10471 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010472 //
10473 // operator conversion-type-id () cv-qualifier;
10474 //
10475 // where cv-qualifier is the same cv-qualification as, or a
10476 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010477 // denotes the type "pointer to function of (P1,...,Pn) returning
10478 // R", or the type "reference to pointer to function of
10479 // (P1,...,Pn) returning R", or the type "reference to function
10480 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010481 // is also considered as a candidate function. Similarly,
10482 // surrogate call functions are added to the set of candidate
10483 // functions for each conversion function declared in an
10484 // accessible base class provided the function is not hidden
10485 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +000010486 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010487 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +000010488 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +000010489 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010490 NamedDecl *D = *I;
10491 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10492 if (isa<UsingShadowDecl>(D))
10493 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010494
Douglas Gregor4a27d702009-10-21 06:18:39 +000010495 // Skip over templated conversion functions; they aren't
10496 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010497 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010498 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010499
John McCall701c89e2009-12-03 04:06:58 +000010500 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010501 if (!Conv->isExplicit()) {
10502 // Strip the reference type (if any) and then the pointer type (if
10503 // any) to get down to what might be a function type.
10504 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10505 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10506 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010507
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010508 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10509 {
10510 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
10511 Object.get(), Args, NumArgs, CandidateSet);
10512 }
10513 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010514 }
Mike Stump1eb44332009-09-09 15:08:12 +000010515
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010516 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10517
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010518 // Perform overload resolution.
10519 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000010520 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000010521 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010522 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010523 // Overload resolution succeeded; we'll build the appropriate call
10524 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010525 break;
10526
10527 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000010528 if (CandidateSet.empty())
John Wiegley429bb272011-04-08 18:41:53 +000010529 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
10530 << Object.get()->getType() << /*call*/ 1
10531 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000010532 else
John Wiegley429bb272011-04-08 18:41:53 +000010533 Diag(Object.get()->getSourceRange().getBegin(),
John McCall1eb3e102010-01-07 02:04:15 +000010534 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010535 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010536 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010537 break;
10538
10539 case OR_Ambiguous:
John Wiegley429bb272011-04-08 18:41:53 +000010540 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010541 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010542 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010543 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010544 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010545
10546 case OR_Deleted:
John Wiegley429bb272011-04-08 18:41:53 +000010547 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010548 diag::err_ovl_deleted_object_call)
10549 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000010550 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010551 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000010552 << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010553 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010554 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010555 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010556
Douglas Gregorff331c12010-07-25 18:17:45 +000010557 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010558 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010559
John McCall5acb0c92011-10-17 18:40:02 +000010560 UnbridgedCasts.restore();
10561
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010562 if (Best->Function == 0) {
10563 // Since there is no function declaration, this is one of the
10564 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000010565 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010566 = cast<CXXConversionDecl>(
10567 Best->Conversions[0].UserDefined.ConversionFunction);
10568
John Wiegley429bb272011-04-08 18:41:53 +000010569 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010570 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010571
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010572 // We selected one of the surrogate functions that converts the
10573 // object parameter to a function pointer. Perform the conversion
10574 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010575
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000010576 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000010577 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010578 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10579 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010580 if (Call.isInvalid())
10581 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000010582 // Record usage of conversion in an implicit cast.
10583 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10584 CK_UserDefinedConversion,
10585 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010586
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010587 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000010588 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010589 }
10590
Eli Friedman5f2987c2012-02-02 03:46:19 +000010591 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010592 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010593 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010594
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010595 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10596 // that calls this method, using Object for the implicit object
10597 // parameter and passing along the remaining arguments.
10598 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +000010599 const FunctionProtoType *Proto =
10600 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010601
10602 unsigned NumArgsInProto = Proto->getNumArgs();
10603 unsigned NumArgsToCheck = NumArgs;
10604
10605 // Build the full argument list for the method call (the
10606 // implicit object parameter is placed at the beginning of the
10607 // list).
10608 Expr **MethodArgs;
10609 if (NumArgs < NumArgsInProto) {
10610 NumArgsToCheck = NumArgsInProto;
10611 MethodArgs = new Expr*[NumArgsInProto + 1];
10612 } else {
10613 MethodArgs = new Expr*[NumArgs + 1];
10614 }
John Wiegley429bb272011-04-08 18:41:53 +000010615 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010616 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10617 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000010618
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010619 DeclarationNameInfo OpLocInfo(
10620 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10621 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010622 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010623 HadMultipleCandidates,
10624 OpLocInfo.getLoc(),
10625 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010626 if (NewFn.isInvalid())
10627 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010628
10629 // Once we've built TheCall, all of the expressions are properly
10630 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000010631 QualType ResultTy = Method->getResultType();
10632 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10633 ResultTy = ResultTy.getNonLValueExprType(Context);
10634
John McCall9ae2f072010-08-23 23:25:46 +000010635 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010636 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCall9ae2f072010-08-23 23:25:46 +000010637 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +000010638 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010639 delete [] MethodArgs;
10640
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010641 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000010642 Method))
10643 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010644
Douglas Gregor518fda12009-01-13 05:10:00 +000010645 // We may have default arguments. If so, we need to allocate more
10646 // slots in the call for them.
10647 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000010648 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000010649 else if (NumArgs > NumArgsInProto)
10650 NumArgsToCheck = NumArgsInProto;
10651
Chris Lattner312531a2009-04-12 08:11:20 +000010652 bool IsError = false;
10653
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010654 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000010655 ExprResult ObjRes =
10656 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10657 Best->FoundDecl, Method);
10658 if (ObjRes.isInvalid())
10659 IsError = true;
10660 else
10661 Object = move(ObjRes);
10662 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000010663
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010664 // Check the argument types.
10665 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010666 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000010667 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010668 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000010669
Douglas Gregor518fda12009-01-13 05:10:00 +000010670 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000010671
John McCall60d7b3a2010-08-24 06:29:42 +000010672 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000010673 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010674 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000010675 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000010676 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010677
Anders Carlsson3faa4862010-01-29 18:43:53 +000010678 IsError |= InputInit.isInvalid();
10679 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010680 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000010681 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000010682 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10683 if (DefArg.isInvalid()) {
10684 IsError = true;
10685 break;
10686 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010687
Douglas Gregord47c47d2009-11-09 19:27:57 +000010688 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010689 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010690
10691 TheCall->setArg(i + 1, Arg);
10692 }
10693
10694 // If this is a variadic call, handle args passed through "...".
10695 if (Proto->isVariadic()) {
10696 // Promote the arguments (C99 6.5.2.2p7).
10697 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000010698 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10699 IsError |= Arg.isInvalid();
10700 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010701 }
10702 }
10703
Chris Lattner312531a2009-04-12 08:11:20 +000010704 if (IsError) return true;
10705
Eli Friedmane61eb042012-02-18 04:48:30 +000010706 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10707
John McCall9ae2f072010-08-23 23:25:46 +000010708 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +000010709 return true;
10710
John McCall182f7092010-08-24 06:09:16 +000010711 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010712}
10713
Douglas Gregor8ba10742008-11-20 16:27:02 +000010714/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000010715/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000010716/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000010717ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000010718Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000010719 assert(Base->getType()->isRecordType() &&
10720 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000010721
John McCall5acb0c92011-10-17 18:40:02 +000010722 if (checkPlaceholderForOverload(*this, Base))
10723 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010724
John McCall5769d612010-02-08 23:07:23 +000010725 SourceLocation Loc = Base->getExprLoc();
10726
Douglas Gregor8ba10742008-11-20 16:27:02 +000010727 // C++ [over.ref]p1:
10728 //
10729 // [...] An expression x->m is interpreted as (x.operator->())->m
10730 // for a class object x of type T if T::operator->() exists and if
10731 // the operator is selected as the best match function by the
10732 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000010733 DeclarationName OpName =
10734 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000010735 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000010736 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010737
John McCall5769d612010-02-08 23:07:23 +000010738 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +000010739 PDiag(diag::err_typecheck_incomplete_tag)
10740 << Base->getSourceRange()))
10741 return ExprError();
10742
John McCalla24dc2e2009-11-17 02:14:36 +000010743 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10744 LookupQualifiedName(R, BaseRecord->getDecl());
10745 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000010746
10747 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000010748 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010749 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10750 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000010751 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000010752
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010753 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10754
Douglas Gregor8ba10742008-11-20 16:27:02 +000010755 // Perform overload resolution.
10756 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010757 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000010758 case OR_Success:
10759 // Overload resolution succeeded; we'll build the call below.
10760 break;
10761
10762 case OR_No_Viable_Function:
10763 if (CandidateSet.empty())
10764 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010765 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010766 else
10767 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010768 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010769 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010770 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010771
10772 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010773 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10774 << "->" << Base->getType() << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010775 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010776 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010777
10778 case OR_Deleted:
10779 Diag(OpLoc, diag::err_ovl_deleted_oper)
10780 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010781 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010782 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010783 << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010784 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010785 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010786 }
10787
Eli Friedman5f2987c2012-02-02 03:46:19 +000010788 MarkFunctionReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000010789 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010790 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000010791
Douglas Gregor8ba10742008-11-20 16:27:02 +000010792 // Convert the object parameter.
10793 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010794 ExprResult BaseResult =
10795 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10796 Best->FoundDecl, Method);
10797 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010798 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010799 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000010800
Douglas Gregor8ba10742008-11-20 16:27:02 +000010801 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010802 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010803 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010804 if (FnExpr.isInvalid())
10805 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010806
John McCallf89e55a2010-11-18 06:31:45 +000010807 QualType ResultTy = Method->getResultType();
10808 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10809 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000010810 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010811 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000010812 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +000010813
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010814 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010815 Method))
10816 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000010817
10818 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000010819}
10820
Douglas Gregor904eed32008-11-10 20:40:00 +000010821/// FixOverloadedFunctionReference - E is an expression that refers to
10822/// a C++ overloaded function (possibly with some parentheses and
10823/// perhaps a '&' around it). We have resolved the overloaded function
10824/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000010825/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000010826Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000010827 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000010828 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000010829 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10830 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000010831 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010832 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010833
Douglas Gregor699ee522009-11-20 19:42:02 +000010834 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010835 }
10836
Douglas Gregor699ee522009-11-20 19:42:02 +000010837 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000010838 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10839 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010840 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000010841 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000010842 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000010843 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000010844 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010845 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010846
10847 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000010848 ICE->getCastKind(),
10849 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000010850 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010851 }
10852
Douglas Gregor699ee522009-11-20 19:42:02 +000010853 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000010854 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000010855 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000010856 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10857 if (Method->isStatic()) {
10858 // Do nothing: static member functions aren't any different
10859 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000010860 } else {
John McCallf7a1a742009-11-24 19:00:30 +000010861 // Fix the sub expression, which really has to be an
10862 // UnresolvedLookupExpr holding an overloaded member function
10863 // or template.
John McCall6bb80172010-03-30 21:47:33 +000010864 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10865 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000010866 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010867 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000010868
John McCallba135432009-11-21 08:51:07 +000010869 assert(isa<DeclRefExpr>(SubExpr)
10870 && "fixed to something other than a decl ref");
10871 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10872 && "fixed to a member ref with no nested name qualifier");
10873
10874 // We have taken the address of a pointer to member
10875 // function. Perform the computation here so that we get the
10876 // appropriate pointer to member type.
10877 QualType ClassType
10878 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10879 QualType MemPtrType
10880 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10881
John McCallf89e55a2010-11-18 06:31:45 +000010882 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10883 VK_RValue, OK_Ordinary,
10884 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000010885 }
10886 }
John McCall6bb80172010-03-30 21:47:33 +000010887 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10888 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000010889 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010890 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010891
John McCall2de56d12010-08-25 11:45:40 +000010892 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000010893 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000010894 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000010895 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010896 }
John McCallba135432009-11-21 08:51:07 +000010897
10898 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000010899 // FIXME: avoid copy.
10900 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000010901 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000010902 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10903 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000010904 }
10905
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010906 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10907 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010908 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010909 Fn,
10910 ULE->getNameLoc(),
10911 Fn->getType(),
10912 VK_LValue,
10913 Found.getDecl(),
10914 TemplateArgs);
10915 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10916 return DRE;
John McCallba135432009-11-21 08:51:07 +000010917 }
10918
John McCall129e2df2009-11-30 22:42:35 +000010919 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000010920 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000010921 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10922 if (MemExpr->hasExplicitTemplateArgs()) {
10923 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10924 TemplateArgs = &TemplateArgsBuffer;
10925 }
John McCalld5532b62009-11-23 01:53:49 +000010926
John McCallaa81e162009-12-01 22:10:20 +000010927 Expr *Base;
10928
John McCallf89e55a2010-11-18 06:31:45 +000010929 // If we're filling in a static method where we used to have an
10930 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000010931 if (MemExpr->isImplicitAccess()) {
10932 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010933 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10934 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010935 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010936 Fn,
10937 MemExpr->getMemberLoc(),
10938 Fn->getType(),
10939 VK_LValue,
10940 Found.getDecl(),
10941 TemplateArgs);
10942 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10943 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000010944 } else {
10945 SourceLocation Loc = MemExpr->getMemberLoc();
10946 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000010947 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000010948 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000010949 Base = new (Context) CXXThisExpr(Loc,
10950 MemExpr->getBaseType(),
10951 /*isImplicit=*/true);
10952 }
John McCallaa81e162009-12-01 22:10:20 +000010953 } else
John McCall3fa5cae2010-10-26 07:05:15 +000010954 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000010955
John McCallf5307512011-04-27 00:36:17 +000010956 ExprValueKind valueKind;
10957 QualType type;
10958 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10959 valueKind = VK_LValue;
10960 type = Fn->getType();
10961 } else {
10962 valueKind = VK_RValue;
10963 type = Context.BoundMemberTy;
10964 }
10965
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010966 MemberExpr *ME = MemberExpr::Create(Context, Base,
10967 MemExpr->isArrow(),
10968 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010969 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010970 Fn,
10971 Found,
10972 MemExpr->getMemberNameInfo(),
10973 TemplateArgs,
10974 type, valueKind, OK_Ordinary);
10975 ME->setHadMultipleCandidates(true);
10976 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000010977 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010978
John McCall3fa5cae2010-10-26 07:05:15 +000010979 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000010980}
10981
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010982ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000010983 DeclAccessPair Found,
10984 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000010985 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000010986}
10987
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000010988} // end namespace clang