blob: 57e74d06b95e563c2dd33698c2e0fcf962a53a93 [file] [log] [blame]
Douglas Gregor5251f1b2008-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
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Lex/Preprocessor.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000030#include "llvm/ADT/DenseSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000032#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034#include <algorithm>
35
36namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000037using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000038
John McCall7decc9e2010-11-18 06:31:45 +000039/// A convenience routine for creating a decayed reference to a
40/// function.
John Wiegley01296292011-04-08 18:41:53 +000041static ExprResult
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000042CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000043 SourceLocation Loc = SourceLocation(),
44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
John McCall113bee02012-03-10 09:33:50 +000045 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000046 VK_LValue, Loc, LocInfo);
47 if (HadMultipleCandidates)
48 DRE->setHadMultipleCandidates(true);
49 ExprResult E = S.Owned(DRE);
John Wiegley01296292011-04-08 18:41:53 +000050 E = S.DefaultFunctionArrayConversion(E.take());
51 if (E.isInvalid())
52 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +000053 return E;
John McCall7decc9e2010-11-18 06:31:45 +000054}
55
John McCall5c32be02010-08-24 20:38:10 +000056static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
57 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000058 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000059 bool CStyle,
60 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000061
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000062static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
63 QualType &ToType,
64 bool InOverloadResolution,
65 StandardConversionSequence &SCS,
66 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000067static OverloadingResult
68IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
69 UserDefinedConversionSequence& User,
70 OverloadCandidateSet& Conversions,
71 bool AllowExplicit);
72
73
74static ImplicitConversionSequence::CompareKind
75CompareStandardConversionSequences(Sema &S,
76 const StandardConversionSequence& SCS1,
77 const StandardConversionSequence& SCS2);
78
79static ImplicitConversionSequence::CompareKind
80CompareQualificationConversions(Sema &S,
81 const StandardConversionSequence& SCS1,
82 const StandardConversionSequence& SCS2);
83
84static ImplicitConversionSequence::CompareKind
85CompareDerivedToBaseConversions(Sema &S,
86 const StandardConversionSequence& SCS1,
87 const StandardConversionSequence& SCS2);
88
89
90
Douglas Gregor5251f1b2008-10-21 16:13:35 +000091/// GetConversionCategory - Retrieve the implicit conversion
92/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000093ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000094GetConversionCategory(ImplicitConversionKind Kind) {
95 static const ImplicitConversionCategory
96 Category[(int)ICK_Num_Conversion_Kinds] = {
97 ICC_Identity,
98 ICC_Lvalue_Transformation,
99 ICC_Lvalue_Transformation,
100 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000101 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000102 ICC_Qualification_Adjustment,
103 ICC_Promotion,
104 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000105 ICC_Promotion,
106 ICC_Conversion,
107 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
111 ICC_Conversion,
112 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000113 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000114 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000115 ICC_Conversion,
116 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000117 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000118 ICC_Conversion
119 };
120 return Category[(int)Kind];
121}
122
123/// GetConversionRank - Retrieve the implicit conversion rank
124/// corresponding to the given implicit conversion kind.
125ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
126 static const ImplicitConversionRank
127 Rank[(int)ICK_Num_Conversion_Kinds] = {
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
131 ICR_Exact_Match,
132 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000133 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000134 ICR_Promotion,
135 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000136 ICR_Promotion,
137 ICR_Conversion,
138 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
143 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000144 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000145 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000146 ICR_Conversion,
147 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000148 ICR_Complex_Real_Conversion,
149 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000150 ICR_Conversion,
151 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000152 };
153 return Rank[(int)Kind];
154}
155
156/// GetImplicitConversionName - Return the name of this kind of
157/// implicit conversion.
158const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000159 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000160 "No conversion",
161 "Lvalue-to-rvalue",
162 "Array-to-pointer",
163 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000164 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000165 "Qualification",
166 "Integral promotion",
167 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000168 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000169 "Integral conversion",
170 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000171 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000172 "Floating-integral conversion",
173 "Pointer conversion",
174 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000175 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000176 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000177 "Derived-to-base conversion",
178 "Vector conversion",
179 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000180 "Complex-real conversion",
181 "Block Pointer conversion",
182 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000183 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000184 };
185 return Name[Kind];
186}
187
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000188/// StandardConversionSequence - Set the standard conversion
189/// sequence to the identity conversion.
190void StandardConversionSequence::setAsIdentityConversion() {
191 First = ICK_Identity;
192 Second = ICK_Identity;
193 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000194 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000195 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000196 ReferenceBinding = false;
197 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000198 IsLvalueReference = true;
199 BindsToFunctionLvalue = false;
200 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000201 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000202 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000203 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000204}
205
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000206/// getRank - Retrieve the rank of this standard conversion sequence
207/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
208/// implicit conversions.
209ImplicitConversionRank StandardConversionSequence::getRank() const {
210 ImplicitConversionRank Rank = ICR_Exact_Match;
211 if (GetConversionRank(First) > Rank)
212 Rank = GetConversionRank(First);
213 if (GetConversionRank(Second) > Rank)
214 Rank = GetConversionRank(Second);
215 if (GetConversionRank(Third) > Rank)
216 Rank = GetConversionRank(Third);
217 return Rank;
218}
219
220/// isPointerConversionToBool - Determines whether this conversion is
221/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000222/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000224bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000225 // Note that FromType has not necessarily been transformed by the
226 // array-to-pointer or function-to-pointer implicit conversions, so
227 // check for their presence as well as checking whether FromType is
228 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000229 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000230 (getFromType()->isPointerType() ||
231 getFromType()->isObjCObjectPointerType() ||
232 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000233 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000234 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
235 return true;
236
237 return false;
238}
239
Douglas Gregor5c407d92008-10-23 00:40:37 +0000240/// isPointerConversionToVoidPointer - Determines whether this
241/// conversion is a conversion of a pointer to a void pointer. This is
242/// used as part of the ranking of standard conversion sequences (C++
243/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000244bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000245StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000246isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000247 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000248 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000249
250 // Note that FromType has not necessarily been transformed by the
251 // array-to-pointer implicit conversion, so check for its presence
252 // and redo the conversion to get a pointer.
253 if (First == ICK_Array_To_Pointer)
254 FromType = Context.getArrayDecayedType(FromType);
255
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000256 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000257 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000258 return ToPtrType->getPointeeType()->isVoidType();
259
260 return false;
261}
262
Richard Smith66e05fe2012-01-18 05:21:49 +0000263/// Skip any implicit casts which could be either part of a narrowing conversion
264/// or after one in an implicit conversion.
265static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
266 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
267 switch (ICE->getCastKind()) {
268 case CK_NoOp:
269 case CK_IntegralCast:
270 case CK_IntegralToBoolean:
271 case CK_IntegralToFloating:
272 case CK_FloatingToIntegral:
273 case CK_FloatingToBoolean:
274 case CK_FloatingCast:
275 Converted = ICE->getSubExpr();
276 continue;
277
278 default:
279 return Converted;
280 }
281 }
282
283 return Converted;
284}
285
286/// Check if this standard conversion sequence represents a narrowing
287/// conversion, according to C++11 [dcl.init.list]p7.
288///
289/// \param Ctx The AST context.
290/// \param Converted The result of applying this standard conversion sequence.
291/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
292/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000293/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
294/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000295NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000296StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
297 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000298 APValue &ConstantValue,
299 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000300 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000301
302 // C++11 [dcl.init.list]p7:
303 // A narrowing conversion is an implicit conversion ...
304 QualType FromType = getToType(0);
305 QualType ToType = getToType(1);
306 switch (Second) {
307 // -- from a floating-point type to an integer type, or
308 //
309 // -- from an integer type or unscoped enumeration type to a floating-point
310 // type, except where the source is a constant expression and the actual
311 // value after conversion will fit into the target type and will produce
312 // the original value when converted back to the original type, or
313 case ICK_Floating_Integral:
314 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
315 return NK_Type_Narrowing;
316 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
317 llvm::APSInt IntConstantValue;
318 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
319 if (Initializer &&
320 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
321 // Convert the integer to the floating type.
322 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
323 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
324 llvm::APFloat::rmNearestTiesToEven);
325 // And back.
326 llvm::APSInt ConvertedValue = IntConstantValue;
327 bool ignored;
328 Result.convertToInteger(ConvertedValue,
329 llvm::APFloat::rmTowardZero, &ignored);
330 // If the resulting value is different, this was a narrowing conversion.
331 if (IntConstantValue != ConvertedValue) {
332 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000333 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000334 return NK_Constant_Narrowing;
335 }
336 } else {
337 // Variables are always narrowings.
338 return NK_Variable_Narrowing;
339 }
340 }
341 return NK_Not_Narrowing;
342
343 // -- from long double to double or float, or from double to float, except
344 // where the source is a constant expression and the actual value after
345 // conversion is within the range of values that can be represented (even
346 // if it cannot be represented exactly), or
347 case ICK_Floating_Conversion:
348 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
349 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
350 // FromType is larger than ToType.
351 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
352 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
353 // Constant!
354 assert(ConstantValue.isFloat());
355 llvm::APFloat FloatVal = ConstantValue.getFloat();
356 // Convert the source value into the target type.
357 bool ignored;
358 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
359 Ctx.getFloatTypeSemantics(ToType),
360 llvm::APFloat::rmNearestTiesToEven, &ignored);
361 // If there was no overflow, the source value is within the range of
362 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000363 if (ConvertStatus & llvm::APFloat::opOverflow) {
364 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000365 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000366 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000367 } else {
368 return NK_Variable_Narrowing;
369 }
370 }
371 return NK_Not_Narrowing;
372
373 // -- from an integer type or unscoped enumeration type to an integer type
374 // that cannot represent all the values of the original type, except where
375 // the source is a constant expression and the actual value after
376 // conversion will fit into the target type and will produce the original
377 // value when converted back to the original type.
378 case ICK_Boolean_Conversion: // Bools are integers too.
379 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
380 // Boolean conversions can be from pointers and pointers to members
381 // [conv.bool], and those aren't considered narrowing conversions.
382 return NK_Not_Narrowing;
383 } // Otherwise, fall through to the integral case.
384 case ICK_Integral_Conversion: {
385 assert(FromType->isIntegralOrUnscopedEnumerationType());
386 assert(ToType->isIntegralOrUnscopedEnumerationType());
387 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
388 const unsigned FromWidth = Ctx.getIntWidth(FromType);
389 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
390 const unsigned ToWidth = Ctx.getIntWidth(ToType);
391
392 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000393 (FromWidth == ToWidth && FromSigned != ToSigned) ||
394 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000395 // Not all values of FromType can be represented in ToType.
396 llvm::APSInt InitializerValue;
397 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000398 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
399 // Such conversions on variables are always narrowing.
400 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000401 }
402 bool Narrowing = false;
403 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000404 // Negative -> unsigned is narrowing. Otherwise, more bits is never
405 // narrowing.
406 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000407 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000408 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000409 // Add a bit to the InitializerValue so we don't have to worry about
410 // signed vs. unsigned comparisons.
411 InitializerValue = InitializerValue.extend(
412 InitializerValue.getBitWidth() + 1);
413 // Convert the initializer to and from the target width and signed-ness.
414 llvm::APSInt ConvertedValue = InitializerValue;
415 ConvertedValue = ConvertedValue.trunc(ToWidth);
416 ConvertedValue.setIsSigned(ToSigned);
417 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
418 ConvertedValue.setIsSigned(InitializerValue.isSigned());
419 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000420 if (ConvertedValue != InitializerValue)
421 Narrowing = true;
422 }
423 if (Narrowing) {
424 ConstantType = Initializer->getType();
425 ConstantValue = APValue(InitializerValue);
426 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000427 }
428 }
429 return NK_Not_Narrowing;
430 }
431
432 default:
433 // Other kinds of conversions are not narrowings.
434 return NK_Not_Narrowing;
435 }
436}
437
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000438/// DebugPrint - Print this standard conversion sequence to standard
439/// error. Useful for debugging overloading issues.
440void StandardConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000441 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000442 bool PrintedSomething = false;
443 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000444 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000445 PrintedSomething = true;
446 }
447
448 if (Second != ICK_Identity) {
449 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000450 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000451 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000452 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000453
454 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000455 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000456 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000457 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000458 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000459 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000460 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000461 PrintedSomething = true;
462 }
463
464 if (Third != ICK_Identity) {
465 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000466 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000467 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000468 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000469 PrintedSomething = true;
470 }
471
472 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000473 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474 }
475}
476
477/// DebugPrint - Print this user-defined conversion sequence to standard
478/// error. Useful for debugging overloading issues.
479void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000480 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000481 if (Before.First || Before.Second || Before.Third) {
482 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000483 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000485 if (ConversionFunction)
486 OS << '\'' << *ConversionFunction << '\'';
487 else
488 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000490 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491 After.DebugPrint();
492 }
493}
494
495/// DebugPrint - Print this implicit conversion sequence to standard
496/// error. Useful for debugging overloading issues.
497void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000498 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000499 switch (ConversionKind) {
500 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000501 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000502 Standard.DebugPrint();
503 break;
504 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000505 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506 UserDefined.DebugPrint();
507 break;
508 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000509 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000510 break;
John McCall0d1da222010-01-12 00:44:57 +0000511 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000512 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000513 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000514 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000515 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000516 break;
517 }
518
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000519 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520}
521
John McCall0d1da222010-01-12 00:44:57 +0000522void AmbiguousConversionSequence::construct() {
523 new (&conversions()) ConversionSet();
524}
525
526void AmbiguousConversionSequence::destruct() {
527 conversions().~ConversionSet();
528}
529
530void
531AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
532 FromTypePtr = O.FromTypePtr;
533 ToTypePtr = O.ToTypePtr;
534 new (&conversions()) ConversionSet(O.conversions());
535}
536
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000537namespace {
538 // Structure used by OverloadCandidate::DeductionFailureInfo to store
539 // template parameter and template argument information.
540 struct DFIParamWithArguments {
541 TemplateParameter Param;
542 TemplateArgument FirstArg;
543 TemplateArgument SecondArg;
544 };
545}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000546
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000547/// \brief Convert from Sema's representation of template deduction information
548/// to the form used in overload-candidate information.
549OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000550static MakeDeductionFailureInfo(ASTContext &Context,
551 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000552 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000553 OverloadCandidate::DeductionFailureInfo Result;
554 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000555 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000556 Result.Data = 0;
557 switch (TDK) {
558 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000559 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000560 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000561 case Sema::TDK_TooManyArguments:
562 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000563 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000565 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000566 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567 Result.Data = Info.Param.getOpaqueValue();
568 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000569
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000570 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000571 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000572 // FIXME: Should allocate from normal heap so that we can free this later.
573 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000574 Saved->Param = Info.Param;
575 Saved->FirstArg = Info.FirstArg;
576 Saved->SecondArg = Info.SecondArg;
577 Result.Data = Saved;
578 break;
579 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000581 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000582 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000583 if (Info.hasSFINAEDiagnostic()) {
584 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
585 SourceLocation(), PartialDiagnostic::NullDiagnostic());
586 Info.takeSFINAEDiagnostic(*Diag);
587 Result.HasDiagnostic = true;
588 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000589 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000591 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000592 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000596 return Result;
597}
John McCall0d1da222010-01-12 00:44:57 +0000598
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000599void OverloadCandidate::DeductionFailureInfo::Destroy() {
600 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
601 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000602 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000603 case Sema::TDK_InstantiationDepth:
604 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000605 case Sema::TDK_TooManyArguments:
606 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000607 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000608 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000610 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000611 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000612 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000613 Data = 0;
614 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000615
616 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000617 // FIXME: Destroy the template argument list?
Douglas Gregord09efd42010-05-08 20:07:26 +0000618 Data = 0;
Richard Smith9ca64612012-05-07 09:03:25 +0000619 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
620 Diag->~PartialDiagnosticAt();
621 HasDiagnostic = false;
622 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000623 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000624
Douglas Gregor461761d2010-05-08 18:20:53 +0000625 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000626 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000627 case Sema::TDK_FailedOverloadResolution:
628 break;
629 }
630}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000631
Richard Smith9ca64612012-05-07 09:03:25 +0000632PartialDiagnosticAt *
633OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
634 if (HasDiagnostic)
635 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
636 return 0;
637}
638
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000640OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
641 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
642 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000643 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000644 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000645 case Sema::TDK_TooManyArguments:
646 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000647 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000648 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000649
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000650 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000651 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000652 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000653
654 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000655 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000656 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000657
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000658 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000659 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000660 case Sema::TDK_FailedOverloadResolution:
661 break;
662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000663
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000664 return TemplateParameter();
665}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000666
Douglas Gregord09efd42010-05-08 20:07:26 +0000667TemplateArgumentList *
668OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
669 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
670 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000671 case Sema::TDK_Invalid:
Douglas Gregord09efd42010-05-08 20:07:26 +0000672 case Sema::TDK_InstantiationDepth:
673 case Sema::TDK_TooManyArguments:
674 case Sema::TDK_TooFewArguments:
675 case Sema::TDK_Incomplete:
676 case Sema::TDK_InvalidExplicitArguments:
677 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000678 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000679 return 0;
680
681 case Sema::TDK_SubstitutionFailure:
682 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000683
Douglas Gregord09efd42010-05-08 20:07:26 +0000684 // Unhandled
685 case Sema::TDK_NonDeducedMismatch:
686 case Sema::TDK_FailedOverloadResolution:
687 break;
688 }
689
690 return 0;
691}
692
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000693const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
694 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
695 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000696 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000697 case Sema::TDK_InstantiationDepth:
698 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000699 case Sema::TDK_TooManyArguments:
700 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000701 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000702 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000703 return 0;
704
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000705 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000706 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000707 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000708
Douglas Gregor461761d2010-05-08 18:20:53 +0000709 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000710 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000711 case Sema::TDK_FailedOverloadResolution:
712 break;
713 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000715 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000717
718const TemplateArgument *
719OverloadCandidate::DeductionFailureInfo::getSecondArg() {
720 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
721 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000722 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000723 case Sema::TDK_InstantiationDepth:
724 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000725 case Sema::TDK_TooManyArguments:
726 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000727 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000728 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000729 return 0;
730
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000731 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000732 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000733 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
734
Douglas Gregor461761d2010-05-08 18:20:53 +0000735 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000736 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000737 case Sema::TDK_FailedOverloadResolution:
738 break;
739 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000740
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000741 return 0;
742}
743
Benjamin Kramer97e59492012-10-09 15:52:25 +0000744void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000745 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000746 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
747 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000748 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
749 i->DeductionFailure.Destroy();
750 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000751}
752
753void OverloadCandidateSet::clear() {
754 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000755 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000756 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000757 Functions.clear();
758}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000759
John McCall4124c492011-10-17 18:40:02 +0000760namespace {
761 class UnbridgedCastsSet {
762 struct Entry {
763 Expr **Addr;
764 Expr *Saved;
765 };
766 SmallVector<Entry, 2> Entries;
767
768 public:
769 void save(Sema &S, Expr *&E) {
770 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
771 Entry entry = { &E, E };
772 Entries.push_back(entry);
773 E = S.stripARCUnbridgedCast(E);
774 }
775
776 void restore() {
777 for (SmallVectorImpl<Entry>::iterator
778 i = Entries.begin(), e = Entries.end(); i != e; ++i)
779 *i->Addr = i->Saved;
780 }
781 };
782}
783
784/// checkPlaceholderForOverload - Do any interesting placeholder-like
785/// preprocessing on the given expression.
786///
787/// \param unbridgedCasts a collection to which to add unbridged casts;
788/// without this, they will be immediately diagnosed as errors
789///
790/// Return true on unrecoverable error.
791static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
792 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000793 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
794 // We can't handle overloaded expressions here because overload
795 // resolution might reasonably tweak them.
796 if (placeholder->getKind() == BuiltinType::Overload) return false;
797
798 // If the context potentially accepts unbridged ARC casts, strip
799 // the unbridged cast and add it to the collection for later restoration.
800 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
801 unbridgedCasts) {
802 unbridgedCasts->save(S, E);
803 return false;
804 }
805
806 // Go ahead and check everything else.
807 ExprResult result = S.CheckPlaceholderExpr(E);
808 if (result.isInvalid())
809 return true;
810
811 E = result.take();
812 return false;
813 }
814
815 // Nothing to do.
816 return false;
817}
818
819/// checkArgPlaceholdersForOverload - Check a set of call operands for
820/// placeholders.
821static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
822 unsigned numArgs,
823 UnbridgedCastsSet &unbridged) {
824 for (unsigned i = 0; i != numArgs; ++i)
825 if (checkPlaceholderForOverload(S, args[i], &unbridged))
826 return true;
827
828 return false;
829}
830
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000831// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000832// overload of the declarations in Old. This routine returns false if
833// New and Old cannot be overloaded, e.g., if New has the same
834// signature as some function in Old (C++ 1.3.10) or if the Old
835// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000836// it does return false, MatchedDecl will point to the decl that New
837// cannot be overloaded with. This decl may be a UsingShadowDecl on
838// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000839//
840// Example: Given the following input:
841//
842// void f(int, float); // #1
843// void f(int, int); // #2
844// int f(int, int); // #3
845//
846// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000847// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000848//
John McCall3d988d92009-12-02 08:47:38 +0000849// When we process #2, Old contains only the FunctionDecl for #1. By
850// comparing the parameter types, we see that #1 and #2 are overloaded
851// (since they have different signatures), so this routine returns
852// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000853//
John McCall3d988d92009-12-02 08:47:38 +0000854// When we process #3, Old is an overload set containing #1 and #2. We
855// compare the signatures of #3 to #1 (they're overloaded, so we do
856// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
857// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000858// signature), IsOverload returns false and MatchedDecl will be set to
859// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000860//
861// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
862// into a class by a using declaration. The rules for whether to hide
863// shadow declarations ignore some properties which otherwise figure
864// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000865Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000866Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
867 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000868 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000869 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000870 NamedDecl *OldD = *I;
871
872 bool OldIsUsingDecl = false;
873 if (isa<UsingShadowDecl>(OldD)) {
874 OldIsUsingDecl = true;
875
876 // We can always introduce two using declarations into the same
877 // context, even if they have identical signatures.
878 if (NewIsUsingDecl) continue;
879
880 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
881 }
882
883 // If either declaration was introduced by a using declaration,
884 // we'll need to use slightly different rules for matching.
885 // Essentially, these rules are the normal rules, except that
886 // function templates hide function templates with different
887 // return types or template parameter lists.
888 bool UseMemberUsingDeclRules =
889 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
890
John McCall3d988d92009-12-02 08:47:38 +0000891 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000892 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
893 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
894 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
895 continue;
896 }
897
John McCalldaa3d6b2009-12-09 03:35:25 +0000898 Match = *I;
899 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000900 }
John McCall3d988d92009-12-02 08:47:38 +0000901 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000902 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
903 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
904 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
905 continue;
906 }
907
John McCalldaa3d6b2009-12-09 03:35:25 +0000908 Match = *I;
909 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000910 }
John McCalla8987a2942010-11-10 03:01:53 +0000911 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000912 // We can overload with these, which can show up when doing
913 // redeclaration checks for UsingDecls.
914 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000915 } else if (isa<TagDecl>(OldD)) {
916 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000917 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
918 // Optimistically assume that an unresolved using decl will
919 // overload; if it doesn't, we'll have to diagnose during
920 // template instantiation.
921 } else {
John McCall1f82f242009-11-18 22:49:29 +0000922 // (C++ 13p1):
923 // Only function declarations can be overloaded; object and type
924 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000925 Match = *I;
926 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000927 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000928 }
John McCall1f82f242009-11-18 22:49:29 +0000929
John McCalldaa3d6b2009-12-09 03:35:25 +0000930 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000931}
932
John McCalle9cccd82010-06-16 08:42:20 +0000933bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
934 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000935 // If both of the functions are extern "C", then they are not
936 // overloads.
937 if (Old->isExternC() && New->isExternC())
938 return false;
939
John McCall1f82f242009-11-18 22:49:29 +0000940 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
941 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
942
943 // C++ [temp.fct]p2:
944 // A function template can be overloaded with other function templates
945 // and with normal (non-template) functions.
946 if ((OldTemplate == 0) != (NewTemplate == 0))
947 return true;
948
949 // Is the function New an overload of the function Old?
950 QualType OldQType = Context.getCanonicalType(Old->getType());
951 QualType NewQType = Context.getCanonicalType(New->getType());
952
953 // Compare the signatures (C++ 1.3.10) of the two functions to
954 // determine whether they are overloads. If we find any mismatch
955 // in the signature, they are overloads.
956
957 // If either of these functions is a K&R-style function (no
958 // prototype), then we consider them to have matching signatures.
959 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
960 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
961 return false;
962
John McCall424cec92011-01-19 06:33:43 +0000963 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
964 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000965
966 // The signature of a function includes the types of its
967 // parameters (C++ 1.3.10), which includes the presence or absence
968 // of the ellipsis; see C++ DR 357).
969 if (OldQType != NewQType &&
970 (OldType->getNumArgs() != NewType->getNumArgs() ||
971 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000972 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000973 return true;
974
975 // C++ [temp.over.link]p4:
976 // The signature of a function template consists of its function
977 // signature, its return type and its template parameter list. The names
978 // of the template parameters are significant only for establishing the
979 // relationship between the template parameters and the rest of the
980 // signature.
981 //
982 // We check the return type and template parameter lists for function
983 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000984 //
985 // However, we don't consider either of these when deciding whether
986 // a member introduced by a shadow declaration is hidden.
987 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000988 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
989 OldTemplate->getTemplateParameters(),
990 false, TPL_TemplateMatch) ||
991 OldType->getResultType() != NewType->getResultType()))
992 return true;
993
994 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000995 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000996 //
997 // As part of this, also check whether one of the member functions
998 // is static, in which case they are not overloads (C++
999 // 13.1p2). While not part of the definition of the signature,
1000 // this check is important to determine whether these functions
1001 // can be overloaded.
1002 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1003 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1004 if (OldMethod && NewMethod &&
1005 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001006 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +00001007 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
1008 if (!UseUsingDeclRules &&
1009 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
1010 (OldMethod->getRefQualifier() == RQ_None ||
1011 NewMethod->getRefQualifier() == RQ_None)) {
1012 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001013 // - Member function declarations with the same name and the same
1014 // parameter-type-list as well as member function template
1015 // declarations with the same name, the same parameter-type-list, and
1016 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +00001017 // them, but not all, have a ref-qualifier (8.3.5).
1018 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1019 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1020 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1021 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001022
John McCall1f82f242009-11-18 22:49:29 +00001023 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001025
John McCall1f82f242009-11-18 22:49:29 +00001026 // The signatures match; this is not an overload.
1027 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001028}
1029
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001030/// \brief Checks availability of the function depending on the current
1031/// function context. Inside an unavailable function, unavailability is ignored.
1032///
1033/// \returns true if \arg FD is unavailable and current context is inside
1034/// an available function, false otherwise.
1035bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1036 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1037}
1038
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001039/// \brief Tries a user-defined conversion from From to ToType.
1040///
1041/// Produces an implicit conversion sequence for when a standard conversion
1042/// is not an option. See TryImplicitConversion for more information.
1043static ImplicitConversionSequence
1044TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1045 bool SuppressUserConversions,
1046 bool AllowExplicit,
1047 bool InOverloadResolution,
1048 bool CStyle,
1049 bool AllowObjCWritebackConversion) {
1050 ImplicitConversionSequence ICS;
1051
1052 if (SuppressUserConversions) {
1053 // We're not in the case above, so there is no conversion that
1054 // we can perform.
1055 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1056 return ICS;
1057 }
1058
1059 // Attempt user-defined conversion.
1060 OverloadCandidateSet Conversions(From->getExprLoc());
1061 OverloadingResult UserDefResult
1062 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1063 AllowExplicit);
1064
1065 if (UserDefResult == OR_Success) {
1066 ICS.setUserDefined();
1067 // C++ [over.ics.user]p4:
1068 // A conversion of an expression of class type to the same class
1069 // type is given Exact Match rank, and a conversion of an
1070 // expression of class type to a base class of that type is
1071 // given Conversion rank, in spite of the fact that a copy
1072 // constructor (i.e., a user-defined conversion function) is
1073 // called for those cases.
1074 if (CXXConstructorDecl *Constructor
1075 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1076 QualType FromCanon
1077 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1078 QualType ToCanon
1079 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1080 if (Constructor->isCopyConstructor() &&
1081 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1082 // Turn this into a "standard" conversion sequence, so that it
1083 // gets ranked with standard conversion sequences.
1084 ICS.setStandard();
1085 ICS.Standard.setAsIdentityConversion();
1086 ICS.Standard.setFromType(From->getType());
1087 ICS.Standard.setAllToTypes(ToType);
1088 ICS.Standard.CopyConstructor = Constructor;
1089 if (ToCanon != FromCanon)
1090 ICS.Standard.Second = ICK_Derived_To_Base;
1091 }
1092 }
1093
1094 // C++ [over.best.ics]p4:
1095 // However, when considering the argument of a user-defined
1096 // conversion function that is a candidate by 13.3.1.3 when
1097 // invoked for the copying of the temporary in the second step
1098 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1099 // 13.3.1.6 in all cases, only standard conversion sequences and
1100 // ellipsis conversion sequences are allowed.
1101 if (SuppressUserConversions && ICS.isUserDefined()) {
1102 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1103 }
1104 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1105 ICS.setAmbiguous();
1106 ICS.Ambiguous.setFromType(From->getType());
1107 ICS.Ambiguous.setToType(ToType);
1108 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1109 Cand != Conversions.end(); ++Cand)
1110 if (Cand->Viable)
1111 ICS.Ambiguous.addConversion(Cand->Function);
1112 } else {
1113 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1114 }
1115
1116 return ICS;
1117}
1118
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001119/// TryImplicitConversion - Attempt to perform an implicit conversion
1120/// from the given expression (Expr) to the given type (ToType). This
1121/// function returns an implicit conversion sequence that can be used
1122/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001123///
1124/// void f(float f);
1125/// void g(int i) { f(i); }
1126///
1127/// this routine would produce an implicit conversion sequence to
1128/// describe the initialization of f from i, which will be a standard
1129/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1130/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1131//
1132/// Note that this routine only determines how the conversion can be
1133/// performed; it does not actually perform the conversion. As such,
1134/// it will not produce any diagnostics if no conversion is available,
1135/// but will instead return an implicit conversion sequence of kind
1136/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001137///
1138/// If @p SuppressUserConversions, then user-defined conversions are
1139/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001140/// If @p AllowExplicit, then explicit user-defined conversions are
1141/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001142///
1143/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1144/// writeback conversion, which allows __autoreleasing id* parameters to
1145/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001146static ImplicitConversionSequence
1147TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1148 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001149 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001150 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001151 bool CStyle,
1152 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001153 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001154 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001155 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001156 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001157 return ICS;
1158 }
1159
David Blaikiebbafb8a2012-03-11 07:00:24 +00001160 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001161 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001162 return ICS;
1163 }
1164
Douglas Gregor836a7e82010-08-11 02:15:33 +00001165 // C++ [over.ics.user]p4:
1166 // A conversion of an expression of class type to the same class
1167 // type is given Exact Match rank, and a conversion of an
1168 // expression of class type to a base class of that type is
1169 // given Conversion rank, in spite of the fact that a copy/move
1170 // constructor (i.e., a user-defined conversion function) is
1171 // called for those cases.
1172 QualType FromType = From->getType();
1173 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001174 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1175 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001176 ICS.setStandard();
1177 ICS.Standard.setAsIdentityConversion();
1178 ICS.Standard.setFromType(FromType);
1179 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001180
Douglas Gregor5ab11652010-04-17 22:01:05 +00001181 // We don't actually check at this point whether there is a valid
1182 // copy/move constructor, since overloading just assumes that it
1183 // exists. When we actually perform initialization, we'll find the
1184 // appropriate constructor to copy the returned object, if needed.
1185 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001186
Douglas Gregor5ab11652010-04-17 22:01:05 +00001187 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001188 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001189 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001190
Douglas Gregor836a7e82010-08-11 02:15:33 +00001191 return ICS;
1192 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001193
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001194 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1195 AllowExplicit, InOverloadResolution, CStyle,
1196 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001197}
1198
John McCall31168b02011-06-15 23:02:42 +00001199ImplicitConversionSequence
1200Sema::TryImplicitConversion(Expr *From, QualType ToType,
1201 bool SuppressUserConversions,
1202 bool AllowExplicit,
1203 bool InOverloadResolution,
1204 bool CStyle,
1205 bool AllowObjCWritebackConversion) {
1206 return clang::TryImplicitConversion(*this, From, ToType,
1207 SuppressUserConversions, AllowExplicit,
1208 InOverloadResolution, CStyle,
1209 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +00001210}
1211
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001212/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001213/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001214/// converted expression. Flavor is the kind of conversion we're
1215/// performing, used in the error message. If @p AllowExplicit,
1216/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001217ExprResult
1218Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001219 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001220 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001221 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001222}
1223
John Wiegley01296292011-04-08 18:41:53 +00001224ExprResult
1225Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001226 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001227 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001228 if (checkPlaceholderForOverload(*this, From))
1229 return ExprError();
1230
John McCall31168b02011-06-15 23:02:42 +00001231 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1232 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001233 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001234 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001235
John McCall5c32be02010-08-24 20:38:10 +00001236 ICS = clang::TryImplicitConversion(*this, From, ToType,
1237 /*SuppressUserConversions=*/false,
1238 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001239 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001240 /*CStyle=*/false,
1241 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001242 return PerformImplicitConversion(From, ToType, ICS, Action);
1243}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001244
1245/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001246/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001247bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1248 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001249 if (Context.hasSameUnqualifiedType(FromType, ToType))
1250 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001251
John McCall991eb4b2010-12-21 00:44:39 +00001252 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1253 // where F adds one of the following at most once:
1254 // - a pointer
1255 // - a member pointer
1256 // - a block pointer
1257 CanQualType CanTo = Context.getCanonicalType(ToType);
1258 CanQualType CanFrom = Context.getCanonicalType(FromType);
1259 Type::TypeClass TyClass = CanTo->getTypeClass();
1260 if (TyClass != CanFrom->getTypeClass()) return false;
1261 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1262 if (TyClass == Type::Pointer) {
1263 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1264 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1265 } else if (TyClass == Type::BlockPointer) {
1266 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1267 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1268 } else if (TyClass == Type::MemberPointer) {
1269 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1270 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1271 } else {
1272 return false;
1273 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001274
John McCall991eb4b2010-12-21 00:44:39 +00001275 TyClass = CanTo->getTypeClass();
1276 if (TyClass != CanFrom->getTypeClass()) return false;
1277 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1278 return false;
1279 }
1280
1281 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1282 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1283 if (!EInfo.getNoReturn()) return false;
1284
1285 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1286 assert(QualType(FromFn, 0).isCanonical());
1287 if (QualType(FromFn, 0) != CanTo) return false;
1288
1289 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001290 return true;
1291}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001292
Douglas Gregor46188682010-05-18 22:42:18 +00001293/// \brief Determine whether the conversion from FromType to ToType is a valid
1294/// vector conversion.
1295///
1296/// \param ICK Will be set to the vector conversion kind, if this is a vector
1297/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001298static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1299 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001300 // We need at least one of these types to be a vector type to have a vector
1301 // conversion.
1302 if (!ToType->isVectorType() && !FromType->isVectorType())
1303 return false;
1304
1305 // Identical types require no conversions.
1306 if (Context.hasSameUnqualifiedType(FromType, ToType))
1307 return false;
1308
1309 // There are no conversions between extended vector types, only identity.
1310 if (ToType->isExtVectorType()) {
1311 // There are no conversions between extended vector types other than the
1312 // identity conversion.
1313 if (FromType->isExtVectorType())
1314 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001315
Douglas Gregor46188682010-05-18 22:42:18 +00001316 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001317 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001318 ICK = ICK_Vector_Splat;
1319 return true;
1320 }
1321 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001322
1323 // We can perform the conversion between vector types in the following cases:
1324 // 1)vector types are equivalent AltiVec and GCC vector types
1325 // 2)lax vector conversions are permitted and the vector types are of the
1326 // same size
1327 if (ToType->isVectorType() && FromType->isVectorType()) {
1328 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001329 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruth9c524c12010-08-08 05:02:51 +00001330 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001331 ICK = ICK_Vector_Conversion;
1332 return true;
1333 }
Douglas Gregor46188682010-05-18 22:42:18 +00001334 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001335
Douglas Gregor46188682010-05-18 22:42:18 +00001336 return false;
1337}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001338
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001339static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1340 bool InOverloadResolution,
1341 StandardConversionSequence &SCS,
1342 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001343
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001344/// IsStandardConversion - Determines whether there is a standard
1345/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1346/// expression From to the type ToType. Standard conversion sequences
1347/// only consider non-class types; for conversions that involve class
1348/// types, use TryImplicitConversion. If a conversion exists, SCS will
1349/// contain the standard conversion sequence required to perform this
1350/// conversion and this routine will return true. Otherwise, this
1351/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001352static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1353 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001354 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001355 bool CStyle,
1356 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001357 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001358
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001359 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001360 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001361 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001362 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001363 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001364 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001365
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001366 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001367 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001368 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001369 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001370 return false;
1371
Mike Stump11289f42009-09-09 15:08:12 +00001372 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001373 }
1374
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001375 // The first conversion can be an lvalue-to-rvalue conversion,
1376 // array-to-pointer conversion, or function-to-pointer conversion
1377 // (C++ 4p1).
1378
John McCall5c32be02010-08-24 20:38:10 +00001379 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001380 DeclAccessPair AccessPair;
1381 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001382 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001383 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001384 // We were able to resolve the address of the overloaded function,
1385 // so we can convert to the type of that function.
1386 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001387
1388 // we can sometimes resolve &foo<int> regardless of ToType, so check
1389 // if the type matches (identity) or we are converting to bool
1390 if (!S.Context.hasSameUnqualifiedType(
1391 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1392 QualType resultTy;
1393 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001394 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001395 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1396 // otherwise, only a boolean conversion is standard
1397 if (!ToType->isBooleanType())
1398 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001399 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001400
Chandler Carruthffce2452011-03-29 08:08:18 +00001401 // Check if the "from" expression is taking the address of an overloaded
1402 // function and recompute the FromType accordingly. Take advantage of the
1403 // fact that non-static member functions *must* have such an address-of
1404 // expression.
1405 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1406 if (Method && !Method->isStatic()) {
1407 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1408 "Non-unary operator on non-static member address");
1409 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1410 == UO_AddrOf &&
1411 "Non-address-of operator on non-static member address");
1412 const Type *ClassType
1413 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1414 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001415 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1416 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1417 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001418 "Non-address-of operator for overloaded function expression");
1419 FromType = S.Context.getPointerType(FromType);
1420 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001421
Douglas Gregor980fb162010-04-29 18:24:40 +00001422 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001423 assert(S.Context.hasSameType(
1424 FromType,
1425 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001426 } else {
1427 return false;
1428 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001429 }
John McCall154a2fd2011-08-30 00:57:29 +00001430 // Lvalue-to-rvalue conversion (C++11 4.1):
1431 // A glvalue (3.10) of a non-function, non-array type T can
1432 // be converted to a prvalue.
1433 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001434 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001435 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001436 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001437 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001438
Douglas Gregorc79862f2012-04-12 17:51:55 +00001439 // C11 6.3.2.1p2:
1440 // ... if the lvalue has atomic type, the value has the non-atomic version
1441 // of the type of the lvalue ...
1442 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1443 FromType = Atomic->getValueType();
1444
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001445 // If T is a non-class type, the type of the rvalue is the
1446 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001447 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1448 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001449 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001450 } else if (FromType->isArrayType()) {
1451 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001452 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001453
1454 // An lvalue or rvalue of type "array of N T" or "array of unknown
1455 // bound of T" can be converted to an rvalue of type "pointer to
1456 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001457 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001458
John McCall5c32be02010-08-24 20:38:10 +00001459 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001460 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001461 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001462
1463 // For the purpose of ranking in overload resolution
1464 // (13.3.3.1.1), this conversion is considered an
1465 // array-to-pointer conversion followed by a qualification
1466 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001467 SCS.Second = ICK_Identity;
1468 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001469 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001470 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001471 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001472 }
John McCall086a4642010-11-24 05:12:34 +00001473 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001474 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001475 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001476
1477 // An lvalue of function type T can be converted to an rvalue of
1478 // type "pointer to T." The result is a pointer to the
1479 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001480 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001481 } else {
1482 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001483 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001484 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001485 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001486
1487 // The second conversion can be an integral promotion, floating
1488 // point promotion, integral conversion, floating point conversion,
1489 // floating-integral conversion, pointer conversion,
1490 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001491 // For overloading in C, this can also be a "compatible-type"
1492 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001493 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001494 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001495 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001496 // The unqualified versions of the types are the same: there's no
1497 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001498 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001499 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001500 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001501 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001502 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001503 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001504 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001505 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001506 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001507 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001508 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001509 SCS.Second = ICK_Complex_Promotion;
1510 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001511 } else if (ToType->isBooleanType() &&
1512 (FromType->isArithmeticType() ||
1513 FromType->isAnyPointerType() ||
1514 FromType->isBlockPointerType() ||
1515 FromType->isMemberPointerType() ||
1516 FromType->isNullPtrType())) {
1517 // Boolean conversions (C++ 4.12).
1518 SCS.Second = ICK_Boolean_Conversion;
1519 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001520 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001521 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001522 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001523 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001524 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001525 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001526 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001527 SCS.Second = ICK_Complex_Conversion;
1528 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001529 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1530 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001531 // Complex-real conversions (C99 6.3.1.7)
1532 SCS.Second = ICK_Complex_Real;
1533 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001534 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001535 // Floating point conversions (C++ 4.8).
1536 SCS.Second = ICK_Floating_Conversion;
1537 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001538 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001539 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001540 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001541 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001542 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001543 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001544 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001545 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001546 SCS.Second = ICK_Block_Pointer_Conversion;
1547 } else if (AllowObjCWritebackConversion &&
1548 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1549 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001550 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1551 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001552 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001553 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001554 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001555 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001556 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001557 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001558 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001559 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001560 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001561 SCS.Second = SecondICK;
1562 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001563 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001564 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001565 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001566 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001567 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001568 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001569 // Treat a conversion that strips "noreturn" as an identity conversion.
1570 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001571 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1572 InOverloadResolution,
1573 SCS, CStyle)) {
1574 SCS.Second = ICK_TransparentUnionConversion;
1575 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001576 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1577 CStyle)) {
1578 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001579 // appropriately.
1580 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001581 } else {
1582 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001583 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001584 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001585 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001586
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001587 QualType CanonFrom;
1588 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001589 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001590 bool ObjCLifetimeConversion;
1591 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1592 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001593 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001594 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001595 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001596 CanonFrom = S.Context.getCanonicalType(FromType);
1597 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001598 } else {
1599 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001600 SCS.Third = ICK_Identity;
1601
Mike Stump11289f42009-09-09 15:08:12 +00001602 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001603 // [...] Any difference in top-level cv-qualification is
1604 // subsumed by the initialization itself and does not constitute
1605 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001606 CanonFrom = S.Context.getCanonicalType(FromType);
1607 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001608 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001609 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001610 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001611 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1612 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001613 FromType = ToType;
1614 CanonFrom = CanonTo;
1615 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001616 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001617 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001618
1619 // If we have not converted the argument type to the parameter type,
1620 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001621 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001622 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001623
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001624 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001625}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001626
1627static bool
1628IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1629 QualType &ToType,
1630 bool InOverloadResolution,
1631 StandardConversionSequence &SCS,
1632 bool CStyle) {
1633
1634 const RecordType *UT = ToType->getAsUnionType();
1635 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1636 return false;
1637 // The field to initialize within the transparent union.
1638 RecordDecl *UD = UT->getDecl();
1639 // It's compatible if the expression matches any of the fields.
1640 for (RecordDecl::field_iterator it = UD->field_begin(),
1641 itend = UD->field_end();
1642 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001643 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1644 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001645 ToType = it->getType();
1646 return true;
1647 }
1648 }
1649 return false;
1650}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001651
1652/// IsIntegralPromotion - Determines whether the conversion from the
1653/// expression From (whose potentially-adjusted type is FromType) to
1654/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1655/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001656bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001657 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001658 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001659 if (!To) {
1660 return false;
1661 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001662
1663 // An rvalue of type char, signed char, unsigned char, short int, or
1664 // unsigned short int can be converted to an rvalue of type int if
1665 // int can represent all the values of the source type; otherwise,
1666 // the source rvalue can be converted to an rvalue of type unsigned
1667 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001668 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1669 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001670 if (// We can promote any signed, promotable integer type to an int
1671 (FromType->isSignedIntegerType() ||
1672 // We can promote any unsigned integer type whose size is
1673 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001674 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001675 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001676 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001677 }
1678
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001679 return To->getKind() == BuiltinType::UInt;
1680 }
1681
Richard Smithb9c5a602012-09-13 21:18:54 +00001682 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001683 // A prvalue of an unscoped enumeration type whose underlying type is not
1684 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1685 // following types that can represent all the values of the enumeration
1686 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1687 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001688 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001689 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001690 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001691 // with lowest integer conversion rank (4.13) greater than the rank of long
1692 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001693 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001694 // C++11 [conv.prom]p4:
1695 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1696 // can be converted to a prvalue of its underlying type. Moreover, if
1697 // integral promotion can be applied to its underlying type, a prvalue of an
1698 // unscoped enumeration type whose underlying type is fixed can also be
1699 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001700 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1701 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1702 // provided for a scoped enumeration.
1703 if (FromEnumType->getDecl()->isScoped())
1704 return false;
1705
Richard Smithb9c5a602012-09-13 21:18:54 +00001706 // We can perform an integral promotion to the underlying type of the enum,
1707 // even if that's not the promoted type.
1708 if (FromEnumType->getDecl()->isFixed()) {
1709 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1710 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1711 IsIntegralPromotion(From, Underlying, ToType);
1712 }
1713
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001714 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001715 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001716 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001717 return Context.hasSameUnqualifiedType(ToType,
1718 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001719 }
John McCall56774992009-12-09 09:09:27 +00001720
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001721 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001722 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1723 // to an rvalue a prvalue of the first of the following types that can
1724 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001725 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001726 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001727 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001728 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001729 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001730 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001731 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001732 // Determine whether the type we're converting from is signed or
1733 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001734 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001735 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001736
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001737 // The types we'll try to promote to, in the appropriate
1738 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001739 QualType PromoteTypes[6] = {
1740 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001741 Context.LongTy, Context.UnsignedLongTy ,
1742 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001743 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001744 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001745 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1746 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001747 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001748 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1749 // We found the type that we can promote to. If this is the
1750 // type we wanted, we have a promotion. Otherwise, no
1751 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001752 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001753 }
1754 }
1755 }
1756
1757 // An rvalue for an integral bit-field (9.6) can be converted to an
1758 // rvalue of type int if int can represent all the values of the
1759 // bit-field; otherwise, it can be converted to unsigned int if
1760 // unsigned int can represent all the values of the bit-field. If
1761 // the bit-field is larger yet, no integral promotion applies to
1762 // it. If the bit-field has an enumerated type, it is treated as any
1763 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001764 // FIXME: We should delay checking of bit-fields until we actually perform the
1765 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001766 using llvm::APSInt;
1767 if (From)
1768 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001769 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001770 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001771 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1772 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1773 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001774
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001775 // Are we promoting to an int from a bitfield that fits in an int?
1776 if (BitWidth < ToSize ||
1777 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1778 return To->getKind() == BuiltinType::Int;
1779 }
Mike Stump11289f42009-09-09 15:08:12 +00001780
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001781 // Are we promoting to an unsigned int from an unsigned bitfield
1782 // that fits into an unsigned int?
1783 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1784 return To->getKind() == BuiltinType::UInt;
1785 }
Mike Stump11289f42009-09-09 15:08:12 +00001786
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001787 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001788 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001789 }
Mike Stump11289f42009-09-09 15:08:12 +00001790
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001791 // An rvalue of type bool can be converted to an rvalue of type int,
1792 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001793 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001794 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001795 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001796
1797 return false;
1798}
1799
1800/// IsFloatingPointPromotion - Determines whether the conversion from
1801/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1802/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001803bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001804 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1805 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001806 /// An rvalue of type float can be converted to an rvalue of type
1807 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001808 if (FromBuiltin->getKind() == BuiltinType::Float &&
1809 ToBuiltin->getKind() == BuiltinType::Double)
1810 return true;
1811
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001812 // C99 6.3.1.5p1:
1813 // When a float is promoted to double or long double, or a
1814 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001815 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001816 (FromBuiltin->getKind() == BuiltinType::Float ||
1817 FromBuiltin->getKind() == BuiltinType::Double) &&
1818 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1819 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001820
1821 // Half can be promoted to float.
1822 if (FromBuiltin->getKind() == BuiltinType::Half &&
1823 ToBuiltin->getKind() == BuiltinType::Float)
1824 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001825 }
1826
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001827 return false;
1828}
1829
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001830/// \brief Determine if a conversion is a complex promotion.
1831///
1832/// A complex promotion is defined as a complex -> complex conversion
1833/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001834/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001835bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001836 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001837 if (!FromComplex)
1838 return false;
1839
John McCall9dd450b2009-09-21 23:43:11 +00001840 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001841 if (!ToComplex)
1842 return false;
1843
1844 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001845 ToComplex->getElementType()) ||
1846 IsIntegralPromotion(0, FromComplex->getElementType(),
1847 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001848}
1849
Douglas Gregor237f96c2008-11-26 23:31:11 +00001850/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1851/// the pointer type FromPtr to a pointer to type ToPointee, with the
1852/// same type qualifiers as FromPtr has on its pointee type. ToType,
1853/// if non-empty, will be a pointer to ToType that may or may not have
1854/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001855///
Mike Stump11289f42009-09-09 15:08:12 +00001856static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001857BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001858 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001859 ASTContext &Context,
1860 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001861 assert((FromPtr->getTypeClass() == Type::Pointer ||
1862 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1863 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001864
John McCall31168b02011-06-15 23:02:42 +00001865 /// Conversions to 'id' subsume cv-qualifier conversions.
1866 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001867 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001868
1869 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001870 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001871 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001872 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001873
John McCall31168b02011-06-15 23:02:42 +00001874 if (StripObjCLifetime)
1875 Quals.removeObjCLifetime();
1876
Mike Stump11289f42009-09-09 15:08:12 +00001877 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001878 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001879 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001880 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001881 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001882
1883 // Build a pointer to ToPointee. It has the right qualifiers
1884 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001885 if (isa<ObjCObjectPointerType>(ToType))
1886 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001887 return Context.getPointerType(ToPointee);
1888 }
1889
1890 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001891 QualType QualifiedCanonToPointee
1892 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001893
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001894 if (isa<ObjCObjectPointerType>(ToType))
1895 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1896 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001897}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001898
Mike Stump11289f42009-09-09 15:08:12 +00001899static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001900 bool InOverloadResolution,
1901 ASTContext &Context) {
1902 // Handle value-dependent integral null pointer constants correctly.
1903 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1904 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001905 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001906 return !InOverloadResolution;
1907
Douglas Gregor56751b52009-09-25 04:25:58 +00001908 return Expr->isNullPointerConstant(Context,
1909 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1910 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001911}
Mike Stump11289f42009-09-09 15:08:12 +00001912
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001913/// IsPointerConversion - Determines whether the conversion of the
1914/// expression From, which has the (possibly adjusted) type FromType,
1915/// can be converted to the type ToType via a pointer conversion (C++
1916/// 4.10). If so, returns true and places the converted type (that
1917/// might differ from ToType in its cv-qualifiers at some level) into
1918/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001919///
Douglas Gregora29dc052008-11-27 01:19:21 +00001920/// This routine also supports conversions to and from block pointers
1921/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1922/// pointers to interfaces. FIXME: Once we've determined the
1923/// appropriate overloading rules for Objective-C, we may want to
1924/// split the Objective-C checks into a different routine; however,
1925/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001926/// conversions, so for now they live here. IncompatibleObjC will be
1927/// set if the conversion is an allowed Objective-C conversion that
1928/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001929bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001930 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001931 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001932 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001933 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001934 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1935 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001936 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001937
Mike Stump11289f42009-09-09 15:08:12 +00001938 // Conversion from a null pointer constant to any Objective-C pointer type.
1939 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001940 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001941 ConvertedType = ToType;
1942 return true;
1943 }
1944
Douglas Gregor231d1c62008-11-27 00:15:41 +00001945 // Blocks: Block pointers can be converted to void*.
1946 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001947 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001948 ConvertedType = ToType;
1949 return true;
1950 }
1951 // Blocks: A null pointer constant can be converted to a block
1952 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001953 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001954 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001955 ConvertedType = ToType;
1956 return true;
1957 }
1958
Sebastian Redl576fd422009-05-10 18:38:11 +00001959 // If the left-hand-side is nullptr_t, the right side can be a null
1960 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001961 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001962 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001963 ConvertedType = ToType;
1964 return true;
1965 }
1966
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001967 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001968 if (!ToTypePtr)
1969 return false;
1970
1971 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001972 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001973 ConvertedType = ToType;
1974 return true;
1975 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001976
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001977 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001978 // , including objective-c pointers.
1979 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001980 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001981 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001982 ConvertedType = BuildSimilarlyQualifiedPointerType(
1983 FromType->getAs<ObjCObjectPointerType>(),
1984 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001985 ToType, Context);
1986 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001987 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001988 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001989 if (!FromTypePtr)
1990 return false;
1991
1992 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001993
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001994 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001995 // pointer conversion, so don't do all of the work below.
1996 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1997 return false;
1998
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001999 // An rvalue of type "pointer to cv T," where T is an object type,
2000 // can be converted to an rvalue of type "pointer to cv void" (C++
2001 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002002 if (FromPointeeType->isIncompleteOrObjectType() &&
2003 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002004 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002005 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002006 ToType, Context,
2007 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002008 return true;
2009 }
2010
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002011 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002012 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002013 ToPointeeType->isVoidType()) {
2014 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2015 ToPointeeType,
2016 ToType, Context);
2017 return true;
2018 }
2019
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002020 // When we're overloading in C, we allow a special kind of pointer
2021 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002022 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002023 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002024 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002025 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002026 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002027 return true;
2028 }
2029
Douglas Gregor5c407d92008-10-23 00:40:37 +00002030 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002031 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002032 // An rvalue of type "pointer to cv D," where D is a class type,
2033 // can be converted to an rvalue of type "pointer to cv B," where
2034 // B is a base class (clause 10) of D. If B is an inaccessible
2035 // (clause 11) or ambiguous (10.2) base class of D, a program that
2036 // necessitates this conversion is ill-formed. The result of the
2037 // conversion is a pointer to the base class sub-object of the
2038 // derived class object. The null pointer value is converted to
2039 // the null pointer value of the destination type.
2040 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002041 // Note that we do not check for ambiguity or inaccessibility
2042 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002043 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002044 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002045 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002046 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002047 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002048 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002049 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002050 ToType, Context);
2051 return true;
2052 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002053
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002054 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2055 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2056 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2057 ToPointeeType,
2058 ToType, Context);
2059 return true;
2060 }
2061
Douglas Gregora119f102008-12-19 19:13:09 +00002062 return false;
2063}
Douglas Gregoraec25842011-04-26 23:16:46 +00002064
2065/// \brief Adopt the given qualifiers for the given type.
2066static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2067 Qualifiers TQs = T.getQualifiers();
2068
2069 // Check whether qualifiers already match.
2070 if (TQs == Qs)
2071 return T;
2072
2073 if (Qs.compatiblyIncludes(TQs))
2074 return Context.getQualifiedType(T, Qs);
2075
2076 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2077}
Douglas Gregora119f102008-12-19 19:13:09 +00002078
2079/// isObjCPointerConversion - Determines whether this is an
2080/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2081/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002082bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002083 QualType& ConvertedType,
2084 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002085 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002086 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002087
Douglas Gregoraec25842011-04-26 23:16:46 +00002088 // The set of qualifiers on the type we're converting from.
2089 Qualifiers FromQualifiers = FromType.getQualifiers();
2090
Steve Naroff7cae42b2009-07-10 23:34:53 +00002091 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002092 const ObjCObjectPointerType* ToObjCPtr =
2093 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002094 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002095 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002096
Steve Naroff7cae42b2009-07-10 23:34:53 +00002097 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002098 // If the pointee types are the same (ignoring qualifications),
2099 // then this is not a pointer conversion.
2100 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2101 FromObjCPtr->getPointeeType()))
2102 return false;
2103
Douglas Gregoraec25842011-04-26 23:16:46 +00002104 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002105 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002106 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002107 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002108 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002109 return true;
2110 }
2111 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002112 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002113 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002114 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002115 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002116 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002117 return true;
2118 }
2119 // Objective C++: We're able to convert from a pointer to an
2120 // interface to a pointer to a different interface.
2121 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002122 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2123 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002124 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002125 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2126 FromObjCPtr->getPointeeType()))
2127 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002128 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002129 ToObjCPtr->getPointeeType(),
2130 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002131 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002132 return true;
2133 }
2134
2135 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2136 // Okay: this is some kind of implicit downcast of Objective-C
2137 // interfaces, which is permitted. However, we're going to
2138 // complain about it.
2139 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002140 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002141 ToObjCPtr->getPointeeType(),
2142 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002143 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002144 return true;
2145 }
Mike Stump11289f42009-09-09 15:08:12 +00002146 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002147 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002148 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002149 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002150 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002151 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002152 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002153 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002154 // to a block pointer type.
2155 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002156 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002157 return true;
2158 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002159 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002160 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002161 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002162 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002163 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002164 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002165 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002166 return true;
2167 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002168 else
Douglas Gregora119f102008-12-19 19:13:09 +00002169 return false;
2170
Douglas Gregor033f56d2008-12-23 00:53:59 +00002171 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002172 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002173 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002174 else if (const BlockPointerType *FromBlockPtr =
2175 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002176 FromPointeeType = FromBlockPtr->getPointeeType();
2177 else
Douglas Gregora119f102008-12-19 19:13:09 +00002178 return false;
2179
Douglas Gregora119f102008-12-19 19:13:09 +00002180 // If we have pointers to pointers, recursively check whether this
2181 // is an Objective-C conversion.
2182 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2183 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2184 IncompatibleObjC)) {
2185 // We always complain about this conversion.
2186 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002187 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002188 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002189 return true;
2190 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002191 // Allow conversion of pointee being objective-c pointer to another one;
2192 // as in I* to id.
2193 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2194 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2195 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2196 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002197
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002198 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002199 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002200 return true;
2201 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002202
Douglas Gregor033f56d2008-12-23 00:53:59 +00002203 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002204 // differences in the argument and result types are in Objective-C
2205 // pointer conversions. If so, we permit the conversion (but
2206 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002207 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002208 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002209 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002210 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002211 if (FromFunctionType && ToFunctionType) {
2212 // If the function types are exactly the same, this isn't an
2213 // Objective-C pointer conversion.
2214 if (Context.getCanonicalType(FromPointeeType)
2215 == Context.getCanonicalType(ToPointeeType))
2216 return false;
2217
2218 // Perform the quick checks that will tell us whether these
2219 // function types are obviously different.
2220 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2221 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2222 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2223 return false;
2224
2225 bool HasObjCConversion = false;
2226 if (Context.getCanonicalType(FromFunctionType->getResultType())
2227 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2228 // Okay, the types match exactly. Nothing to do.
2229 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2230 ToFunctionType->getResultType(),
2231 ConvertedType, IncompatibleObjC)) {
2232 // Okay, we have an Objective-C pointer conversion.
2233 HasObjCConversion = true;
2234 } else {
2235 // Function types are too different. Abort.
2236 return false;
2237 }
Mike Stump11289f42009-09-09 15:08:12 +00002238
Douglas Gregora119f102008-12-19 19:13:09 +00002239 // Check argument types.
2240 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2241 ArgIdx != NumArgs; ++ArgIdx) {
2242 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2243 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2244 if (Context.getCanonicalType(FromArgType)
2245 == Context.getCanonicalType(ToArgType)) {
2246 // Okay, the types match exactly. Nothing to do.
2247 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2248 ConvertedType, IncompatibleObjC)) {
2249 // Okay, we have an Objective-C pointer conversion.
2250 HasObjCConversion = true;
2251 } else {
2252 // Argument types are too different. Abort.
2253 return false;
2254 }
2255 }
2256
2257 if (HasObjCConversion) {
2258 // We had an Objective-C conversion. Allow this pointer
2259 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002260 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002261 IncompatibleObjC = true;
2262 return true;
2263 }
2264 }
2265
Sebastian Redl72b597d2009-01-25 19:43:20 +00002266 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002267}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002268
John McCall31168b02011-06-15 23:02:42 +00002269/// \brief Determine whether this is an Objective-C writeback conversion,
2270/// used for parameter passing when performing automatic reference counting.
2271///
2272/// \param FromType The type we're converting form.
2273///
2274/// \param ToType The type we're converting to.
2275///
2276/// \param ConvertedType The type that will be produced after applying
2277/// this conversion.
2278bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2279 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002280 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002281 Context.hasSameUnqualifiedType(FromType, ToType))
2282 return false;
2283
2284 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2285 QualType ToPointee;
2286 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2287 ToPointee = ToPointer->getPointeeType();
2288 else
2289 return false;
2290
2291 Qualifiers ToQuals = ToPointee.getQualifiers();
2292 if (!ToPointee->isObjCLifetimeType() ||
2293 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002294 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002295 return false;
2296
2297 // Argument must be a pointer to __strong to __weak.
2298 QualType FromPointee;
2299 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2300 FromPointee = FromPointer->getPointeeType();
2301 else
2302 return false;
2303
2304 Qualifiers FromQuals = FromPointee.getQualifiers();
2305 if (!FromPointee->isObjCLifetimeType() ||
2306 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2307 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2308 return false;
2309
2310 // Make sure that we have compatible qualifiers.
2311 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2312 if (!ToQuals.compatiblyIncludes(FromQuals))
2313 return false;
2314
2315 // Remove qualifiers from the pointee type we're converting from; they
2316 // aren't used in the compatibility check belong, and we'll be adding back
2317 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2318 FromPointee = FromPointee.getUnqualifiedType();
2319
2320 // The unqualified form of the pointee types must be compatible.
2321 ToPointee = ToPointee.getUnqualifiedType();
2322 bool IncompatibleObjC;
2323 if (Context.typesAreCompatible(FromPointee, ToPointee))
2324 FromPointee = ToPointee;
2325 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2326 IncompatibleObjC))
2327 return false;
2328
2329 /// \brief Construct the type we're converting to, which is a pointer to
2330 /// __autoreleasing pointee.
2331 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2332 ConvertedType = Context.getPointerType(FromPointee);
2333 return true;
2334}
2335
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002336bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2337 QualType& ConvertedType) {
2338 QualType ToPointeeType;
2339 if (const BlockPointerType *ToBlockPtr =
2340 ToType->getAs<BlockPointerType>())
2341 ToPointeeType = ToBlockPtr->getPointeeType();
2342 else
2343 return false;
2344
2345 QualType FromPointeeType;
2346 if (const BlockPointerType *FromBlockPtr =
2347 FromType->getAs<BlockPointerType>())
2348 FromPointeeType = FromBlockPtr->getPointeeType();
2349 else
2350 return false;
2351 // We have pointer to blocks, check whether the only
2352 // differences in the argument and result types are in Objective-C
2353 // pointer conversions. If so, we permit the conversion.
2354
2355 const FunctionProtoType *FromFunctionType
2356 = FromPointeeType->getAs<FunctionProtoType>();
2357 const FunctionProtoType *ToFunctionType
2358 = ToPointeeType->getAs<FunctionProtoType>();
2359
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002360 if (!FromFunctionType || !ToFunctionType)
2361 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002362
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002363 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002364 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002365
2366 // Perform the quick checks that will tell us whether these
2367 // function types are obviously different.
2368 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2369 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2370 return false;
2371
2372 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2373 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2374 if (FromEInfo != ToEInfo)
2375 return false;
2376
2377 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002378 if (Context.hasSameType(FromFunctionType->getResultType(),
2379 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002380 // Okay, the types match exactly. Nothing to do.
2381 } else {
2382 QualType RHS = FromFunctionType->getResultType();
2383 QualType LHS = ToFunctionType->getResultType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002384 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002385 !RHS.hasQualifiers() && LHS.hasQualifiers())
2386 LHS = LHS.getUnqualifiedType();
2387
2388 if (Context.hasSameType(RHS,LHS)) {
2389 // OK exact match.
2390 } else if (isObjCPointerConversion(RHS, LHS,
2391 ConvertedType, IncompatibleObjC)) {
2392 if (IncompatibleObjC)
2393 return false;
2394 // Okay, we have an Objective-C pointer conversion.
2395 }
2396 else
2397 return false;
2398 }
2399
2400 // Check argument types.
2401 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2402 ArgIdx != NumArgs; ++ArgIdx) {
2403 IncompatibleObjC = false;
2404 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2405 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2406 if (Context.hasSameType(FromArgType, ToArgType)) {
2407 // Okay, the types match exactly. Nothing to do.
2408 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2409 ConvertedType, IncompatibleObjC)) {
2410 if (IncompatibleObjC)
2411 return false;
2412 // Okay, we have an Objective-C pointer conversion.
2413 } else
2414 // Argument types are too different. Abort.
2415 return false;
2416 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002417 if (LangOpts.ObjCAutoRefCount &&
2418 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2419 ToFunctionType))
2420 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002421
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002422 ConvertedType = ToType;
2423 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002424}
2425
Richard Trieucaff2472011-11-23 22:32:32 +00002426enum {
2427 ft_default,
2428 ft_different_class,
2429 ft_parameter_arity,
2430 ft_parameter_mismatch,
2431 ft_return_type,
2432 ft_qualifer_mismatch
2433};
2434
2435/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2436/// function types. Catches different number of parameter, mismatch in
2437/// parameter types, and different return types.
2438void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2439 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002440 // If either type is not valid, include no extra info.
2441 if (FromType.isNull() || ToType.isNull()) {
2442 PDiag << ft_default;
2443 return;
2444 }
2445
Richard Trieucaff2472011-11-23 22:32:32 +00002446 // Get the function type from the pointers.
2447 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2448 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2449 *ToMember = ToType->getAs<MemberPointerType>();
2450 if (FromMember->getClass() != ToMember->getClass()) {
2451 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2452 << QualType(FromMember->getClass(), 0);
2453 return;
2454 }
2455 FromType = FromMember->getPointeeType();
2456 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002457 }
2458
Richard Trieu96ed5b62011-12-13 23:19:45 +00002459 if (FromType->isPointerType())
2460 FromType = FromType->getPointeeType();
2461 if (ToType->isPointerType())
2462 ToType = ToType->getPointeeType();
2463
2464 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002465 FromType = FromType.getNonReferenceType();
2466 ToType = ToType.getNonReferenceType();
2467
Richard Trieucaff2472011-11-23 22:32:32 +00002468 // Don't print extra info for non-specialized template functions.
2469 if (FromType->isInstantiationDependentType() &&
2470 !FromType->getAs<TemplateSpecializationType>()) {
2471 PDiag << ft_default;
2472 return;
2473 }
2474
Richard Trieu96ed5b62011-12-13 23:19:45 +00002475 // No extra info for same types.
2476 if (Context.hasSameType(FromType, ToType)) {
2477 PDiag << ft_default;
2478 return;
2479 }
2480
Richard Trieucaff2472011-11-23 22:32:32 +00002481 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2482 *ToFunction = ToType->getAs<FunctionProtoType>();
2483
2484 // Both types need to be function types.
2485 if (!FromFunction || !ToFunction) {
2486 PDiag << ft_default;
2487 return;
2488 }
2489
2490 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2491 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2492 << FromFunction->getNumArgs();
2493 return;
2494 }
2495
2496 // Handle different parameter types.
2497 unsigned ArgPos;
2498 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2499 PDiag << ft_parameter_mismatch << ArgPos + 1
2500 << ToFunction->getArgType(ArgPos)
2501 << FromFunction->getArgType(ArgPos);
2502 return;
2503 }
2504
2505 // Handle different return type.
2506 if (!Context.hasSameType(FromFunction->getResultType(),
2507 ToFunction->getResultType())) {
2508 PDiag << ft_return_type << ToFunction->getResultType()
2509 << FromFunction->getResultType();
2510 return;
2511 }
2512
2513 unsigned FromQuals = FromFunction->getTypeQuals(),
2514 ToQuals = ToFunction->getTypeQuals();
2515 if (FromQuals != ToQuals) {
2516 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2517 return;
2518 }
2519
2520 // Unable to find a difference, so add no extra info.
2521 PDiag << ft_default;
2522}
2523
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002524/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002525/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002526/// they have same number of arguments. This routine assumes that Objective-C
2527/// pointer types which only differ in their protocol qualifiers are equal.
Sylvestre Ledru830885c2012-07-23 08:59:39 +00002528/// If the parameters are different, ArgPos will have the parameter index
Richard Trieucaff2472011-11-23 22:32:32 +00002529/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002530bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002531 const FunctionProtoType *NewType,
2532 unsigned *ArgPos) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002533 if (!getLangOpts().ObjC1) {
Richard Trieucaff2472011-11-23 22:32:32 +00002534 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2535 N = NewType->arg_type_begin(),
2536 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2537 if (!Context.hasSameType(*O, *N)) {
2538 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2539 return false;
2540 }
2541 }
2542 return true;
2543 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002544
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002545 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2546 N = NewType->arg_type_begin(),
2547 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2548 QualType ToType = (*O);
2549 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002550 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002551 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2552 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002553 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2554 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2555 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2556 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002557 continue;
2558 }
John McCall8b07ec22010-05-15 11:32:37 +00002559 else if (const ObjCObjectPointerType *PTTo =
2560 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002561 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002562 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002563 if (Context.hasSameUnqualifiedType(
2564 PTTo->getObjectType()->getBaseType(),
2565 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002566 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002567 }
Richard Trieucaff2472011-11-23 22:32:32 +00002568 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002569 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002570 }
2571 }
2572 return true;
2573}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002574
Douglas Gregor39c16d42008-10-24 04:54:22 +00002575/// CheckPointerConversion - Check the pointer conversion from the
2576/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002577/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002578/// conversions for which IsPointerConversion has already returned
2579/// true. It returns true and produces a diagnostic if there was an
2580/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002581bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002582 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002583 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002584 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002585 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002586 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002587
John McCall8cb679e2010-11-15 09:13:47 +00002588 Kind = CK_BitCast;
2589
David Blaikie1c7c8f72012-08-08 17:33:31 +00002590 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2591 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2592 Expr::NPCK_ZeroExpression) {
2593 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2594 DiagRuntimeBehavior(From->getExprLoc(), From,
2595 PDiag(diag::warn_impcast_bool_to_null_pointer)
2596 << ToType << From->getSourceRange());
2597 else if (!isUnevaluatedContext())
2598 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2599 << ToType << From->getSourceRange();
2600 }
John McCall9320b872011-09-09 05:25:32 +00002601 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2602 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002603 QualType FromPointeeType = FromPtrType->getPointeeType(),
2604 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002605
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002606 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2607 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002608 // We must have a derived-to-base conversion. Check an
2609 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002610 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2611 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002612 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002613 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002614 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002615
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002616 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002617 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002618 }
2619 }
John McCall9320b872011-09-09 05:25:32 +00002620 } else if (const ObjCObjectPointerType *ToPtrType =
2621 ToType->getAs<ObjCObjectPointerType>()) {
2622 if (const ObjCObjectPointerType *FromPtrType =
2623 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002624 // Objective-C++ conversions are always okay.
2625 // FIXME: We should have a different class of conversions for the
2626 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002627 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002628 return false;
John McCall9320b872011-09-09 05:25:32 +00002629 } else if (FromType->isBlockPointerType()) {
2630 Kind = CK_BlockPointerToObjCPointerCast;
2631 } else {
2632 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002633 }
John McCall9320b872011-09-09 05:25:32 +00002634 } else if (ToType->isBlockPointerType()) {
2635 if (!FromType->isBlockPointerType())
2636 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002637 }
John McCall8cb679e2010-11-15 09:13:47 +00002638
2639 // We shouldn't fall into this case unless it's valid for other
2640 // reasons.
2641 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2642 Kind = CK_NullToPointer;
2643
Douglas Gregor39c16d42008-10-24 04:54:22 +00002644 return false;
2645}
2646
Sebastian Redl72b597d2009-01-25 19:43:20 +00002647/// IsMemberPointerConversion - Determines whether the conversion of the
2648/// expression From, which has the (possibly adjusted) type FromType, can be
2649/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2650/// If so, returns true and places the converted type (that might differ from
2651/// ToType in its cv-qualifiers at some level) into ConvertedType.
2652bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002653 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002654 bool InOverloadResolution,
2655 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002656 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002657 if (!ToTypePtr)
2658 return false;
2659
2660 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002661 if (From->isNullPointerConstant(Context,
2662 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2663 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002664 ConvertedType = ToType;
2665 return true;
2666 }
2667
2668 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002669 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002670 if (!FromTypePtr)
2671 return false;
2672
2673 // A pointer to member of B can be converted to a pointer to member of D,
2674 // where D is derived from B (C++ 4.11p2).
2675 QualType FromClass(FromTypePtr->getClass(), 0);
2676 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002677
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002678 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002679 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002680 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002681 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2682 ToClass.getTypePtr());
2683 return true;
2684 }
2685
2686 return false;
2687}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002688
Sebastian Redl72b597d2009-01-25 19:43:20 +00002689/// CheckMemberPointerConversion - Check the member pointer conversion from the
2690/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002691/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002692/// for which IsMemberPointerConversion has already returned true. It returns
2693/// true and produces a diagnostic if there was an error, or returns false
2694/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002695bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002696 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002697 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002698 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002699 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002700 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002701 if (!FromPtrType) {
2702 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002703 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002704 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002705 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002706 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002707 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002708 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002709
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002710 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002711 assert(ToPtrType && "No member pointer cast has a target type "
2712 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002713
Sebastian Redled8f2002009-01-28 18:33:18 +00002714 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2715 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002716
Sebastian Redled8f2002009-01-28 18:33:18 +00002717 // FIXME: What about dependent types?
2718 assert(FromClass->isRecordType() && "Pointer into non-class.");
2719 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002720
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002721 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002722 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002723 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2724 assert(DerivationOkay &&
2725 "Should not have been called if derivation isn't OK.");
2726 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002727
Sebastian Redled8f2002009-01-28 18:33:18 +00002728 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2729 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002730 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2731 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2732 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2733 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002734 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002735
Douglas Gregor89ee6822009-02-28 01:32:25 +00002736 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002737 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2738 << FromClass << ToClass << QualType(VBase, 0)
2739 << From->getSourceRange();
2740 return true;
2741 }
2742
John McCall5b0829a2010-02-10 09:31:12 +00002743 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002744 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2745 Paths.front(),
2746 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002747
Anders Carlssond7923c62009-08-22 23:33:40 +00002748 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002749 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002750 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002751 return false;
2752}
2753
Douglas Gregor9a657932008-10-21 23:43:52 +00002754/// IsQualificationConversion - Determines whether the conversion from
2755/// an rvalue of type FromType to ToType is a qualification conversion
2756/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002757///
2758/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2759/// when the qualification conversion involves a change in the Objective-C
2760/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002761bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002762Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002763 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002764 FromType = Context.getCanonicalType(FromType);
2765 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002766 ObjCLifetimeConversion = false;
2767
Douglas Gregor9a657932008-10-21 23:43:52 +00002768 // If FromType and ToType are the same type, this is not a
2769 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002770 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002771 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002772
Douglas Gregor9a657932008-10-21 23:43:52 +00002773 // (C++ 4.4p4):
2774 // A conversion can add cv-qualifiers at levels other than the first
2775 // in multi-level pointers, subject to the following rules: [...]
2776 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002777 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002778 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002779 // Within each iteration of the loop, we check the qualifiers to
2780 // determine if this still looks like a qualification
2781 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002782 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002783 // until there are no more pointers or pointers-to-members left to
2784 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002785 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002786
Douglas Gregor90609aa2011-04-25 18:40:17 +00002787 Qualifiers FromQuals = FromType.getQualifiers();
2788 Qualifiers ToQuals = ToType.getQualifiers();
2789
John McCall31168b02011-06-15 23:02:42 +00002790 // Objective-C ARC:
2791 // Check Objective-C lifetime conversions.
2792 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2793 UnwrappedAnyPointer) {
2794 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2795 ObjCLifetimeConversion = true;
2796 FromQuals.removeObjCLifetime();
2797 ToQuals.removeObjCLifetime();
2798 } else {
2799 // Qualification conversions cannot cast between different
2800 // Objective-C lifetime qualifiers.
2801 return false;
2802 }
2803 }
2804
Douglas Gregorf30053d2011-05-08 06:09:53 +00002805 // Allow addition/removal of GC attributes but not changing GC attributes.
2806 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2807 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2808 FromQuals.removeObjCGCAttr();
2809 ToQuals.removeObjCGCAttr();
2810 }
2811
Douglas Gregor9a657932008-10-21 23:43:52 +00002812 // -- for every j > 0, if const is in cv 1,j then const is in cv
2813 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002814 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002815 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002816
Douglas Gregor9a657932008-10-21 23:43:52 +00002817 // -- if the cv 1,j and cv 2,j are different, then const is in
2818 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002819 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002820 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002821 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002822
Douglas Gregor9a657932008-10-21 23:43:52 +00002823 // Keep track of whether all prior cv-qualifiers in the "to" type
2824 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002825 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002826 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002827 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002828
2829 // We are left with FromType and ToType being the pointee types
2830 // after unwrapping the original FromType and ToType the same number
2831 // of types. If we unwrapped any pointers, and if FromType and
2832 // ToType have the same unqualified type (since we checked
2833 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002834 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002835}
2836
Douglas Gregorc79862f2012-04-12 17:51:55 +00002837/// \brief - Determine whether this is a conversion from a scalar type to an
2838/// atomic type.
2839///
2840/// If successful, updates \c SCS's second and third steps in the conversion
2841/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002842static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2843 bool InOverloadResolution,
2844 StandardConversionSequence &SCS,
2845 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002846 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2847 if (!ToAtomic)
2848 return false;
2849
2850 StandardConversionSequence InnerSCS;
2851 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2852 InOverloadResolution, InnerSCS,
2853 CStyle, /*AllowObjCWritebackConversion=*/false))
2854 return false;
2855
2856 SCS.Second = InnerSCS.Second;
2857 SCS.setToType(1, InnerSCS.getToType(1));
2858 SCS.Third = InnerSCS.Third;
2859 SCS.QualificationIncludesObjCLifetime
2860 = InnerSCS.QualificationIncludesObjCLifetime;
2861 SCS.setToType(2, InnerSCS.getToType(2));
2862 return true;
2863}
2864
Sebastian Redle5417162012-03-27 18:33:03 +00002865static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2866 CXXConstructorDecl *Constructor,
2867 QualType Type) {
2868 const FunctionProtoType *CtorType =
2869 Constructor->getType()->getAs<FunctionProtoType>();
2870 if (CtorType->getNumArgs() > 0) {
2871 QualType FirstArg = CtorType->getArgType(0);
2872 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2873 return true;
2874 }
2875 return false;
2876}
2877
Sebastian Redl82ace982012-02-11 23:51:08 +00002878static OverloadingResult
2879IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2880 CXXRecordDecl *To,
2881 UserDefinedConversionSequence &User,
2882 OverloadCandidateSet &CandidateSet,
2883 bool AllowExplicit) {
2884 DeclContext::lookup_iterator Con, ConEnd;
2885 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2886 Con != ConEnd; ++Con) {
2887 NamedDecl *D = *Con;
2888 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2889
2890 // Find the constructor (which may be a template).
2891 CXXConstructorDecl *Constructor = 0;
2892 FunctionTemplateDecl *ConstructorTmpl
2893 = dyn_cast<FunctionTemplateDecl>(D);
2894 if (ConstructorTmpl)
2895 Constructor
2896 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2897 else
2898 Constructor = cast<CXXConstructorDecl>(D);
2899
2900 bool Usable = !Constructor->isInvalidDecl() &&
2901 S.isInitListConstructor(Constructor) &&
2902 (AllowExplicit || !Constructor->isExplicit());
2903 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002904 // If the first argument is (a reference to) the target type,
2905 // suppress conversions.
2906 bool SuppressUserConversions =
2907 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002908 if (ConstructorTmpl)
2909 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2910 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002911 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002912 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002913 else
2914 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002915 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002916 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002917 }
2918 }
2919
2920 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2921
2922 OverloadCandidateSet::iterator Best;
2923 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2924 case OR_Success: {
2925 // Record the standard conversion we used and the conversion function.
2926 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002927 QualType ThisType = Constructor->getThisType(S.Context);
2928 // Initializer lists don't have conversions as such.
2929 User.Before.setAsIdentityConversion();
2930 User.HadMultipleCandidates = HadMultipleCandidates;
2931 User.ConversionFunction = Constructor;
2932 User.FoundConversionFunction = Best->FoundDecl;
2933 User.After.setAsIdentityConversion();
2934 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2935 User.After.setAllToTypes(ToType);
2936 return OR_Success;
2937 }
2938
2939 case OR_No_Viable_Function:
2940 return OR_No_Viable_Function;
2941 case OR_Deleted:
2942 return OR_Deleted;
2943 case OR_Ambiguous:
2944 return OR_Ambiguous;
2945 }
2946
2947 llvm_unreachable("Invalid OverloadResult!");
2948}
2949
Douglas Gregor576e98c2009-01-30 23:27:23 +00002950/// Determines whether there is a user-defined conversion sequence
2951/// (C++ [over.ics.user]) that converts expression From to the type
2952/// ToType. If such a conversion exists, User will contain the
2953/// user-defined conversion sequence that performs such a conversion
2954/// and this routine will return true. Otherwise, this routine returns
2955/// false and User is unspecified.
2956///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002957/// \param AllowExplicit true if the conversion should consider C++0x
2958/// "explicit" conversion functions as well as non-explicit conversion
2959/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002960static OverloadingResult
2961IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002962 UserDefinedConversionSequence &User,
2963 OverloadCandidateSet &CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002964 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002965 // Whether we will only visit constructors.
2966 bool ConstructorsOnly = false;
2967
2968 // If the type we are conversion to is a class type, enumerate its
2969 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002970 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002971 // C++ [over.match.ctor]p1:
2972 // When objects of class type are direct-initialized (8.5), or
2973 // copy-initialized from an expression of the same or a
2974 // derived class type (8.5), overload resolution selects the
2975 // constructor. [...] For copy-initialization, the candidate
2976 // functions are all the converting constructors (12.3.1) of
2977 // that class. The argument list is the expression-list within
2978 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002979 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002980 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002981 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002982 ConstructorsOnly = true;
2983
Benjamin Kramer90633e32012-11-23 17:04:52 +00002984 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002985 // RequireCompleteType may have returned true due to some invalid decl
2986 // during template instantiation, but ToType may be complete enough now
2987 // to try to recover.
2988 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002989 // We're not going to find any constructors.
2990 } else if (CXXRecordDecl *ToRecordDecl
2991 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002992
2993 Expr **Args = &From;
2994 unsigned NumArgs = 1;
2995 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002996 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl82ace982012-02-11 23:51:08 +00002997 // But first, see if there is an init-list-contructor that will work.
2998 OverloadingResult Result = IsInitializerListConstructorConversion(
2999 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3000 if (Result != OR_No_Viable_Function)
3001 return Result;
3002 // Never mind.
3003 CandidateSet.clear();
3004
3005 // If we're list-initializing, we pass the individual elements as
3006 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003007 Args = InitList->getInits();
3008 NumArgs = InitList->getNumInits();
3009 ListInitializing = true;
3010 }
3011
Douglas Gregor89ee6822009-02-28 01:32:25 +00003012 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00003013 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00003014 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003015 NamedDecl *D = *Con;
3016 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3017
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003018 // Find the constructor (which may be a template).
3019 CXXConstructorDecl *Constructor = 0;
3020 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003021 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003022 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003023 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003024 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3025 else
John McCalla0296f72010-03-19 07:35:19 +00003026 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003027
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003028 bool Usable = !Constructor->isInvalidDecl();
3029 if (ListInitializing)
3030 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3031 else
3032 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3033 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003034 bool SuppressUserConversions = !ConstructorsOnly;
3035 if (SuppressUserConversions && ListInitializing) {
3036 SuppressUserConversions = false;
3037 if (NumArgs == 1) {
3038 // If the first argument is (a reference to) the target type,
3039 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003040 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3041 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003042 }
3043 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003044 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003045 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3046 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003047 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003048 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003049 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003050 // Allow one user-defined conversion when user specifies a
3051 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003052 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003053 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003054 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003055 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003056 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003057 }
3058 }
3059
Douglas Gregor5ab11652010-04-17 22:01:05 +00003060 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003061 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003062 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003063 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003064 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003065 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003066 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003067 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3068 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003069 std::pair<CXXRecordDecl::conversion_iterator,
3070 CXXRecordDecl::conversion_iterator>
3071 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3072 for (CXXRecordDecl::conversion_iterator
3073 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003074 DeclAccessPair FoundDecl = I.getPair();
3075 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003076 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3077 if (isa<UsingShadowDecl>(D))
3078 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3079
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003080 CXXConversionDecl *Conv;
3081 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003082 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3083 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003084 else
John McCallda4458e2010-03-31 01:36:47 +00003085 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003086
3087 if (AllowExplicit || !Conv->isExplicit()) {
3088 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003089 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3090 ActingContext, From, ToType,
3091 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003092 else
John McCall5c32be02010-08-24 20:38:10 +00003093 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3094 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003095 }
3096 }
3097 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003098 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003099
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003100 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3101
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003102 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003103 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003104 case OR_Success:
3105 // Record the standard conversion we used and the conversion function.
3106 if (CXXConstructorDecl *Constructor
3107 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3108 // C++ [over.ics.user]p1:
3109 // If the user-defined conversion is specified by a
3110 // constructor (12.3.1), the initial standard conversion
3111 // sequence converts the source type to the type required by
3112 // the argument of the constructor.
3113 //
3114 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003115 if (isa<InitListExpr>(From)) {
3116 // Initializer lists don't have conversions as such.
3117 User.Before.setAsIdentityConversion();
3118 } else {
3119 if (Best->Conversions[0].isEllipsis())
3120 User.EllipsisConversion = true;
3121 else {
3122 User.Before = Best->Conversions[0].Standard;
3123 User.EllipsisConversion = false;
3124 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003125 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003126 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003127 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003128 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003129 User.After.setAsIdentityConversion();
3130 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3131 User.After.setAllToTypes(ToType);
3132 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003133 }
3134 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003135 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3136 // C++ [over.ics.user]p1:
3137 //
3138 // [...] If the user-defined conversion is specified by a
3139 // conversion function (12.3.2), the initial standard
3140 // conversion sequence converts the source type to the
3141 // implicit object parameter of the conversion function.
3142 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003143 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003144 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003145 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003146 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003147
John McCall5c32be02010-08-24 20:38:10 +00003148 // C++ [over.ics.user]p2:
3149 // The second standard conversion sequence converts the
3150 // result of the user-defined conversion to the target type
3151 // for the sequence. Since an implicit conversion sequence
3152 // is an initialization, the special rules for
3153 // initialization by user-defined conversion apply when
3154 // selecting the best user-defined conversion for a
3155 // user-defined conversion sequence (see 13.3.3 and
3156 // 13.3.3.1).
3157 User.After = Best->FinalConversion;
3158 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003159 }
David Blaikie8a40f702012-01-17 06:56:22 +00003160 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003161
John McCall5c32be02010-08-24 20:38:10 +00003162 case OR_No_Viable_Function:
3163 return OR_No_Viable_Function;
3164 case OR_Deleted:
3165 // No conversion here! We're done.
3166 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003167
John McCall5c32be02010-08-24 20:38:10 +00003168 case OR_Ambiguous:
3169 return OR_Ambiguous;
3170 }
3171
David Blaikie8a40f702012-01-17 06:56:22 +00003172 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003173}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003174
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003175bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003176Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003177 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003178 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003179 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003180 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00003181 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003182 if (OvResult == OR_Ambiguous)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003183 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003184 diag::err_typecheck_ambiguous_condition)
3185 << From->getType() << ToType << From->getSourceRange();
3186 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003187 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003188 diag::err_typecheck_nonviable_condition)
3189 << From->getType() << ToType << From->getSourceRange();
3190 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003191 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003192 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003193 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003194}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003195
Douglas Gregor2837aa22012-02-22 17:32:19 +00003196/// \brief Compare the user-defined conversion functions or constructors
3197/// of two user-defined conversion sequences to determine whether any ordering
3198/// is possible.
3199static ImplicitConversionSequence::CompareKind
3200compareConversionFunctions(Sema &S,
3201 FunctionDecl *Function1,
3202 FunctionDecl *Function2) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003203 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003204 return ImplicitConversionSequence::Indistinguishable;
3205
3206 // Objective-C++:
3207 // If both conversion functions are implicitly-declared conversions from
3208 // a lambda closure type to a function pointer and a block pointer,
3209 // respectively, always prefer the conversion to a function pointer,
3210 // because the function pointer is more lightweight and is more likely
3211 // to keep code working.
3212 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3213 if (!Conv1)
3214 return ImplicitConversionSequence::Indistinguishable;
3215
3216 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3217 if (!Conv2)
3218 return ImplicitConversionSequence::Indistinguishable;
3219
3220 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3221 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3222 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3223 if (Block1 != Block2)
3224 return Block1? ImplicitConversionSequence::Worse
3225 : ImplicitConversionSequence::Better;
3226 }
3227
3228 return ImplicitConversionSequence::Indistinguishable;
3229}
3230
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003231/// CompareImplicitConversionSequences - Compare two implicit
3232/// conversion sequences to determine whether one is better than the
3233/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003234static ImplicitConversionSequence::CompareKind
3235CompareImplicitConversionSequences(Sema &S,
3236 const ImplicitConversionSequence& ICS1,
3237 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003238{
3239 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3240 // conversion sequences (as defined in 13.3.3.1)
3241 // -- a standard conversion sequence (13.3.3.1.1) is a better
3242 // conversion sequence than a user-defined conversion sequence or
3243 // an ellipsis conversion sequence, and
3244 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3245 // conversion sequence than an ellipsis conversion sequence
3246 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003247 //
John McCall0d1da222010-01-12 00:44:57 +00003248 // C++0x [over.best.ics]p10:
3249 // For the purpose of ranking implicit conversion sequences as
3250 // described in 13.3.3.2, the ambiguous conversion sequence is
3251 // treated as a user-defined sequence that is indistinguishable
3252 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00003253 if (ICS1.getKindRank() < ICS2.getKindRank())
3254 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003255 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003256 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003257
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003258 // The following checks require both conversion sequences to be of
3259 // the same kind.
3260 if (ICS1.getKind() != ICS2.getKind())
3261 return ImplicitConversionSequence::Indistinguishable;
3262
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003263 ImplicitConversionSequence::CompareKind Result =
3264 ImplicitConversionSequence::Indistinguishable;
3265
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003266 // Two implicit conversion sequences of the same form are
3267 // indistinguishable conversion sequences unless one of the
3268 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003269 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003270 Result = CompareStandardConversionSequences(S,
3271 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003272 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003273 // User-defined conversion sequence U1 is a better conversion
3274 // sequence than another user-defined conversion sequence U2 if
3275 // they contain the same user-defined conversion function or
3276 // constructor and if the second standard conversion sequence of
3277 // U1 is better than the second standard conversion sequence of
3278 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003279 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003280 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003281 Result = CompareStandardConversionSequences(S,
3282 ICS1.UserDefined.After,
3283 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003284 else
3285 Result = compareConversionFunctions(S,
3286 ICS1.UserDefined.ConversionFunction,
3287 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003288 }
3289
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003290 // List-initialization sequence L1 is a better conversion sequence than
3291 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3292 // for some X and L2 does not.
3293 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003294 !ICS1.isBad() &&
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003295 ICS1.isListInitializationSequence() &&
3296 ICS2.isListInitializationSequence()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003297 if (ICS1.isStdInitializerListElement() &&
3298 !ICS2.isStdInitializerListElement())
3299 return ImplicitConversionSequence::Better;
3300 if (!ICS1.isStdInitializerListElement() &&
3301 ICS2.isStdInitializerListElement())
3302 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003303 }
3304
3305 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003306}
3307
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003308static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3309 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3310 Qualifiers Quals;
3311 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003312 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003313 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003314
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003315 return Context.hasSameUnqualifiedType(T1, T2);
3316}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003317
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003318// Per 13.3.3.2p3, compare the given standard conversion sequences to
3319// determine if one is a proper subset of the other.
3320static ImplicitConversionSequence::CompareKind
3321compareStandardConversionSubsets(ASTContext &Context,
3322 const StandardConversionSequence& SCS1,
3323 const StandardConversionSequence& SCS2) {
3324 ImplicitConversionSequence::CompareKind Result
3325 = ImplicitConversionSequence::Indistinguishable;
3326
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003327 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003328 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003329 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3330 return ImplicitConversionSequence::Better;
3331 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3332 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003333
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003334 if (SCS1.Second != SCS2.Second) {
3335 if (SCS1.Second == ICK_Identity)
3336 Result = ImplicitConversionSequence::Better;
3337 else if (SCS2.Second == ICK_Identity)
3338 Result = ImplicitConversionSequence::Worse;
3339 else
3340 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003341 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003342 return ImplicitConversionSequence::Indistinguishable;
3343
3344 if (SCS1.Third == SCS2.Third) {
3345 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3346 : ImplicitConversionSequence::Indistinguishable;
3347 }
3348
3349 if (SCS1.Third == ICK_Identity)
3350 return Result == ImplicitConversionSequence::Worse
3351 ? ImplicitConversionSequence::Indistinguishable
3352 : ImplicitConversionSequence::Better;
3353
3354 if (SCS2.Third == ICK_Identity)
3355 return Result == ImplicitConversionSequence::Better
3356 ? ImplicitConversionSequence::Indistinguishable
3357 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003358
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003359 return ImplicitConversionSequence::Indistinguishable;
3360}
3361
Douglas Gregore696ebb2011-01-26 14:52:12 +00003362/// \brief Determine whether one of the given reference bindings is better
3363/// than the other based on what kind of bindings they are.
3364static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3365 const StandardConversionSequence &SCS2) {
3366 // C++0x [over.ics.rank]p3b4:
3367 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3368 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003369 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003370 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003371 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003372 // reference*.
3373 //
3374 // FIXME: Rvalue references. We're going rogue with the above edits,
3375 // because the semantics in the current C++0x working paper (N3225 at the
3376 // time of this writing) break the standard definition of std::forward
3377 // and std::reference_wrapper when dealing with references to functions.
3378 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003379 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3380 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3381 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003382
Douglas Gregore696ebb2011-01-26 14:52:12 +00003383 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3384 SCS2.IsLvalueReference) ||
3385 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3386 !SCS2.IsLvalueReference);
3387}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003388
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003389/// CompareStandardConversionSequences - Compare two standard
3390/// conversion sequences to determine whether one is better than the
3391/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003392static ImplicitConversionSequence::CompareKind
3393CompareStandardConversionSequences(Sema &S,
3394 const StandardConversionSequence& SCS1,
3395 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003396{
3397 // Standard conversion sequence S1 is a better conversion sequence
3398 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3399
3400 // -- S1 is a proper subsequence of S2 (comparing the conversion
3401 // sequences in the canonical form defined by 13.3.3.1.1,
3402 // excluding any Lvalue Transformation; the identity conversion
3403 // sequence is considered to be a subsequence of any
3404 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003405 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003406 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003407 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003408
3409 // -- the rank of S1 is better than the rank of S2 (by the rules
3410 // defined below), or, if not that,
3411 ImplicitConversionRank Rank1 = SCS1.getRank();
3412 ImplicitConversionRank Rank2 = SCS2.getRank();
3413 if (Rank1 < Rank2)
3414 return ImplicitConversionSequence::Better;
3415 else if (Rank2 < Rank1)
3416 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003417
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003418 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3419 // are indistinguishable unless one of the following rules
3420 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003421
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003422 // A conversion that is not a conversion of a pointer, or
3423 // pointer to member, to bool is better than another conversion
3424 // that is such a conversion.
3425 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3426 return SCS2.isPointerConversionToBool()
3427 ? ImplicitConversionSequence::Better
3428 : ImplicitConversionSequence::Worse;
3429
Douglas Gregor5c407d92008-10-23 00:40:37 +00003430 // C++ [over.ics.rank]p4b2:
3431 //
3432 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003433 // conversion of B* to A* is better than conversion of B* to
3434 // void*, and conversion of A* to void* is better than conversion
3435 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003436 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003437 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003438 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003439 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003440 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3441 // Exactly one of the conversion sequences is a conversion to
3442 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003443 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3444 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003445 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3446 // Neither conversion sequence converts to a void pointer; compare
3447 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003448 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003449 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003450 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003451 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3452 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003453 // Both conversion sequences are conversions to void
3454 // pointers. Compare the source types to determine if there's an
3455 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003456 QualType FromType1 = SCS1.getFromType();
3457 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003458
3459 // Adjust the types we're converting from via the array-to-pointer
3460 // conversion, if we need to.
3461 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003462 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003463 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003464 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003465
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003466 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3467 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003468
John McCall5c32be02010-08-24 20:38:10 +00003469 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003470 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003471 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003472 return ImplicitConversionSequence::Worse;
3473
3474 // Objective-C++: If one interface is more specific than the
3475 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003476 const ObjCObjectPointerType* FromObjCPtr1
3477 = FromType1->getAs<ObjCObjectPointerType>();
3478 const ObjCObjectPointerType* FromObjCPtr2
3479 = FromType2->getAs<ObjCObjectPointerType>();
3480 if (FromObjCPtr1 && FromObjCPtr2) {
3481 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3482 FromObjCPtr2);
3483 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3484 FromObjCPtr1);
3485 if (AssignLeft != AssignRight) {
3486 return AssignLeft? ImplicitConversionSequence::Better
3487 : ImplicitConversionSequence::Worse;
3488 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003489 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003490 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003491
3492 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3493 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003494 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003495 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003496 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003497
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003498 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003499 // Check for a better reference binding based on the kind of bindings.
3500 if (isBetterReferenceBindingKind(SCS1, SCS2))
3501 return ImplicitConversionSequence::Better;
3502 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3503 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003504
Sebastian Redlb28b4072009-03-22 23:49:27 +00003505 // C++ [over.ics.rank]p3b4:
3506 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3507 // which the references refer are the same type except for
3508 // top-level cv-qualifiers, and the type to which the reference
3509 // initialized by S2 refers is more cv-qualified than the type
3510 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003511 QualType T1 = SCS1.getToType(2);
3512 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003513 T1 = S.Context.getCanonicalType(T1);
3514 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003515 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003516 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3517 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003518 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003519 // Objective-C++ ARC: If the references refer to objects with different
3520 // lifetimes, prefer bindings that don't change lifetime.
3521 if (SCS1.ObjCLifetimeConversionBinding !=
3522 SCS2.ObjCLifetimeConversionBinding) {
3523 return SCS1.ObjCLifetimeConversionBinding
3524 ? ImplicitConversionSequence::Worse
3525 : ImplicitConversionSequence::Better;
3526 }
3527
Chandler Carruth8e543b32010-12-12 08:17:55 +00003528 // If the type is an array type, promote the element qualifiers to the
3529 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003530 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003531 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003532 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003533 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003534 if (T2.isMoreQualifiedThan(T1))
3535 return ImplicitConversionSequence::Better;
3536 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003537 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003538 }
3539 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003540
Francois Pichet08d2fa02011-09-18 21:37:37 +00003541 // In Microsoft mode, prefer an integral conversion to a
3542 // floating-to-integral conversion if the integral conversion
3543 // is between types of the same size.
3544 // For example:
3545 // void f(float);
3546 // void f(int);
3547 // int main {
3548 // long a;
3549 // f(a);
3550 // }
3551 // Here, MSVC will call f(int) instead of generating a compile error
3552 // as clang will do in standard mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003553 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003554 SCS1.Second == ICK_Integral_Conversion &&
3555 SCS2.Second == ICK_Floating_Integral &&
3556 S.Context.getTypeSize(SCS1.getFromType()) ==
3557 S.Context.getTypeSize(SCS1.getToType(2)))
3558 return ImplicitConversionSequence::Better;
3559
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003560 return ImplicitConversionSequence::Indistinguishable;
3561}
3562
3563/// CompareQualificationConversions - Compares two standard conversion
3564/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003565/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3566ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003567CompareQualificationConversions(Sema &S,
3568 const StandardConversionSequence& SCS1,
3569 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003570 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003571 // -- S1 and S2 differ only in their qualification conversion and
3572 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3573 // cv-qualification signature of type T1 is a proper subset of
3574 // the cv-qualification signature of type T2, and S1 is not the
3575 // deprecated string literal array-to-pointer conversion (4.2).
3576 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3577 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3578 return ImplicitConversionSequence::Indistinguishable;
3579
3580 // FIXME: the example in the standard doesn't use a qualification
3581 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003582 QualType T1 = SCS1.getToType(2);
3583 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003584 T1 = S.Context.getCanonicalType(T1);
3585 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003586 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003587 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3588 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003589
3590 // If the types are the same, we won't learn anything by unwrapped
3591 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003592 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003593 return ImplicitConversionSequence::Indistinguishable;
3594
Chandler Carruth607f38e2009-12-29 07:16:59 +00003595 // If the type is an array type, promote the element qualifiers to the type
3596 // for comparison.
3597 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003598 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003599 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003600 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003601
Mike Stump11289f42009-09-09 15:08:12 +00003602 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003603 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003604
3605 // Objective-C++ ARC:
3606 // Prefer qualification conversions not involving a change in lifetime
3607 // to qualification conversions that do not change lifetime.
3608 if (SCS1.QualificationIncludesObjCLifetime !=
3609 SCS2.QualificationIncludesObjCLifetime) {
3610 Result = SCS1.QualificationIncludesObjCLifetime
3611 ? ImplicitConversionSequence::Worse
3612 : ImplicitConversionSequence::Better;
3613 }
3614
John McCall5c32be02010-08-24 20:38:10 +00003615 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003616 // Within each iteration of the loop, we check the qualifiers to
3617 // determine if this still looks like a qualification
3618 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003619 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003620 // until there are no more pointers or pointers-to-members left
3621 // to unwrap. This essentially mimics what
3622 // IsQualificationConversion does, but here we're checking for a
3623 // strict subset of qualifiers.
3624 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3625 // The qualifiers are the same, so this doesn't tell us anything
3626 // about how the sequences rank.
3627 ;
3628 else if (T2.isMoreQualifiedThan(T1)) {
3629 // T1 has fewer qualifiers, so it could be the better sequence.
3630 if (Result == ImplicitConversionSequence::Worse)
3631 // Neither has qualifiers that are a subset of the other's
3632 // qualifiers.
3633 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003634
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003635 Result = ImplicitConversionSequence::Better;
3636 } else if (T1.isMoreQualifiedThan(T2)) {
3637 // T2 has fewer qualifiers, so it could be the better sequence.
3638 if (Result == ImplicitConversionSequence::Better)
3639 // Neither has qualifiers that are a subset of the other's
3640 // qualifiers.
3641 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003642
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003643 Result = ImplicitConversionSequence::Worse;
3644 } else {
3645 // Qualifiers are disjoint.
3646 return ImplicitConversionSequence::Indistinguishable;
3647 }
3648
3649 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003650 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003651 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003652 }
3653
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003654 // Check that the winning standard conversion sequence isn't using
3655 // the deprecated string literal array to pointer conversion.
3656 switch (Result) {
3657 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003658 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003659 Result = ImplicitConversionSequence::Indistinguishable;
3660 break;
3661
3662 case ImplicitConversionSequence::Indistinguishable:
3663 break;
3664
3665 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003666 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003667 Result = ImplicitConversionSequence::Indistinguishable;
3668 break;
3669 }
3670
3671 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003672}
3673
Douglas Gregor5c407d92008-10-23 00:40:37 +00003674/// CompareDerivedToBaseConversions - Compares two standard conversion
3675/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003676/// various kinds of derived-to-base conversions (C++
3677/// [over.ics.rank]p4b3). As part of these checks, we also look at
3678/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003679ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003680CompareDerivedToBaseConversions(Sema &S,
3681 const StandardConversionSequence& SCS1,
3682 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003683 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003684 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003685 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003686 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003687
3688 // Adjust the types we're converting from via the array-to-pointer
3689 // conversion, if we need to.
3690 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003691 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003692 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003693 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003694
3695 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003696 FromType1 = S.Context.getCanonicalType(FromType1);
3697 ToType1 = S.Context.getCanonicalType(ToType1);
3698 FromType2 = S.Context.getCanonicalType(FromType2);
3699 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003700
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003701 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003702 //
3703 // If class B is derived directly or indirectly from class A and
3704 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003705 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003706 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003707 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003708 SCS2.Second == ICK_Pointer_Conversion &&
3709 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3710 FromType1->isPointerType() && FromType2->isPointerType() &&
3711 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003712 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003713 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003714 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003715 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003716 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003717 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003718 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003719 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003720
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003721 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003722 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003723 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003724 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003725 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003726 return ImplicitConversionSequence::Worse;
3727 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003728
3729 // -- conversion of B* to A* is better than conversion of C* to A*,
3730 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003731 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003732 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003733 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003734 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003735 }
3736 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3737 SCS2.Second == ICK_Pointer_Conversion) {
3738 const ObjCObjectPointerType *FromPtr1
3739 = FromType1->getAs<ObjCObjectPointerType>();
3740 const ObjCObjectPointerType *FromPtr2
3741 = FromType2->getAs<ObjCObjectPointerType>();
3742 const ObjCObjectPointerType *ToPtr1
3743 = ToType1->getAs<ObjCObjectPointerType>();
3744 const ObjCObjectPointerType *ToPtr2
3745 = ToType2->getAs<ObjCObjectPointerType>();
3746
3747 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3748 // Apply the same conversion ranking rules for Objective-C pointer types
3749 // that we do for C++ pointers to class types. However, we employ the
3750 // Objective-C pseudo-subtyping relationship used for assignment of
3751 // Objective-C pointer types.
3752 bool FromAssignLeft
3753 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3754 bool FromAssignRight
3755 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3756 bool ToAssignLeft
3757 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3758 bool ToAssignRight
3759 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3760
3761 // A conversion to an a non-id object pointer type or qualified 'id'
3762 // type is better than a conversion to 'id'.
3763 if (ToPtr1->isObjCIdType() &&
3764 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3765 return ImplicitConversionSequence::Worse;
3766 if (ToPtr2->isObjCIdType() &&
3767 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3768 return ImplicitConversionSequence::Better;
3769
3770 // A conversion to a non-id object pointer type is better than a
3771 // conversion to a qualified 'id' type
3772 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3773 return ImplicitConversionSequence::Worse;
3774 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3775 return ImplicitConversionSequence::Better;
3776
3777 // A conversion to an a non-Class object pointer type or qualified 'Class'
3778 // type is better than a conversion to 'Class'.
3779 if (ToPtr1->isObjCClassType() &&
3780 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3781 return ImplicitConversionSequence::Worse;
3782 if (ToPtr2->isObjCClassType() &&
3783 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3784 return ImplicitConversionSequence::Better;
3785
3786 // A conversion to a non-Class object pointer type is better than a
3787 // conversion to a qualified 'Class' type.
3788 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3789 return ImplicitConversionSequence::Worse;
3790 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3791 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003792
Douglas Gregor058d3de2011-01-31 18:51:41 +00003793 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3794 if (S.Context.hasSameType(FromType1, FromType2) &&
3795 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3796 (ToAssignLeft != ToAssignRight))
3797 return ToAssignLeft? ImplicitConversionSequence::Worse
3798 : ImplicitConversionSequence::Better;
3799
3800 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3801 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3802 (FromAssignLeft != FromAssignRight))
3803 return FromAssignLeft? ImplicitConversionSequence::Better
3804 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003805 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003806 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003807
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003808 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003809 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3810 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3811 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003812 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003813 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003814 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003815 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003816 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003817 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003818 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003819 ToType2->getAs<MemberPointerType>();
3820 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3821 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3822 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3823 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3824 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3825 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3826 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3827 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003828 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003829 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003830 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003831 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003832 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003833 return ImplicitConversionSequence::Better;
3834 }
3835 // conversion of B::* to C::* is better than conversion of A::* to C::*
3836 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003837 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003838 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003839 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003840 return ImplicitConversionSequence::Worse;
3841 }
3842 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003843
Douglas Gregor5ab11652010-04-17 22:01:05 +00003844 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003845 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003846 // -- binding of an expression of type C to a reference of type
3847 // B& is better than binding an expression of type C to a
3848 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003849 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3850 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3851 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003852 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003853 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003854 return ImplicitConversionSequence::Worse;
3855 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003856
Douglas Gregor2fe98832008-11-03 19:09:14 +00003857 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003858 // -- binding of an expression of type B to a reference of type
3859 // A& is better than binding an expression of type C to a
3860 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003861 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3862 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3863 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003864 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003865 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003866 return ImplicitConversionSequence::Worse;
3867 }
3868 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003869
Douglas Gregor5c407d92008-10-23 00:40:37 +00003870 return ImplicitConversionSequence::Indistinguishable;
3871}
3872
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003873/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3874/// determine whether they are reference-related,
3875/// reference-compatible, reference-compatible with added
3876/// qualification, or incompatible, for use in C++ initialization by
3877/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3878/// type, and the first type (T1) is the pointee type of the reference
3879/// type being initialized.
3880Sema::ReferenceCompareResult
3881Sema::CompareReferenceRelationship(SourceLocation Loc,
3882 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003883 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003884 bool &ObjCConversion,
3885 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003886 assert(!OrigT1->isReferenceType() &&
3887 "T1 must be the pointee type of the reference type");
3888 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3889
3890 QualType T1 = Context.getCanonicalType(OrigT1);
3891 QualType T2 = Context.getCanonicalType(OrigT2);
3892 Qualifiers T1Quals, T2Quals;
3893 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3894 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3895
3896 // C++ [dcl.init.ref]p4:
3897 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3898 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3899 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003900 DerivedToBase = false;
3901 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003902 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003903 if (UnqualT1 == UnqualT2) {
3904 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003905 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003906 IsDerivedFrom(UnqualT2, UnqualT1))
3907 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003908 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3909 UnqualT2->isObjCObjectOrInterfaceType() &&
3910 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3911 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003912 else
3913 return Ref_Incompatible;
3914
3915 // At this point, we know that T1 and T2 are reference-related (at
3916 // least).
3917
3918 // If the type is an array type, promote the element qualifiers to the type
3919 // for comparison.
3920 if (isa<ArrayType>(T1) && T1Quals)
3921 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3922 if (isa<ArrayType>(T2) && T2Quals)
3923 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3924
3925 // C++ [dcl.init.ref]p4:
3926 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3927 // reference-related to T2 and cv1 is the same cv-qualification
3928 // as, or greater cv-qualification than, cv2. For purposes of
3929 // overload resolution, cases for which cv1 is greater
3930 // cv-qualification than cv2 are identified as
3931 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003932 //
3933 // Note that we also require equivalence of Objective-C GC and address-space
3934 // qualifiers when performing these computations, so that e.g., an int in
3935 // address space 1 is not reference-compatible with an int in address
3936 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003937 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3938 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3939 T1Quals.removeObjCLifetime();
3940 T2Quals.removeObjCLifetime();
3941 ObjCLifetimeConversion = true;
3942 }
3943
Douglas Gregord517d552011-04-28 17:56:11 +00003944 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003945 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003946 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003947 return Ref_Compatible_With_Added_Qualification;
3948 else
3949 return Ref_Related;
3950}
3951
Douglas Gregor836a7e82010-08-11 02:15:33 +00003952/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003953/// with DeclType. Return true if something definite is found.
3954static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003955FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3956 QualType DeclType, SourceLocation DeclLoc,
3957 Expr *Init, QualType T2, bool AllowRvalues,
3958 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003959 assert(T2->isRecordType() && "Can only find conversions of record types.");
3960 CXXRecordDecl *T2RecordDecl
3961 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3962
3963 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003964 std::pair<CXXRecordDecl::conversion_iterator,
3965 CXXRecordDecl::conversion_iterator>
3966 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3967 for (CXXRecordDecl::conversion_iterator
3968 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003969 NamedDecl *D = *I;
3970 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3971 if (isa<UsingShadowDecl>(D))
3972 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3973
3974 FunctionTemplateDecl *ConvTemplate
3975 = dyn_cast<FunctionTemplateDecl>(D);
3976 CXXConversionDecl *Conv;
3977 if (ConvTemplate)
3978 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3979 else
3980 Conv = cast<CXXConversionDecl>(D);
3981
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003982 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003983 // explicit conversions, skip it.
3984 if (!AllowExplicit && Conv->isExplicit())
3985 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003986
Douglas Gregor836a7e82010-08-11 02:15:33 +00003987 if (AllowRvalues) {
3988 bool DerivedToBase = false;
3989 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003990 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003991
3992 // If we are initializing an rvalue reference, don't permit conversion
3993 // functions that return lvalues.
3994 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3995 const ReferenceType *RefType
3996 = Conv->getConversionType()->getAs<LValueReferenceType>();
3997 if (RefType && !RefType->getPointeeType()->isFunctionType())
3998 continue;
3999 }
4000
Douglas Gregor836a7e82010-08-11 02:15:33 +00004001 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004002 S.CompareReferenceRelationship(
4003 DeclLoc,
4004 Conv->getConversionType().getNonReferenceType()
4005 .getUnqualifiedType(),
4006 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004007 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004008 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004009 continue;
4010 } else {
4011 // If the conversion function doesn't return a reference type,
4012 // it can't be considered for this conversion. An rvalue reference
4013 // is only acceptable if its referencee is a function type.
4014
4015 const ReferenceType *RefType =
4016 Conv->getConversionType()->getAs<ReferenceType>();
4017 if (!RefType ||
4018 (!RefType->isLValueReferenceType() &&
4019 !RefType->getPointeeType()->isFunctionType()))
4020 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004021 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004022
Douglas Gregor836a7e82010-08-11 02:15:33 +00004023 if (ConvTemplate)
4024 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00004025 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004026 else
4027 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00004028 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00004029 }
4030
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004031 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4032
Sebastian Redld92badf2010-06-30 18:13:39 +00004033 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004034 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004035 case OR_Success:
4036 // C++ [over.ics.ref]p1:
4037 //
4038 // [...] If the parameter binds directly to the result of
4039 // applying a conversion function to the argument
4040 // expression, the implicit conversion sequence is a
4041 // user-defined conversion sequence (13.3.3.1.2), with the
4042 // second standard conversion sequence either an identity
4043 // conversion or, if the conversion function returns an
4044 // entity of a type that is a derived class of the parameter
4045 // type, a derived-to-base Conversion.
4046 if (!Best->FinalConversion.DirectBinding)
4047 return false;
4048
4049 ICS.setUserDefined();
4050 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4051 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004052 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004053 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004054 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004055 ICS.UserDefined.EllipsisConversion = false;
4056 assert(ICS.UserDefined.After.ReferenceBinding &&
4057 ICS.UserDefined.After.DirectBinding &&
4058 "Expected a direct reference binding!");
4059 return true;
4060
4061 case OR_Ambiguous:
4062 ICS.setAmbiguous();
4063 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4064 Cand != CandidateSet.end(); ++Cand)
4065 if (Cand->Viable)
4066 ICS.Ambiguous.addConversion(Cand->Function);
4067 return true;
4068
4069 case OR_No_Viable_Function:
4070 case OR_Deleted:
4071 // There was no suitable conversion, or we found a deleted
4072 // conversion; continue with other checks.
4073 return false;
4074 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004075
David Blaikie8a40f702012-01-17 06:56:22 +00004076 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004077}
4078
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004079/// \brief Compute an implicit conversion sequence for reference
4080/// initialization.
4081static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004082TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004083 SourceLocation DeclLoc,
4084 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004085 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004086 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4087
4088 // Most paths end in a failed conversion.
4089 ImplicitConversionSequence ICS;
4090 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4091
4092 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4093 QualType T2 = Init->getType();
4094
4095 // If the initializer is the address of an overloaded function, try
4096 // to resolve the overloaded function. If all goes well, T2 is the
4097 // type of the resulting function.
4098 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4099 DeclAccessPair Found;
4100 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4101 false, Found))
4102 T2 = Fn->getType();
4103 }
4104
4105 // Compute some basic properties of the types and the initializer.
4106 bool isRValRef = DeclType->isRValueReferenceType();
4107 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004108 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004109 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004110 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004111 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004112 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004113 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004114
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004115
Sebastian Redld92badf2010-06-30 18:13:39 +00004116 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004117 // A reference to type "cv1 T1" is initialized by an expression
4118 // of type "cv2 T2" as follows:
4119
Sebastian Redld92badf2010-06-30 18:13:39 +00004120 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004121 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004122 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4123 // reference-compatible with "cv2 T2," or
4124 //
4125 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4126 if (InitCategory.isLValue() &&
4127 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004128 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004129 // When a parameter of reference type binds directly (8.5.3)
4130 // to an argument expression, the implicit conversion sequence
4131 // is the identity conversion, unless the argument expression
4132 // has a type that is a derived class of the parameter type,
4133 // in which case the implicit conversion sequence is a
4134 // derived-to-base Conversion (13.3.3.1).
4135 ICS.setStandard();
4136 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004137 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4138 : ObjCConversion? ICK_Compatible_Conversion
4139 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004140 ICS.Standard.Third = ICK_Identity;
4141 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4142 ICS.Standard.setToType(0, T2);
4143 ICS.Standard.setToType(1, T1);
4144 ICS.Standard.setToType(2, T1);
4145 ICS.Standard.ReferenceBinding = true;
4146 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004147 ICS.Standard.IsLvalueReference = !isRValRef;
4148 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4149 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004150 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004151 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004152 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004153
Sebastian Redld92badf2010-06-30 18:13:39 +00004154 // Nothing more to do: the inaccessibility/ambiguity check for
4155 // derived-to-base conversions is suppressed when we're
4156 // computing the implicit conversion sequence (C++
4157 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004158 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004159 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004160
Sebastian Redld92badf2010-06-30 18:13:39 +00004161 // -- has a class type (i.e., T2 is a class type), where T1 is
4162 // not reference-related to T2, and can be implicitly
4163 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4164 // is reference-compatible with "cv3 T3" 92) (this
4165 // conversion is selected by enumerating the applicable
4166 // conversion functions (13.3.1.6) and choosing the best
4167 // one through overload resolution (13.3)),
4168 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004169 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004170 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004171 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4172 Init, T2, /*AllowRvalues=*/false,
4173 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004174 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004175 }
4176 }
4177
Sebastian Redld92badf2010-06-30 18:13:39 +00004178 // -- Otherwise, the reference shall be an lvalue reference to a
4179 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004180 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004181 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004182 // We actually handle one oddity of C++ [over.ics.ref] at this
4183 // point, which is that, due to p2 (which short-circuits reference
4184 // binding by only attempting a simple conversion for non-direct
4185 // bindings) and p3's strange wording, we allow a const volatile
4186 // reference to bind to an rvalue. Hence the check for the presence
4187 // of "const" rather than checking for "const" being the only
4188 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004189 // This is also the point where rvalue references and lvalue inits no longer
4190 // go together.
Richard Smithce4f6082012-05-24 04:29:20 +00004191 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004192 return ICS;
4193
Douglas Gregorf143cd52011-01-24 16:14:37 +00004194 // -- If the initializer expression
4195 //
4196 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004197 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004198 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4199 (InitCategory.isXValue() ||
4200 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4201 (InitCategory.isLValue() && T2->isFunctionType()))) {
4202 ICS.setStandard();
4203 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004204 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004205 : ObjCConversion? ICK_Compatible_Conversion
4206 : ICK_Identity;
4207 ICS.Standard.Third = ICK_Identity;
4208 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4209 ICS.Standard.setToType(0, T2);
4210 ICS.Standard.setToType(1, T1);
4211 ICS.Standard.setToType(2, T1);
4212 ICS.Standard.ReferenceBinding = true;
4213 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4214 // binding unless we're binding to a class prvalue.
4215 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4216 // allow the use of rvalue references in C++98/03 for the benefit of
4217 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004218 ICS.Standard.DirectBinding =
David Blaikiebbafb8a2012-03-11 07:00:24 +00004219 S.getLangOpts().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004220 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004221 ICS.Standard.IsLvalueReference = !isRValRef;
4222 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004223 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004224 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004225 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004226 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004227 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004228 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004229
Douglas Gregorf143cd52011-01-24 16:14:37 +00004230 // -- has a class type (i.e., T2 is a class type), where T1 is not
4231 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004232 // an xvalue, class prvalue, or function lvalue of type
4233 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004234 // "cv3 T3",
4235 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004236 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004237 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004238 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004239 // class subobject).
4240 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004241 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004242 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4243 Init, T2, /*AllowRvalues=*/true,
4244 AllowExplicit)) {
4245 // In the second case, if the reference is an rvalue reference
4246 // and the second standard conversion sequence of the
4247 // user-defined conversion sequence includes an lvalue-to-rvalue
4248 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004249 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004250 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4251 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4252
Douglas Gregor95273c32011-01-21 16:36:05 +00004253 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004255
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004256 // -- Otherwise, a temporary of type "cv1 T1" is created and
4257 // initialized from the initializer expression using the
4258 // rules for a non-reference copy initialization (8.5). The
4259 // reference is then bound to the temporary. If T1 is
4260 // reference-related to T2, cv1 must be the same
4261 // cv-qualification as, or greater cv-qualification than,
4262 // cv2; otherwise, the program is ill-formed.
4263 if (RefRelationship == Sema::Ref_Related) {
4264 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4265 // we would be reference-compatible or reference-compatible with
4266 // added qualification. But that wasn't the case, so the reference
4267 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004268 //
4269 // Note that we only want to check address spaces and cvr-qualifiers here.
4270 // ObjC GC and lifetime qualifiers aren't important.
4271 Qualifiers T1Quals = T1.getQualifiers();
4272 Qualifiers T2Quals = T2.getQualifiers();
4273 T1Quals.removeObjCGCAttr();
4274 T1Quals.removeObjCLifetime();
4275 T2Quals.removeObjCGCAttr();
4276 T2Quals.removeObjCLifetime();
4277 if (!T1Quals.compatiblyIncludes(T2Quals))
4278 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004279 }
4280
4281 // If at least one of the types is a class type, the types are not
4282 // related, and we aren't allowed any user conversions, the
4283 // reference binding fails. This case is important for breaking
4284 // recursion, since TryImplicitConversion below will attempt to
4285 // create a temporary through the use of a copy constructor.
4286 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4287 (T1->isRecordType() || T2->isRecordType()))
4288 return ICS;
4289
Douglas Gregorcba72b12011-01-21 05:18:22 +00004290 // If T1 is reference-related to T2 and the reference is an rvalue
4291 // reference, the initializer expression shall not be an lvalue.
4292 if (RefRelationship >= Sema::Ref_Related &&
4293 isRValRef && Init->Classify(S.Context).isLValue())
4294 return ICS;
4295
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004296 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004297 // When a parameter of reference type is not bound directly to
4298 // an argument expression, the conversion sequence is the one
4299 // required to convert the argument expression to the
4300 // underlying type of the reference according to
4301 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4302 // to copy-initializing a temporary of the underlying type with
4303 // the argument expression. Any difference in top-level
4304 // cv-qualification is subsumed by the initialization itself
4305 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004306 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4307 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004308 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004309 /*CStyle=*/false,
4310 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004311
4312 // Of course, that's still a reference binding.
4313 if (ICS.isStandard()) {
4314 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004315 ICS.Standard.IsLvalueReference = !isRValRef;
4316 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4317 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004318 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004319 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004320 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004321 // Don't allow rvalue references to bind to lvalues.
4322 if (DeclType->isRValueReferenceType()) {
4323 if (const ReferenceType *RefType
4324 = ICS.UserDefined.ConversionFunction->getResultType()
4325 ->getAs<LValueReferenceType>()) {
4326 if (!RefType->getPointeeType()->isFunctionType()) {
4327 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4328 DeclType);
4329 return ICS;
4330 }
4331 }
4332 }
4333
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004334 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004335 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4336 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4337 ICS.UserDefined.After.BindsToRvalue = true;
4338 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4339 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004340 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004341
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004342 return ICS;
4343}
4344
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004345static ImplicitConversionSequence
4346TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4347 bool SuppressUserConversions,
4348 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004349 bool AllowObjCWritebackConversion,
4350 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004351
4352/// TryListConversion - Try to copy-initialize a value of type ToType from the
4353/// initializer list From.
4354static ImplicitConversionSequence
4355TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4356 bool SuppressUserConversions,
4357 bool InOverloadResolution,
4358 bool AllowObjCWritebackConversion) {
4359 // C++11 [over.ics.list]p1:
4360 // When an argument is an initializer list, it is not an expression and
4361 // special rules apply for converting it to a parameter type.
4362
4363 ImplicitConversionSequence Result;
4364 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004365 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004366
Sebastian Redl09edce02012-01-23 22:09:39 +00004367 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004368 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004369 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004370 return Result;
4371
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004372 // C++11 [over.ics.list]p2:
4373 // If the parameter type is std::initializer_list<X> or "array of X" and
4374 // all the elements can be implicitly converted to X, the implicit
4375 // conversion sequence is the worst conversion necessary to convert an
4376 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004377 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004378 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004379 if (ToType->isArrayType())
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004380 X = S.Context.getBaseElementType(ToType);
4381 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004382 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004383 if (!X.isNull()) {
4384 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4385 Expr *Init = From->getInit(i);
4386 ImplicitConversionSequence ICS =
4387 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4388 InOverloadResolution,
4389 AllowObjCWritebackConversion);
4390 // If a single element isn't convertible, fail.
4391 if (ICS.isBad()) {
4392 Result = ICS;
4393 break;
4394 }
4395 // Otherwise, look for the worst conversion.
4396 if (Result.isBad() ||
4397 CompareImplicitConversionSequences(S, ICS, Result) ==
4398 ImplicitConversionSequence::Worse)
4399 Result = ICS;
4400 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004401
4402 // For an empty list, we won't have computed any conversion sequence.
4403 // Introduce the identity conversion sequence.
4404 if (From->getNumInits() == 0) {
4405 Result.setStandard();
4406 Result.Standard.setAsIdentityConversion();
4407 Result.Standard.setFromType(ToType);
4408 Result.Standard.setAllToTypes(ToType);
4409 }
4410
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004411 Result.setListInitializationSequence();
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004412 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004413 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004414 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004415
4416 // C++11 [over.ics.list]p3:
4417 // Otherwise, if the parameter is a non-aggregate class X and overload
4418 // resolution chooses a single best constructor [...] the implicit
4419 // conversion sequence is a user-defined conversion sequence. If multiple
4420 // constructors are viable but none is better than the others, the
4421 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004422 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4423 // This function can deal with initializer lists.
4424 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4425 /*AllowExplicit=*/false,
4426 InOverloadResolution, /*CStyle=*/false,
4427 AllowObjCWritebackConversion);
4428 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004429 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004430 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004431
4432 // C++11 [over.ics.list]p4:
4433 // Otherwise, if the parameter has an aggregate type which can be
4434 // initialized from the initializer list [...] the implicit conversion
4435 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004436 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004437 // Type is an aggregate, argument is an init list. At this point it comes
4438 // down to checking whether the initialization works.
4439 // FIXME: Find out whether this parameter is consumed or not.
4440 InitializedEntity Entity =
4441 InitializedEntity::InitializeParameter(S.Context, ToType,
4442 /*Consumed=*/false);
4443 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4444 Result.setUserDefined();
4445 Result.UserDefined.Before.setAsIdentityConversion();
4446 // Initializer lists don't have a type.
4447 Result.UserDefined.Before.setFromType(QualType());
4448 Result.UserDefined.Before.setAllToTypes(QualType());
4449
4450 Result.UserDefined.After.setAsIdentityConversion();
4451 Result.UserDefined.After.setFromType(ToType);
4452 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004453 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004454 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004455 return Result;
4456 }
4457
4458 // C++11 [over.ics.list]p5:
4459 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004460 if (ToType->isReferenceType()) {
4461 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4462 // mention initializer lists in any way. So we go by what list-
4463 // initialization would do and try to extrapolate from that.
4464
4465 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4466
4467 // If the initializer list has a single element that is reference-related
4468 // to the parameter type, we initialize the reference from that.
4469 if (From->getNumInits() == 1) {
4470 Expr *Init = From->getInit(0);
4471
4472 QualType T2 = Init->getType();
4473
4474 // If the initializer is the address of an overloaded function, try
4475 // to resolve the overloaded function. If all goes well, T2 is the
4476 // type of the resulting function.
4477 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4478 DeclAccessPair Found;
4479 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4480 Init, ToType, false, Found))
4481 T2 = Fn->getType();
4482 }
4483
4484 // Compute some basic properties of the types and the initializer.
4485 bool dummy1 = false;
4486 bool dummy2 = false;
4487 bool dummy3 = false;
4488 Sema::ReferenceCompareResult RefRelationship
4489 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4490 dummy2, dummy3);
4491
4492 if (RefRelationship >= Sema::Ref_Related)
4493 return TryReferenceInit(S, Init, ToType,
4494 /*FIXME:*/From->getLocStart(),
4495 SuppressUserConversions,
4496 /*AllowExplicit=*/false);
4497 }
4498
4499 // Otherwise, we bind the reference to a temporary created from the
4500 // initializer list.
4501 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4502 InOverloadResolution,
4503 AllowObjCWritebackConversion);
4504 if (Result.isFailure())
4505 return Result;
4506 assert(!Result.isEllipsis() &&
4507 "Sub-initialization cannot result in ellipsis conversion.");
4508
4509 // Can we even bind to a temporary?
4510 if (ToType->isRValueReferenceType() ||
4511 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4512 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4513 Result.UserDefined.After;
4514 SCS.ReferenceBinding = true;
4515 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4516 SCS.BindsToRvalue = true;
4517 SCS.BindsToFunctionLvalue = false;
4518 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4519 SCS.ObjCLifetimeConversionBinding = false;
4520 } else
4521 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4522 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004523 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004524 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004525
4526 // C++11 [over.ics.list]p6:
4527 // Otherwise, if the parameter type is not a class:
4528 if (!ToType->isRecordType()) {
4529 // - if the initializer list has one element, the implicit conversion
4530 // sequence is the one required to convert the element to the
4531 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004532 unsigned NumInits = From->getNumInits();
4533 if (NumInits == 1)
4534 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4535 SuppressUserConversions,
4536 InOverloadResolution,
4537 AllowObjCWritebackConversion);
4538 // - if the initializer list has no elements, the implicit conversion
4539 // sequence is the identity conversion.
4540 else if (NumInits == 0) {
4541 Result.setStandard();
4542 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004543 Result.Standard.setFromType(ToType);
4544 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004545 }
Sebastian Redl12edeb02012-02-28 23:36:38 +00004546 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004547 return Result;
4548 }
4549
4550 // C++11 [over.ics.list]p7:
4551 // In all cases other than those enumerated above, no conversion is possible
4552 return Result;
4553}
4554
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004555/// TryCopyInitialization - Try to copy-initialize a value of type
4556/// ToType from the expression From. Return the implicit conversion
4557/// sequence required to pass this argument, which may be a bad
4558/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004559/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004560/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004561static ImplicitConversionSequence
4562TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004563 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004564 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004565 bool AllowObjCWritebackConversion,
4566 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004567 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4568 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4569 InOverloadResolution,AllowObjCWritebackConversion);
4570
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004571 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004572 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004573 /*FIXME:*/From->getLocStart(),
4574 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004575 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004576
John McCall5c32be02010-08-24 20:38:10 +00004577 return TryImplicitConversion(S, From, ToType,
4578 SuppressUserConversions,
4579 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004580 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004581 /*CStyle=*/false,
4582 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004583}
4584
Anna Zaks1b068122011-07-28 19:46:48 +00004585static bool TryCopyInitialization(const CanQualType FromQTy,
4586 const CanQualType ToQTy,
4587 Sema &S,
4588 SourceLocation Loc,
4589 ExprValueKind FromVK) {
4590 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4591 ImplicitConversionSequence ICS =
4592 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4593
4594 return !ICS.isBad();
4595}
4596
Douglas Gregor436424c2008-11-18 23:14:02 +00004597/// TryObjectArgumentInitialization - Try to initialize the object
4598/// parameter of the given member function (@c Method) from the
4599/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004600static ImplicitConversionSequence
4601TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004602 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004603 CXXMethodDecl *Method,
4604 CXXRecordDecl *ActingContext) {
4605 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004606 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4607 // const volatile object.
4608 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4609 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004610 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004611
4612 // Set up the conversion sequence as a "bad" conversion, to allow us
4613 // to exit early.
4614 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004615
4616 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004617 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004618 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004619 FromType = PT->getPointeeType();
4620
Douglas Gregor02824322011-01-26 19:30:28 +00004621 // When we had a pointer, it's implicitly dereferenced, so we
4622 // better have an lvalue.
4623 assert(FromClassification.isLValue());
4624 }
4625
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004626 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004627
Douglas Gregor02824322011-01-26 19:30:28 +00004628 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004629 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004630 // parameter is
4631 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004632 // - "lvalue reference to cv X" for functions declared without a
4633 // ref-qualifier or with the & ref-qualifier
4634 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004635 // ref-qualifier
4636 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004637 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004638 // cv-qualification on the member function declaration.
4639 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004640 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004641 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004642 // (C++ [over.match.funcs]p5). We perform a simplified version of
4643 // reference binding here, that allows class rvalues to bind to
4644 // non-constant references.
4645
Douglas Gregor02824322011-01-26 19:30:28 +00004646 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004647 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004648 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004649 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004650 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004651 ICS.setBad(BadConversionSequence::bad_qualifiers,
4652 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004653 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004654 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004655
4656 // Check that we have either the same type or a derived type. It
4657 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004658 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004659 ImplicitConversionKind SecondKind;
4660 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4661 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004662 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004663 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004664 else {
John McCall65eb8792010-02-25 01:37:24 +00004665 ICS.setBad(BadConversionSequence::unrelated_class,
4666 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004667 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004668 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004669
Douglas Gregor02824322011-01-26 19:30:28 +00004670 // Check the ref-qualifier.
4671 switch (Method->getRefQualifier()) {
4672 case RQ_None:
4673 // Do nothing; we don't care about lvalueness or rvalueness.
4674 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004675
Douglas Gregor02824322011-01-26 19:30:28 +00004676 case RQ_LValue:
4677 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4678 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004679 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004680 ImplicitParamType);
4681 return ICS;
4682 }
4683 break;
4684
4685 case RQ_RValue:
4686 if (!FromClassification.isRValue()) {
4687 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004688 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004689 ImplicitParamType);
4690 return ICS;
4691 }
4692 break;
4693 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004694
Douglas Gregor436424c2008-11-18 23:14:02 +00004695 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004696 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004697 ICS.Standard.setAsIdentityConversion();
4698 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004699 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004700 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004701 ICS.Standard.ReferenceBinding = true;
4702 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004703 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004704 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004705 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4706 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4707 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004708 return ICS;
4709}
4710
4711/// PerformObjectArgumentInitialization - Perform initialization of
4712/// the implicit object parameter for the given Method with the given
4713/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004714ExprResult
4715Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004716 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004717 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004718 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004719 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004720 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004721 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004722
Douglas Gregor02824322011-01-26 19:30:28 +00004723 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004724 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004725 FromRecordType = PT->getPointeeType();
4726 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004727 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004728 } else {
4729 FromRecordType = From->getType();
4730 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004731 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004732 }
4733
John McCall6e9f8f62009-12-03 04:06:58 +00004734 // Note that we always use the true parent context when performing
4735 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004736 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004737 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4738 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004739 if (ICS.isBad()) {
4740 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4741 Qualifiers FromQs = FromRecordType.getQualifiers();
4742 Qualifiers ToQs = DestType.getQualifiers();
4743 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4744 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004745 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004746 diag::err_member_function_call_bad_cvr)
4747 << Method->getDeclName() << FromRecordType << (CVR - 1)
4748 << From->getSourceRange();
4749 Diag(Method->getLocation(), diag::note_previous_decl)
4750 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004751 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004752 }
4753 }
4754
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004755 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004756 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004757 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004758 }
Mike Stump11289f42009-09-09 15:08:12 +00004759
John Wiegley01296292011-04-08 18:41:53 +00004760 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4761 ExprResult FromRes =
4762 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4763 if (FromRes.isInvalid())
4764 return ExprError();
4765 From = FromRes.take();
4766 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004767
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004768 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004769 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004770 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004771 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004772}
4773
Douglas Gregor5fb53972009-01-14 15:45:31 +00004774/// TryContextuallyConvertToBool - Attempt to contextually convert the
4775/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004776static ImplicitConversionSequence
4777TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004778 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004779 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004780 // FIXME: Are these flags correct?
4781 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004782 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004783 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004784 /*CStyle=*/false,
4785 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004786}
4787
4788/// PerformContextuallyConvertToBool - Perform a contextual conversion
4789/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004790ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004791 if (checkPlaceholderForOverload(*this, From))
4792 return ExprError();
4793
John McCall5c32be02010-08-24 20:38:10 +00004794 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004795 if (!ICS.isBad())
4796 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004797
Fariborz Jahanian76197412009-11-18 18:26:29 +00004798 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004799 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004800 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004801 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004802 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004803}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004804
Richard Smithf8379a02012-01-18 23:55:52 +00004805/// Check that the specified conversion is permitted in a converted constant
4806/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4807/// is acceptable.
4808static bool CheckConvertedConstantConversions(Sema &S,
4809 StandardConversionSequence &SCS) {
4810 // Since we know that the target type is an integral or unscoped enumeration
4811 // type, most conversion kinds are impossible. All possible First and Third
4812 // conversions are fine.
4813 switch (SCS.Second) {
4814 case ICK_Identity:
4815 case ICK_Integral_Promotion:
4816 case ICK_Integral_Conversion:
4817 return true;
4818
4819 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004820 // Conversion from an integral or unscoped enumeration type to bool is
4821 // classified as ICK_Boolean_Conversion, but it's also an integral
4822 // conversion, so it's permitted in a converted constant expression.
4823 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4824 SCS.getToType(2)->isBooleanType();
4825
Richard Smithf8379a02012-01-18 23:55:52 +00004826 case ICK_Floating_Integral:
4827 case ICK_Complex_Real:
4828 return false;
4829
4830 case ICK_Lvalue_To_Rvalue:
4831 case ICK_Array_To_Pointer:
4832 case ICK_Function_To_Pointer:
4833 case ICK_NoReturn_Adjustment:
4834 case ICK_Qualification:
4835 case ICK_Compatible_Conversion:
4836 case ICK_Vector_Conversion:
4837 case ICK_Vector_Splat:
4838 case ICK_Derived_To_Base:
4839 case ICK_Pointer_Conversion:
4840 case ICK_Pointer_Member:
4841 case ICK_Block_Pointer_Conversion:
4842 case ICK_Writeback_Conversion:
4843 case ICK_Floating_Promotion:
4844 case ICK_Complex_Promotion:
4845 case ICK_Complex_Conversion:
4846 case ICK_Floating_Conversion:
4847 case ICK_TransparentUnionConversion:
4848 llvm_unreachable("unexpected second conversion kind");
4849
4850 case ICK_Num_Conversion_Kinds:
4851 break;
4852 }
4853
4854 llvm_unreachable("unknown conversion kind");
4855}
4856
4857/// CheckConvertedConstantExpression - Check that the expression From is a
4858/// converted constant expression of type T, perform the conversion and produce
4859/// the converted expression, per C++11 [expr.const]p3.
4860ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4861 llvm::APSInt &Value,
4862 CCEKind CCE) {
4863 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4864 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4865
4866 if (checkPlaceholderForOverload(*this, From))
4867 return ExprError();
4868
4869 // C++11 [expr.const]p3 with proposed wording fixes:
4870 // A converted constant expression of type T is a core constant expression,
4871 // implicitly converted to a prvalue of type T, where the converted
4872 // expression is a literal constant expression and the implicit conversion
4873 // sequence contains only user-defined conversions, lvalue-to-rvalue
4874 // conversions, integral promotions, and integral conversions other than
4875 // narrowing conversions.
4876 ImplicitConversionSequence ICS =
4877 TryImplicitConversion(From, T,
4878 /*SuppressUserConversions=*/false,
4879 /*AllowExplicit=*/false,
4880 /*InOverloadResolution=*/false,
4881 /*CStyle=*/false,
4882 /*AllowObjcWritebackConversion=*/false);
4883 StandardConversionSequence *SCS = 0;
4884 switch (ICS.getKind()) {
4885 case ImplicitConversionSequence::StandardConversion:
4886 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004887 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004888 diag::err_typecheck_converted_constant_expression_disallowed)
4889 << From->getType() << From->getSourceRange() << T;
4890 SCS = &ICS.Standard;
4891 break;
4892 case ImplicitConversionSequence::UserDefinedConversion:
4893 // We are converting from class type to an integral or enumeration type, so
4894 // the Before sequence must be trivial.
4895 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004896 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004897 diag::err_typecheck_converted_constant_expression_disallowed)
4898 << From->getType() << From->getSourceRange() << T;
4899 SCS = &ICS.UserDefined.After;
4900 break;
4901 case ImplicitConversionSequence::AmbiguousConversion:
4902 case ImplicitConversionSequence::BadConversion:
4903 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004904 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004905 diag::err_typecheck_converted_constant_expression)
4906 << From->getType() << From->getSourceRange() << T;
4907 return ExprError();
4908
4909 case ImplicitConversionSequence::EllipsisConversion:
4910 llvm_unreachable("ellipsis conversion in converted constant expression");
4911 }
4912
4913 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4914 if (Result.isInvalid())
4915 return Result;
4916
4917 // Check for a narrowing implicit conversion.
4918 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00004919 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00004920 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4921 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00004922 case NK_Variable_Narrowing:
4923 // Implicit conversion to a narrower type, and the value is not a constant
4924 // expression. We'll diagnose this in a moment.
4925 case NK_Not_Narrowing:
4926 break;
4927
4928 case NK_Constant_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004929 Diag(From->getLocStart(),
4930 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4931 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004932 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00004933 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00004934 break;
4935
4936 case NK_Type_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004937 Diag(From->getLocStart(),
4938 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4939 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004940 << CCE << /*Constant*/0 << From->getType() << T;
4941 break;
4942 }
4943
4944 // Check the expression is a constant expression.
4945 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4946 Expr::EvalResult Eval;
4947 Eval.Diag = &Notes;
4948
4949 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4950 // The expression can't be folded, so we can't keep it at this position in
4951 // the AST.
4952 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00004953 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00004954 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00004955
4956 if (Notes.empty()) {
4957 // It's a constant expression.
4958 return Result;
4959 }
Richard Smithf8379a02012-01-18 23:55:52 +00004960 }
4961
4962 // It's not a constant expression. Produce an appropriate diagnostic.
4963 if (Notes.size() == 1 &&
4964 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4965 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4966 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004967 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00004968 << CCE << From->getSourceRange();
4969 for (unsigned I = 0; I < Notes.size(); ++I)
4970 Diag(Notes[I].first, Notes[I].second);
4971 }
Richard Smith911e1422012-01-30 22:27:01 +00004972 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00004973}
4974
John McCallfec112d2011-09-09 06:11:02 +00004975/// dropPointerConversions - If the given standard conversion sequence
4976/// involves any pointer conversions, remove them. This may change
4977/// the result type of the conversion sequence.
4978static void dropPointerConversion(StandardConversionSequence &SCS) {
4979 if (SCS.Second == ICK_Pointer_Conversion) {
4980 SCS.Second = ICK_Identity;
4981 SCS.Third = ICK_Identity;
4982 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4983 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004984}
John McCall5c32be02010-08-24 20:38:10 +00004985
John McCallfec112d2011-09-09 06:11:02 +00004986/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4987/// convert the expression From to an Objective-C pointer type.
4988static ImplicitConversionSequence
4989TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4990 // Do an implicit conversion to 'id'.
4991 QualType Ty = S.Context.getObjCIdType();
4992 ImplicitConversionSequence ICS
4993 = TryImplicitConversion(S, From, Ty,
4994 // FIXME: Are these flags correct?
4995 /*SuppressUserConversions=*/false,
4996 /*AllowExplicit=*/true,
4997 /*InOverloadResolution=*/false,
4998 /*CStyle=*/false,
4999 /*AllowObjCWritebackConversion=*/false);
5000
5001 // Strip off any final conversions to 'id'.
5002 switch (ICS.getKind()) {
5003 case ImplicitConversionSequence::BadConversion:
5004 case ImplicitConversionSequence::AmbiguousConversion:
5005 case ImplicitConversionSequence::EllipsisConversion:
5006 break;
5007
5008 case ImplicitConversionSequence::UserDefinedConversion:
5009 dropPointerConversion(ICS.UserDefined.After);
5010 break;
5011
5012 case ImplicitConversionSequence::StandardConversion:
5013 dropPointerConversion(ICS.Standard);
5014 break;
5015 }
5016
5017 return ICS;
5018}
5019
5020/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5021/// conversion of the expression From to an Objective-C pointer type.
5022ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005023 if (checkPlaceholderForOverload(*this, From))
5024 return ExprError();
5025
John McCall8b07ec22010-05-15 11:32:37 +00005026 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005027 ImplicitConversionSequence ICS =
5028 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005029 if (!ICS.isBad())
5030 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005031 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005032}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005033
Richard Smith8dd34252012-02-04 07:07:42 +00005034/// Determine whether the provided type is an integral type, or an enumeration
5035/// type of a permitted flavor.
5036static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5037 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5038 : T->isIntegralOrUnscopedEnumerationType();
5039}
5040
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005041/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005042/// enumeration type.
5043///
5044/// This routine will attempt to convert an expression of class type to an
5045/// integral or enumeration type, if that class type only has a single
5046/// conversion to an integral or enumeration type.
5047///
Douglas Gregor4799d032010-06-30 00:20:43 +00005048/// \param Loc The source location of the construct that requires the
5049/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005050///
James Dennett18348b62012-06-22 08:52:37 +00005051/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005052///
James Dennett18348b62012-06-22 08:52:37 +00005053/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor4799d032010-06-30 00:20:43 +00005054///
Richard Smith8dd34252012-02-04 07:07:42 +00005055/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5056/// enumerations should be considered.
5057///
Douglas Gregor4799d032010-06-30 00:20:43 +00005058/// \returns The expression, converted to an integral or enumeration type if
5059/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005060ExprResult
John McCallb268a282010-08-23 23:25:46 +00005061Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregore2b37442012-05-04 22:38:52 +00005062 ICEConvertDiagnoser &Diagnoser,
Richard Smith8dd34252012-02-04 07:07:42 +00005063 bool AllowScopedEnumerations) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005064 // We can't perform any more checking for type-dependent expressions.
5065 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00005066 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005067
Eli Friedman1da70392012-01-26 00:26:18 +00005068 // Process placeholders immediately.
5069 if (From->hasPlaceholderType()) {
5070 ExprResult result = CheckPlaceholderExpr(From);
5071 if (result.isInvalid()) return result;
5072 From = result.take();
5073 }
5074
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005075 // If the expression already has integral or enumeration type, we're golden.
5076 QualType T = From->getType();
Richard Smith8dd34252012-02-04 07:07:42 +00005077 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedman1da70392012-01-26 00:26:18 +00005078 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005079
5080 // FIXME: Check for missing '()' if T is a function type?
5081
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005082 // If we don't have a class type in C++, there's no way we can get an
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005083 // expression of integral or enumeration type.
5084 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005085 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005086 if (!Diagnoser.Suppress)
5087 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00005088 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005089 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005090
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005091 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005092 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregore2b37442012-05-04 22:38:52 +00005093 ICEConvertDiagnoser &Diagnoser;
5094 Expr *From;
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005095
Douglas Gregore2b37442012-05-04 22:38:52 +00005096 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5097 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005098
5099 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005100 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005101 }
Douglas Gregore2b37442012-05-04 22:38:52 +00005102 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005103
5104 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCallb268a282010-08-23 23:25:46 +00005105 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005106
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005107 // Look for a conversion to an integral or enumeration type.
5108 UnresolvedSet<4> ViableConversions;
5109 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005110 std::pair<CXXRecordDecl::conversion_iterator,
5111 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005112 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005113
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005114 bool HadMultipleCandidates
5115 = (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005116
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005117 for (CXXRecordDecl::conversion_iterator
5118 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005119 if (CXXConversionDecl *Conversion
Richard Smith8dd34252012-02-04 07:07:42 +00005120 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5121 if (isIntegralOrEnumerationType(
5122 Conversion->getConversionType().getNonReferenceType(),
5123 AllowScopedEnumerations)) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005124 if (Conversion->isExplicit())
5125 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5126 else
5127 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5128 }
Richard Smith8dd34252012-02-04 07:07:42 +00005129 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005130 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005131
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005132 switch (ViableConversions.size()) {
5133 case 0:
Douglas Gregore2b37442012-05-04 22:38:52 +00005134 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005135 DeclAccessPair Found = ExplicitConversions[0];
5136 CXXConversionDecl *Conversion
5137 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005138
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005139 // The user probably meant to invoke the given explicit
5140 // conversion; use it.
5141 QualType ConvTy
5142 = Conversion->getConversionType().getNonReferenceType();
5143 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00005144 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005145
Douglas Gregore2b37442012-05-04 22:38:52 +00005146 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005147 << FixItHint::CreateInsertion(From->getLocStart(),
5148 "static_cast<" + TypeStr + ">(")
5149 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5150 ")");
Douglas Gregore2b37442012-05-04 22:38:52 +00005151 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005152
5153 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005154 // explicit conversion function.
5155 if (isSFINAEContext())
5156 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005157
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005158 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005159 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5160 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005161 if (Result.isInvalid())
5162 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005163 // Record usage of conversion in an implicit cast.
5164 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5165 CK_UserDefinedConversion,
5166 Result.get(), 0,
5167 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005168 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005169
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005170 // We'll complain below about a non-integral condition type.
5171 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005172
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005173 case 1: {
5174 // Apply this conversion.
5175 DeclAccessPair Found = ViableConversions[0];
5176 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005177
Douglas Gregor4799d032010-06-30 00:20:43 +00005178 CXXConversionDecl *Conversion
5179 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5180 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005181 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregore2b37442012-05-04 22:38:52 +00005182 if (!Diagnoser.SuppressConversion) {
Douglas Gregor4799d032010-06-30 00:20:43 +00005183 if (isSFINAEContext())
5184 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005185
Douglas Gregore2b37442012-05-04 22:38:52 +00005186 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5187 << From->getSourceRange();
Douglas Gregor4799d032010-06-30 00:20:43 +00005188 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005189
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005190 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5191 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005192 if (Result.isInvalid())
5193 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005194 // Record usage of conversion in an implicit cast.
5195 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5196 CK_UserDefinedConversion,
5197 Result.get(), 0,
5198 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005199 break;
5200 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005201
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005202 default:
Douglas Gregore2b37442012-05-04 22:38:52 +00005203 if (Diagnoser.Suppress)
5204 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005205
Douglas Gregore2b37442012-05-04 22:38:52 +00005206 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005207 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5208 CXXConversionDecl *Conv
5209 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5210 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregore2b37442012-05-04 22:38:52 +00005211 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005212 }
John McCallb268a282010-08-23 23:25:46 +00005213 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005214 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005215
Richard Smithf4c51d92012-02-04 09:53:13 +00005216 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregore2b37442012-05-04 22:38:52 +00005217 !Diagnoser.Suppress) {
5218 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5219 << From->getSourceRange();
5220 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005221
Eli Friedman1da70392012-01-26 00:26:18 +00005222 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005223}
5224
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005225/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005226/// candidate functions, using the given function call arguments. If
5227/// @p SuppressUserConversions, then don't allow user-defined
5228/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005229///
James Dennett2a4d13c2012-06-15 07:13:21 +00005230/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005231/// based on an incomplete set of function arguments. This feature is used by
5232/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005233void
5234Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005235 DeclAccessPair FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005236 llvm::ArrayRef<Expr *> Args,
Douglas Gregor2fe98832008-11-03 19:09:14 +00005237 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005238 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005239 bool PartialOverloading,
5240 bool AllowExplicit) {
Mike Stump11289f42009-09-09 15:08:12 +00005241 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005242 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005243 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005244 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005245 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005246
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005247 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005248 if (!isa<CXXConstructorDecl>(Method)) {
5249 // If we get here, it's because we're calling a member function
5250 // that is named without a member access expression (e.g.,
5251 // "this->f") that was either written explicitly or created
5252 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005253 // function, e.g., X::f(). We use an empty type for the implied
5254 // object argument (C++ [over.call.func]p3), and the acting context
5255 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005256 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005257 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005258 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005259 return;
5260 }
5261 // We treat a constructor like a non-member function, since its object
5262 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005263 }
5264
Douglas Gregorff7028a2009-11-13 23:59:09 +00005265 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005266 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005267
Douglas Gregor27381f32009-11-23 12:27:39 +00005268 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005269 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005270
Douglas Gregorffe14e32009-11-14 01:20:54 +00005271 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5272 // C++ [class.copy]p3:
5273 // A member function template is never instantiated to perform the copy
5274 // of a class object to an object of its class type.
5275 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005276 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005277 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005278 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5279 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005280 return;
5281 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005282
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005283 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005284 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005285 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005286 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005287 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005288 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005289 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005290 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005291
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005292 unsigned NumArgsInProto = Proto->getNumArgs();
5293
5294 // (C++ 13.3.2p2): A candidate function having fewer than m
5295 // parameters is viable only if it has an ellipsis in its parameter
5296 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005297 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005298 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005299 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005300 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005301 return;
5302 }
5303
5304 // (C++ 13.3.2p2): A candidate function having more than m parameters
5305 // is viable only if the (m+1)st parameter has a default argument
5306 // (8.3.6). For the purposes of overload resolution, the
5307 // parameter list is truncated on the right, so that there are
5308 // exactly m parameters.
5309 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005310 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005311 // Not enough arguments.
5312 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005313 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005314 return;
5315 }
5316
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005317 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005318 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005319 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5320 if (CheckCUDATarget(Caller, Function)) {
5321 Candidate.Viable = false;
5322 Candidate.FailureKind = ovl_fail_bad_target;
5323 return;
5324 }
5325
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005326 // Determine the implicit conversion sequences for each of the
5327 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005328 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005329 if (ArgIdx < NumArgsInProto) {
5330 // (C++ 13.3.2p3): for F to be a viable function, there shall
5331 // exist for each argument an implicit conversion sequence
5332 // (13.3.3.1) that converts that argument to the corresponding
5333 // parameter of F.
5334 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005335 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005336 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005337 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005338 /*InOverloadResolution=*/true,
5339 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005340 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005341 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005342 if (Candidate.Conversions[ArgIdx].isBad()) {
5343 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005344 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00005345 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00005346 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005347 } else {
5348 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5349 // argument for which there is no corresponding parameter is
5350 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005351 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005352 }
5353 }
5354}
5355
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005356/// \brief Add all of the function declarations in the given function set to
5357/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005358void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005359 llvm::ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005360 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005361 bool SuppressUserConversions,
5362 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005363 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005364 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5365 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005366 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005367 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005368 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005369 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005370 Args.slice(1), CandidateSet,
5371 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005372 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005373 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005374 SuppressUserConversions);
5375 } else {
John McCalla0296f72010-03-19 07:35:19 +00005376 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005377 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5378 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005379 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005380 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005381 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005382 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005383 Args[0]->Classify(Context), Args.slice(1),
5384 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005385 else
John McCalla0296f72010-03-19 07:35:19 +00005386 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005387 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005388 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005389 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005390 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005391}
5392
John McCallf0f1cf02009-11-17 07:50:12 +00005393/// AddMethodCandidate - Adds a named decl (which is some kind of
5394/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005395void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005396 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005397 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00005398 Expr **Args, unsigned NumArgs,
5399 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005400 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005401 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005402 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005403
5404 if (isa<UsingShadowDecl>(Decl))
5405 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005406
John McCallf0f1cf02009-11-17 07:50:12 +00005407 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5408 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5409 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005410 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5411 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005412 ObjectType, ObjectClassification,
5413 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005414 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005415 } else {
John McCalla0296f72010-03-19 07:35:19 +00005416 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005417 ObjectType, ObjectClassification,
5418 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorf1e46692010-04-16 17:33:27 +00005419 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005420 }
5421}
5422
Douglas Gregor436424c2008-11-18 23:14:02 +00005423/// AddMethodCandidate - Adds the given C++ member function to the set
5424/// of candidate functions, using the given function call arguments
5425/// and the object argument (@c Object). For example, in a call
5426/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5427/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5428/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005429/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005430void
John McCalla0296f72010-03-19 07:35:19 +00005431Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005432 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005433 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005434 llvm::ArrayRef<Expr *> Args,
Douglas Gregor436424c2008-11-18 23:14:02 +00005435 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005436 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00005437 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005438 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005439 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005440 assert(!isa<CXXConstructorDecl>(Method) &&
5441 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005442
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005443 if (!CandidateSet.isNewCandidate(Method))
5444 return;
5445
Douglas Gregor27381f32009-11-23 12:27:39 +00005446 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005447 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005448
Douglas Gregor436424c2008-11-18 23:14:02 +00005449 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005450 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005451 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005452 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005453 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005454 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005455 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005456
5457 unsigned NumArgsInProto = Proto->getNumArgs();
5458
5459 // (C++ 13.3.2p2): A candidate function having fewer than m
5460 // parameters is viable only if it has an ellipsis in its parameter
5461 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005462 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005463 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005464 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005465 return;
5466 }
5467
5468 // (C++ 13.3.2p2): A candidate function having more than m parameters
5469 // is viable only if the (m+1)st parameter has a default argument
5470 // (8.3.6). For the purposes of overload resolution, the
5471 // parameter list is truncated on the right, so that there are
5472 // exactly m parameters.
5473 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005474 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005475 // Not enough arguments.
5476 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005477 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005478 return;
5479 }
5480
5481 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005482
John McCall6e9f8f62009-12-03 04:06:58 +00005483 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005484 // The implicit object argument is ignored.
5485 Candidate.IgnoreObjectArgument = true;
5486 else {
5487 // Determine the implicit conversion sequence for the object
5488 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005489 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005490 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5491 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005492 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005493 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005494 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005495 return;
5496 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005497 }
5498
5499 // Determine the implicit conversion sequences for each of the
5500 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005501 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005502 if (ArgIdx < NumArgsInProto) {
5503 // (C++ 13.3.2p3): for F to be a viable function, there shall
5504 // exist for each argument an implicit conversion sequence
5505 // (13.3.3.1) that converts that argument to the corresponding
5506 // parameter of F.
5507 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005508 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005509 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005510 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005511 /*InOverloadResolution=*/true,
5512 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005513 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005514 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005515 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005516 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005517 break;
5518 }
5519 } else {
5520 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5521 // argument for which there is no corresponding parameter is
5522 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005523 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005524 }
5525 }
5526}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005527
Douglas Gregor97628d62009-08-21 00:16:32 +00005528/// \brief Add a C++ member function template as a candidate to the candidate
5529/// set, using template argument deduction to produce an appropriate member
5530/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005531void
Douglas Gregor97628d62009-08-21 00:16:32 +00005532Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005533 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005534 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005535 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005536 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005537 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005538 llvm::ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005539 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005540 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005541 if (!CandidateSet.isNewCandidate(MethodTmpl))
5542 return;
5543
Douglas Gregor97628d62009-08-21 00:16:32 +00005544 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005545 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005546 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005547 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005548 // candidate functions in the usual way.113) A given name can refer to one
5549 // or more function templates and also to a set of overloaded non-template
5550 // functions. In such a case, the candidate functions generated from each
5551 // function template are combined with the set of non-template candidate
5552 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005553 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005554 FunctionDecl *Specialization = 0;
5555 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005556 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5557 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005558 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005559 Candidate.FoundDecl = FoundDecl;
5560 Candidate.Function = MethodTmpl->getTemplatedDecl();
5561 Candidate.Viable = false;
5562 Candidate.FailureKind = ovl_fail_bad_deduction;
5563 Candidate.IsSurrogate = false;
5564 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005565 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005566 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005567 Info);
5568 return;
5569 }
Mike Stump11289f42009-09-09 15:08:12 +00005570
Douglas Gregor97628d62009-08-21 00:16:32 +00005571 // Add the function template specialization produced by template argument
5572 // deduction as a candidate.
5573 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005574 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005575 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005576 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005577 ActingContext, ObjectType, ObjectClassification, Args,
5578 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005579}
5580
Douglas Gregor05155d82009-08-21 23:19:43 +00005581/// \brief Add a C++ function template specialization as a candidate
5582/// in the candidate set, using template argument deduction to produce
5583/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005584void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005585Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005586 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005587 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005588 llvm::ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005589 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005590 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005591 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5592 return;
5593
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005594 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005595 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005596 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005597 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005598 // candidate functions in the usual way.113) A given name can refer to one
5599 // or more function templates and also to a set of overloaded non-template
5600 // functions. In such a case, the candidate functions generated from each
5601 // function template are combined with the set of non-template candidate
5602 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005603 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005604 FunctionDecl *Specialization = 0;
5605 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005606 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5607 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005608 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005609 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005610 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5611 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005612 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005613 Candidate.IsSurrogate = false;
5614 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005615 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005616 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005617 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005618 return;
5619 }
Mike Stump11289f42009-09-09 15:08:12 +00005620
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005621 // Add the function template specialization produced by template argument
5622 // deduction as a candidate.
5623 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005624 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005625 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005626}
Mike Stump11289f42009-09-09 15:08:12 +00005627
Douglas Gregora1f013e2008-11-07 22:36:19 +00005628/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005629/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005630/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005631/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005632/// (which may or may not be the same type as the type that the
5633/// conversion function produces).
5634void
5635Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005636 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005637 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005638 Expr *From, QualType ToType,
5639 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005640 assert(!Conversion->getDescribedFunctionTemplate() &&
5641 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005642 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005643 if (!CandidateSet.isNewCandidate(Conversion))
5644 return;
5645
Douglas Gregor27381f32009-11-23 12:27:39 +00005646 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005647 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005648
Douglas Gregora1f013e2008-11-07 22:36:19 +00005649 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005650 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005651 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005652 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005653 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005654 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005655 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005656 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005657 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005658 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005659 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005660
Douglas Gregor6affc782010-08-19 15:37:02 +00005661 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005662 // For conversion functions, the function is considered to be a member of
5663 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005664 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005665 //
5666 // Determine the implicit conversion sequence for the implicit
5667 // object parameter.
5668 QualType ImplicitParamType = From->getType();
5669 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5670 ImplicitParamType = FromPtrType->getPointeeType();
5671 CXXRecordDecl *ConversionContext
5672 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005673
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005674 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005675 = TryObjectArgumentInitialization(*this, From->getType(),
5676 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005677 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005678
John McCall0d1da222010-01-12 00:44:57 +00005679 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005680 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005681 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005682 return;
5683 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005684
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005685 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005686 // derived to base as such conversions are given Conversion Rank. They only
5687 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5688 QualType FromCanon
5689 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5690 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5691 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5692 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005693 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005694 return;
5695 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005696
Douglas Gregora1f013e2008-11-07 22:36:19 +00005697 // To determine what the conversion from the result of calling the
5698 // conversion function to the type we're eventually trying to
5699 // convert to (ToType), we need to synthesize a call to the
5700 // conversion function and attempt copy initialization from it. This
5701 // makes sure that we get the right semantics with respect to
5702 // lvalues/rvalues and the type. Fortunately, we can allocate this
5703 // call on the stack and we don't need its arguments to be
5704 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00005705 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005706 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005707 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5708 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005709 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005710 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005711
Richard Smith48d24642011-07-13 22:53:21 +00005712 QualType ConversionType = Conversion->getConversionType();
5713 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005714 Candidate.Viable = false;
5715 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5716 return;
5717 }
5718
Richard Smith48d24642011-07-13 22:53:21 +00005719 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005720
Mike Stump11289f42009-09-09 15:08:12 +00005721 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005722 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5723 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005724 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Benjamin Kramerc215e762012-08-24 11:54:20 +00005725 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005726 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005727 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005728 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005729 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005730 /*InOverloadResolution=*/false,
5731 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005732
John McCall0d1da222010-01-12 00:44:57 +00005733 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005734 case ImplicitConversionSequence::StandardConversion:
5735 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005736
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005737 // C++ [over.ics.user]p3:
5738 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005739 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005740 // shall have exact match rank.
5741 if (Conversion->getPrimaryTemplate() &&
5742 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5743 Candidate.Viable = false;
5744 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5745 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005746
Douglas Gregorcba72b12011-01-21 05:18:22 +00005747 // C++0x [dcl.init.ref]p5:
5748 // In the second case, if the reference is an rvalue reference and
5749 // the second standard conversion sequence of the user-defined
5750 // conversion sequence includes an lvalue-to-rvalue conversion, the
5751 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005752 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005753 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5754 Candidate.Viable = false;
5755 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5756 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005757 break;
5758
5759 case ImplicitConversionSequence::BadConversion:
5760 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005761 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005762 break;
5763
5764 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005765 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005766 "Can only end up with a standard conversion sequence or failure");
5767 }
5768}
5769
Douglas Gregor05155d82009-08-21 23:19:43 +00005770/// \brief Adds a conversion function template specialization
5771/// candidate to the overload set, using template argument deduction
5772/// to deduce the template arguments of the conversion function
5773/// template from the type that we are converting to (C++
5774/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005775void
Douglas Gregor05155d82009-08-21 23:19:43 +00005776Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005777 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005778 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005779 Expr *From, QualType ToType,
5780 OverloadCandidateSet &CandidateSet) {
5781 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5782 "Only conversion function templates permitted here");
5783
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005784 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5785 return;
5786
Craig Toppere6706e42012-09-19 02:26:47 +00005787 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005788 CXXConversionDecl *Specialization = 0;
5789 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005790 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005791 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005792 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005793 Candidate.FoundDecl = FoundDecl;
5794 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5795 Candidate.Viable = false;
5796 Candidate.FailureKind = ovl_fail_bad_deduction;
5797 Candidate.IsSurrogate = false;
5798 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005799 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005800 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005801 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005802 return;
5803 }
Mike Stump11289f42009-09-09 15:08:12 +00005804
Douglas Gregor05155d82009-08-21 23:19:43 +00005805 // Add the conversion function template specialization produced by
5806 // template argument deduction as a candidate.
5807 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005808 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005809 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005810}
5811
Douglas Gregorab7897a2008-11-19 22:57:39 +00005812/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5813/// converts the given @c Object to a function pointer via the
5814/// conversion function @c Conversion, and then attempts to call it
5815/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5816/// the type of function that we'll eventually be calling.
5817void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005818 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005819 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005820 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005821 Expr *Object,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005822 llvm::ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005823 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005824 if (!CandidateSet.isNewCandidate(Conversion))
5825 return;
5826
Douglas Gregor27381f32009-11-23 12:27:39 +00005827 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005828 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005829
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005830 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005831 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005832 Candidate.Function = 0;
5833 Candidate.Surrogate = Conversion;
5834 Candidate.Viable = true;
5835 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005836 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005837 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005838
5839 // Determine the implicit conversion sequence for the implicit
5840 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005841 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005842 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005843 Object->Classify(Context),
5844 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005845 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005846 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005847 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005848 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005849 return;
5850 }
5851
5852 // The first conversion is actually a user-defined conversion whose
5853 // first conversion is ObjectInit's standard conversion (which is
5854 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005855 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005856 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005857 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005858 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005859 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005860 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005861 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005862 = Candidate.Conversions[0].UserDefined.Before;
5863 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5864
Mike Stump11289f42009-09-09 15:08:12 +00005865 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005866 unsigned NumArgsInProto = Proto->getNumArgs();
5867
5868 // (C++ 13.3.2p2): A candidate function having fewer than m
5869 // parameters is viable only if it has an ellipsis in its parameter
5870 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005871 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005872 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005873 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005874 return;
5875 }
5876
5877 // Function types don't have any default arguments, so just check if
5878 // we have enough arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005879 if (Args.size() < NumArgsInProto) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005880 // Not enough arguments.
5881 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005882 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005883 return;
5884 }
5885
5886 // Determine the implicit conversion sequences for each of the
5887 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005888 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005889 if (ArgIdx < NumArgsInProto) {
5890 // (C++ 13.3.2p3): for F to be a viable function, there shall
5891 // exist for each argument an implicit conversion sequence
5892 // (13.3.3.1) that converts that argument to the corresponding
5893 // parameter of F.
5894 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005895 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005896 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005897 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005898 /*InOverloadResolution=*/false,
5899 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005900 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005901 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005902 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005903 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005904 break;
5905 }
5906 } else {
5907 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5908 // argument for which there is no corresponding parameter is
5909 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005910 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005911 }
5912 }
5913}
5914
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005915/// \brief Add overload candidates for overloaded operators that are
5916/// member functions.
5917///
5918/// Add the overloaded operator candidates that are member functions
5919/// for the operator Op that was used in an operator expression such
5920/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5921/// CandidateSet will store the added overload candidates. (C++
5922/// [over.match.oper]).
5923void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5924 SourceLocation OpLoc,
5925 Expr **Args, unsigned NumArgs,
5926 OverloadCandidateSet& CandidateSet,
5927 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005928 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5929
5930 // C++ [over.match.oper]p3:
5931 // For a unary operator @ with an operand of a type whose
5932 // cv-unqualified version is T1, and for a binary operator @ with
5933 // a left operand of a type whose cv-unqualified version is T1 and
5934 // a right operand of a type whose cv-unqualified version is T2,
5935 // three sets of candidate functions, designated member
5936 // candidates, non-member candidates and built-in candidates, are
5937 // constructed as follows:
5938 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005939
5940 // -- If T1 is a class type, the set of member candidates is the
5941 // result of the qualified lookup of T1::operator@
5942 // (13.3.1.1.1); otherwise, the set of member candidates is
5943 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005944 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005945 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005946 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005947 return;
Mike Stump11289f42009-09-09 15:08:12 +00005948
John McCall27b18f82009-11-17 02:14:36 +00005949 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5950 LookupQualifiedName(Operators, T1Rec->getDecl());
5951 Operators.suppressDiagnostics();
5952
Mike Stump11289f42009-09-09 15:08:12 +00005953 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005954 OperEnd = Operators.end();
5955 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005956 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005957 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005958 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005959 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005960 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005961 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005962}
5963
Douglas Gregora11693b2008-11-12 17:17:38 +00005964/// AddBuiltinCandidate - Add a candidate for a built-in
5965/// operator. ResultTy and ParamTys are the result and parameter types
5966/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005967/// arguments being passed to the candidate. IsAssignmentOperator
5968/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005969/// operator. NumContextualBoolArguments is the number of arguments
5970/// (at the beginning of the argument list) that will be contextually
5971/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005972void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005973 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005974 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005975 bool IsAssignmentOperator,
5976 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005977 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005978 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005979
Douglas Gregora11693b2008-11-12 17:17:38 +00005980 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005981 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005982 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005983 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005984 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005985 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005986 Candidate.BuiltinTypes.ResultTy = ResultTy;
5987 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5988 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5989
5990 // Determine the implicit conversion sequences for each of the
5991 // arguments.
5992 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005993 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005994 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005995 // C++ [over.match.oper]p4:
5996 // For the built-in assignment operators, conversions of the
5997 // left operand are restricted as follows:
5998 // -- no temporaries are introduced to hold the left operand, and
5999 // -- no user-defined conversions are applied to the left
6000 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006001 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006002 //
6003 // We block these conversions by turning off user-defined
6004 // conversions, since that is the only way that initialization of
6005 // a reference to a non-class type can occur from something that
6006 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006007 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006008 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006009 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006010 Candidate.Conversions[ArgIdx]
6011 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006012 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006013 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006014 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006015 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006016 /*InOverloadResolution=*/false,
6017 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006018 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006019 }
John McCall0d1da222010-01-12 00:44:57 +00006020 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006021 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006022 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006023 break;
6024 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006025 }
6026}
6027
6028/// BuiltinCandidateTypeSet - A set of types that will be used for the
6029/// candidate operator functions for built-in operators (C++
6030/// [over.built]). The types are separated into pointer types and
6031/// enumeration types.
6032class BuiltinCandidateTypeSet {
6033 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006034 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006035
6036 /// PointerTypes - The set of pointer types that will be used in the
6037 /// built-in candidates.
6038 TypeSet PointerTypes;
6039
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006040 /// MemberPointerTypes - The set of member pointer types that will be
6041 /// used in the built-in candidates.
6042 TypeSet MemberPointerTypes;
6043
Douglas Gregora11693b2008-11-12 17:17:38 +00006044 /// EnumerationTypes - The set of enumeration types that will be
6045 /// used in the built-in candidates.
6046 TypeSet EnumerationTypes;
6047
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006048 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006049 /// candidates.
6050 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006051
6052 /// \brief A flag indicating non-record types are viable candidates
6053 bool HasNonRecordTypes;
6054
6055 /// \brief A flag indicating whether either arithmetic or enumeration types
6056 /// were present in the candidate set.
6057 bool HasArithmeticOrEnumeralTypes;
6058
Douglas Gregor80af3132011-05-21 23:15:46 +00006059 /// \brief A flag indicating whether the nullptr type was present in the
6060 /// candidate set.
6061 bool HasNullPtrType;
6062
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006063 /// Sema - The semantic analysis instance where we are building the
6064 /// candidate type set.
6065 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006066
Douglas Gregora11693b2008-11-12 17:17:38 +00006067 /// Context - The AST context in which we will build the type sets.
6068 ASTContext &Context;
6069
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006070 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6071 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006072 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006073
6074public:
6075 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006076 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006077
Mike Stump11289f42009-09-09 15:08:12 +00006078 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006079 : HasNonRecordTypes(false),
6080 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006081 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006082 SemaRef(SemaRef),
6083 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006084
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006085 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006086 SourceLocation Loc,
6087 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006088 bool AllowExplicitConversions,
6089 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006090
6091 /// pointer_begin - First pointer type found;
6092 iterator pointer_begin() { return PointerTypes.begin(); }
6093
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006094 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006095 iterator pointer_end() { return PointerTypes.end(); }
6096
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006097 /// member_pointer_begin - First member pointer type found;
6098 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6099
6100 /// member_pointer_end - Past the last member pointer type found;
6101 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6102
Douglas Gregora11693b2008-11-12 17:17:38 +00006103 /// enumeration_begin - First enumeration type found;
6104 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6105
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006106 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006107 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006108
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006109 iterator vector_begin() { return VectorTypes.begin(); }
6110 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006111
6112 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6113 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006114 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006115};
6116
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006117/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006118/// the set of pointer types along with any more-qualified variants of
6119/// that type. For example, if @p Ty is "int const *", this routine
6120/// will add "int const *", "int const volatile *", "int const
6121/// restrict *", and "int const volatile restrict *" to the set of
6122/// pointer types. Returns true if the add of @p Ty itself succeeded,
6123/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006124///
6125/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006126bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006127BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6128 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006129
Douglas Gregora11693b2008-11-12 17:17:38 +00006130 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006131 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006132 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006133
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006134 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006135 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006136 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006137 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006138 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6139 PointeeTy = PTy->getPointeeType();
6140 buildObjCPtr = true;
6141 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006142 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006143 }
6144
Sebastian Redl4990a632009-11-18 20:39:26 +00006145 // Don't add qualified variants of arrays. For one, they're not allowed
6146 // (the qualifier would sink to the element type), and for another, the
6147 // only overload situation where it matters is subscript or pointer +- int,
6148 // and those shouldn't have qualifier variants anyway.
6149 if (PointeeTy->isArrayType())
6150 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006151
John McCall8ccfcb52009-09-24 19:53:00 +00006152 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006153 bool hasVolatile = VisibleQuals.hasVolatile();
6154 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006155
John McCall8ccfcb52009-09-24 19:53:00 +00006156 // Iterate through all strict supersets of BaseCVR.
6157 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6158 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006159 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006160 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006161
6162 // Skip over restrict if no restrict found anywhere in the types, or if
6163 // the type cannot be restrict-qualified.
6164 if ((CVR & Qualifiers::Restrict) &&
6165 (!hasRestrict ||
6166 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6167 continue;
6168
6169 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006170 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006171
6172 // Build qualified pointer type.
6173 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006174 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006175 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006176 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006177 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6178
6179 // Insert qualified pointer type.
6180 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006181 }
6182
6183 return true;
6184}
6185
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006186/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6187/// to the set of pointer types along with any more-qualified variants of
6188/// that type. For example, if @p Ty is "int const *", this routine
6189/// will add "int const *", "int const volatile *", "int const
6190/// restrict *", and "int const volatile restrict *" to the set of
6191/// pointer types. Returns true if the add of @p Ty itself succeeded,
6192/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006193///
6194/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006195bool
6196BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6197 QualType Ty) {
6198 // Insert this type.
6199 if (!MemberPointerTypes.insert(Ty))
6200 return false;
6201
John McCall8ccfcb52009-09-24 19:53:00 +00006202 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6203 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006204
John McCall8ccfcb52009-09-24 19:53:00 +00006205 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006206 // Don't add qualified variants of arrays. For one, they're not allowed
6207 // (the qualifier would sink to the element type), and for another, the
6208 // only overload situation where it matters is subscript or pointer +- int,
6209 // and those shouldn't have qualifier variants anyway.
6210 if (PointeeTy->isArrayType())
6211 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006212 const Type *ClassTy = PointerTy->getClass();
6213
6214 // Iterate through all strict supersets of the pointee type's CVR
6215 // qualifiers.
6216 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6217 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6218 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006219
John McCall8ccfcb52009-09-24 19:53:00 +00006220 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006221 MemberPointerTypes.insert(
6222 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006223 }
6224
6225 return true;
6226}
6227
Douglas Gregora11693b2008-11-12 17:17:38 +00006228/// AddTypesConvertedFrom - Add each of the types to which the type @p
6229/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006230/// primarily interested in pointer types and enumeration types. We also
6231/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006232/// AllowUserConversions is true if we should look at the conversion
6233/// functions of a class type, and AllowExplicitConversions if we
6234/// should also include the explicit conversion functions of a class
6235/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006236void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006237BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006238 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006239 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006240 bool AllowExplicitConversions,
6241 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006242 // Only deal with canonical types.
6243 Ty = Context.getCanonicalType(Ty);
6244
6245 // Look through reference types; they aren't part of the type of an
6246 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006247 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006248 Ty = RefTy->getPointeeType();
6249
John McCall33ddac02011-01-19 10:06:00 +00006250 // If we're dealing with an array type, decay to the pointer.
6251 if (Ty->isArrayType())
6252 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6253
6254 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006255 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006256
Chandler Carruth00a38332010-12-13 01:44:01 +00006257 // Flag if we ever add a non-record type.
6258 const RecordType *TyRec = Ty->getAs<RecordType>();
6259 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6260
Chandler Carruth00a38332010-12-13 01:44:01 +00006261 // Flag if we encounter an arithmetic type.
6262 HasArithmeticOrEnumeralTypes =
6263 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6264
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006265 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6266 PointerTypes.insert(Ty);
6267 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006268 // Insert our type, and its more-qualified variants, into the set
6269 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006270 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006271 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006272 } else if (Ty->isMemberPointerType()) {
6273 // Member pointers are far easier, since the pointee can't be converted.
6274 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6275 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006276 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006277 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006278 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006279 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006280 // We treat vector types as arithmetic types in many contexts as an
6281 // extension.
6282 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006283 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006284 } else if (Ty->isNullPtrType()) {
6285 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006286 } else if (AllowUserConversions && TyRec) {
6287 // No conversion functions in incomplete types.
6288 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6289 return;
Mike Stump11289f42009-09-09 15:08:12 +00006290
Chandler Carruth00a38332010-12-13 01:44:01 +00006291 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006292 std::pair<CXXRecordDecl::conversion_iterator,
6293 CXXRecordDecl::conversion_iterator>
6294 Conversions = ClassDecl->getVisibleConversionFunctions();
6295 for (CXXRecordDecl::conversion_iterator
6296 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006297 NamedDecl *D = I.getDecl();
6298 if (isa<UsingShadowDecl>(D))
6299 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006300
Chandler Carruth00a38332010-12-13 01:44:01 +00006301 // Skip conversion function templates; they don't tell us anything
6302 // about which builtin types we can convert to.
6303 if (isa<FunctionTemplateDecl>(D))
6304 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006305
Chandler Carruth00a38332010-12-13 01:44:01 +00006306 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6307 if (AllowExplicitConversions || !Conv->isExplicit()) {
6308 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6309 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006310 }
6311 }
6312 }
6313}
6314
Douglas Gregor84605ae2009-08-24 13:43:27 +00006315/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6316/// the volatile- and non-volatile-qualified assignment operators for the
6317/// given type to the candidate set.
6318static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6319 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00006320 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006321 unsigned NumArgs,
6322 OverloadCandidateSet &CandidateSet) {
6323 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006324
Douglas Gregor84605ae2009-08-24 13:43:27 +00006325 // T& operator=(T&, T)
6326 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6327 ParamTypes[1] = T;
6328 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6329 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006330
Douglas Gregor84605ae2009-08-24 13:43:27 +00006331 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6332 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006333 ParamTypes[0]
6334 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006335 ParamTypes[1] = T;
6336 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006337 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006338 }
6339}
Mike Stump11289f42009-09-09 15:08:12 +00006340
Sebastian Redl1054fae2009-10-25 17:03:50 +00006341/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6342/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006343static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6344 Qualifiers VRQuals;
6345 const RecordType *TyRec;
6346 if (const MemberPointerType *RHSMPType =
6347 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006348 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006349 else
6350 TyRec = ArgExpr->getType()->getAs<RecordType>();
6351 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006352 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006353 VRQuals.addVolatile();
6354 VRQuals.addRestrict();
6355 return VRQuals;
6356 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006357
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006358 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006359 if (!ClassDecl->hasDefinition())
6360 return VRQuals;
6361
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006362 std::pair<CXXRecordDecl::conversion_iterator,
6363 CXXRecordDecl::conversion_iterator>
6364 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006365
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006366 for (CXXRecordDecl::conversion_iterator
6367 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006368 NamedDecl *D = I.getDecl();
6369 if (isa<UsingShadowDecl>(D))
6370 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6371 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006372 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6373 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6374 CanTy = ResTypeRef->getPointeeType();
6375 // Need to go down the pointer/mempointer chain and add qualifiers
6376 // as see them.
6377 bool done = false;
6378 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006379 if (CanTy.isRestrictQualified())
6380 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006381 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6382 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006383 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006384 CanTy->getAs<MemberPointerType>())
6385 CanTy = ResTypeMPtr->getPointeeType();
6386 else
6387 done = true;
6388 if (CanTy.isVolatileQualified())
6389 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006390 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6391 return VRQuals;
6392 }
6393 }
6394 }
6395 return VRQuals;
6396}
John McCall52872982010-11-13 05:51:15 +00006397
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006398namespace {
John McCall52872982010-11-13 05:51:15 +00006399
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006400/// \brief Helper class to manage the addition of builtin operator overload
6401/// candidates. It provides shared state and utility methods used throughout
6402/// the process, as well as a helper method to add each group of builtin
6403/// operator overloads from the standard to a candidate set.
6404class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006405 // Common instance state available to all overload candidate addition methods.
6406 Sema &S;
6407 Expr **Args;
6408 unsigned NumArgs;
6409 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006410 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006411 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006412 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006413
Chandler Carruthc6586e52010-12-12 10:35:00 +00006414 // Define some constants used to index and iterate over the arithemetic types
6415 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006416 // The "promoted arithmetic types" are the arithmetic
6417 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006418 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00006419 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00006420 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00006421 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00006422 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00006423 LastPromotedArithmeticType = 11;
6424 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00006425
Chandler Carruthc6586e52010-12-12 10:35:00 +00006426 /// \brief Get the canonical type for a given arithmetic type index.
6427 CanQualType getArithmeticType(unsigned index) {
6428 assert(index < NumArithmeticTypes);
6429 static CanQualType ASTContext::* const
6430 ArithmeticTypes[NumArithmeticTypes] = {
6431 // Start of promoted types.
6432 &ASTContext::FloatTy,
6433 &ASTContext::DoubleTy,
6434 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006435
Chandler Carruthc6586e52010-12-12 10:35:00 +00006436 // Start of integral types.
6437 &ASTContext::IntTy,
6438 &ASTContext::LongTy,
6439 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006440 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006441 &ASTContext::UnsignedIntTy,
6442 &ASTContext::UnsignedLongTy,
6443 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006444 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006445 // End of promoted types.
6446
6447 &ASTContext::BoolTy,
6448 &ASTContext::CharTy,
6449 &ASTContext::WCharTy,
6450 &ASTContext::Char16Ty,
6451 &ASTContext::Char32Ty,
6452 &ASTContext::SignedCharTy,
6453 &ASTContext::ShortTy,
6454 &ASTContext::UnsignedCharTy,
6455 &ASTContext::UnsignedShortTy,
6456 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00006457 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00006458 };
6459 return S.Context.*ArithmeticTypes[index];
6460 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006461
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006462 /// \brief Gets the canonical type resulting from the usual arithemetic
6463 /// converions for the given arithmetic types.
6464 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6465 // Accelerator table for performing the usual arithmetic conversions.
6466 // The rules are basically:
6467 // - if either is floating-point, use the wider floating-point
6468 // - if same signedness, use the higher rank
6469 // - if same size, use unsigned of the higher rank
6470 // - use the larger type
6471 // These rules, together with the axiom that higher ranks are
6472 // never smaller, are sufficient to precompute all of these results
6473 // *except* when dealing with signed types of higher rank.
6474 // (we could precompute SLL x UI for all known platforms, but it's
6475 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00006476 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006477 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00006478 Dep=-1,
6479 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006480 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00006481 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006482 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00006483/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6484/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6485/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6486/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6487/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6488/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6489/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6490/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6491/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6492/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6493/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006494 };
6495
6496 assert(L < LastPromotedArithmeticType);
6497 assert(R < LastPromotedArithmeticType);
6498 int Idx = ConversionsTable[L][R];
6499
6500 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006501 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006502
6503 // Slow path: we need to compare widths.
6504 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006505 CanQualType LT = getArithmeticType(L),
6506 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006507 unsigned LW = S.Context.getIntWidth(LT),
6508 RW = S.Context.getIntWidth(RT);
6509
6510 // If they're different widths, use the signed type.
6511 if (LW > RW) return LT;
6512 else if (LW < RW) return RT;
6513
6514 // Otherwise, use the unsigned type of the signed type's rank.
6515 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6516 assert(L == SLL || R == SLL);
6517 return S.Context.UnsignedLongLongTy;
6518 }
6519
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006520 /// \brief Helper method to factor out the common pattern of adding overloads
6521 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006522 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006523 bool HasVolatile,
6524 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006525 QualType ParamTypes[2] = {
6526 S.Context.getLValueReferenceType(CandidateTy),
6527 S.Context.IntTy
6528 };
6529
6530 // Non-volatile version.
6531 if (NumArgs == 1)
6532 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6533 else
6534 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6535
6536 // Use a heuristic to reduce number of builtin candidates in the set:
6537 // add volatile version only if there are conversions to a volatile type.
6538 if (HasVolatile) {
6539 ParamTypes[0] =
6540 S.Context.getLValueReferenceType(
6541 S.Context.getVolatileType(CandidateTy));
6542 if (NumArgs == 1)
6543 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6544 else
6545 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6546 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00006547
6548 // Add restrict version only if there are conversions to a restrict type
6549 // and our candidate type is a non-restrict-qualified pointer.
6550 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6551 !CandidateTy.isRestrictQualified()) {
6552 ParamTypes[0]
6553 = S.Context.getLValueReferenceType(
6554 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6555 if (NumArgs == 1)
6556 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6557 else
6558 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6559
6560 if (HasVolatile) {
6561 ParamTypes[0]
6562 = S.Context.getLValueReferenceType(
6563 S.Context.getCVRQualifiedType(CandidateTy,
6564 (Qualifiers::Volatile |
6565 Qualifiers::Restrict)));
6566 if (NumArgs == 1)
6567 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6568 CandidateSet);
6569 else
6570 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6571 }
6572 }
6573
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006574 }
6575
6576public:
6577 BuiltinOperatorOverloadBuilder(
6578 Sema &S, Expr **Args, unsigned NumArgs,
6579 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006580 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006581 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006582 OverloadCandidateSet &CandidateSet)
6583 : S(S), Args(Args), NumArgs(NumArgs),
6584 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006585 HasArithmeticOrEnumeralCandidateType(
6586 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006587 CandidateTypes(CandidateTypes),
6588 CandidateSet(CandidateSet) {
6589 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006590 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006591 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006592 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00006593 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006594 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006595 assert(getArithmeticType(FirstPromotedArithmeticType)
6596 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006597 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006598 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00006599 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006600 "Invalid last promoted arithmetic type");
6601 }
6602
6603 // C++ [over.built]p3:
6604 //
6605 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6606 // is either volatile or empty, there exist candidate operator
6607 // functions of the form
6608 //
6609 // VQ T& operator++(VQ T&);
6610 // T operator++(VQ T&, int);
6611 //
6612 // C++ [over.built]p4:
6613 //
6614 // For every pair (T, VQ), where T is an arithmetic type other
6615 // than bool, and VQ is either volatile or empty, there exist
6616 // candidate operator functions of the form
6617 //
6618 // VQ T& operator--(VQ T&);
6619 // T operator--(VQ T&, int);
6620 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006621 if (!HasArithmeticOrEnumeralCandidateType)
6622 return;
6623
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006624 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6625 Arith < NumArithmeticTypes; ++Arith) {
6626 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00006627 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00006628 VisibleTypeConversionsQuals.hasVolatile(),
6629 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006630 }
6631 }
6632
6633 // C++ [over.built]p5:
6634 //
6635 // For every pair (T, VQ), where T is a cv-qualified or
6636 // cv-unqualified object type, and VQ is either volatile or
6637 // empty, there exist candidate operator functions of the form
6638 //
6639 // T*VQ& operator++(T*VQ&);
6640 // T*VQ& operator--(T*VQ&);
6641 // T* operator++(T*VQ&, int);
6642 // T* operator--(T*VQ&, int);
6643 void addPlusPlusMinusMinusPointerOverloads() {
6644 for (BuiltinCandidateTypeSet::iterator
6645 Ptr = CandidateTypes[0].pointer_begin(),
6646 PtrEnd = CandidateTypes[0].pointer_end();
6647 Ptr != PtrEnd; ++Ptr) {
6648 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00006649 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006650 continue;
6651
6652 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006653 (!(*Ptr).isVolatileQualified() &&
6654 VisibleTypeConversionsQuals.hasVolatile()),
6655 (!(*Ptr).isRestrictQualified() &&
6656 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006657 }
6658 }
6659
6660 // C++ [over.built]p6:
6661 // For every cv-qualified or cv-unqualified object type T, there
6662 // exist candidate operator functions of the form
6663 //
6664 // T& operator*(T*);
6665 //
6666 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006667 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00006668 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006669 // T& operator*(T*);
6670 void addUnaryStarPointerOverloads() {
6671 for (BuiltinCandidateTypeSet::iterator
6672 Ptr = CandidateTypes[0].pointer_begin(),
6673 PtrEnd = CandidateTypes[0].pointer_end();
6674 Ptr != PtrEnd; ++Ptr) {
6675 QualType ParamTy = *Ptr;
6676 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006677 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6678 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006679
Douglas Gregor02824322011-01-26 19:30:28 +00006680 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6681 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6682 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006683
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006684 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6685 &ParamTy, Args, 1, CandidateSet);
6686 }
6687 }
6688
6689 // C++ [over.built]p9:
6690 // For every promoted arithmetic type T, there exist candidate
6691 // operator functions of the form
6692 //
6693 // T operator+(T);
6694 // T operator-(T);
6695 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006696 if (!HasArithmeticOrEnumeralCandidateType)
6697 return;
6698
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006699 for (unsigned Arith = FirstPromotedArithmeticType;
6700 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006701 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006702 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6703 }
6704
6705 // Extension: We also add these operators for vector types.
6706 for (BuiltinCandidateTypeSet::iterator
6707 Vec = CandidateTypes[0].vector_begin(),
6708 VecEnd = CandidateTypes[0].vector_end();
6709 Vec != VecEnd; ++Vec) {
6710 QualType VecTy = *Vec;
6711 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6712 }
6713 }
6714
6715 // C++ [over.built]p8:
6716 // For every type T, there exist candidate operator functions of
6717 // the form
6718 //
6719 // T* operator+(T*);
6720 void addUnaryPlusPointerOverloads() {
6721 for (BuiltinCandidateTypeSet::iterator
6722 Ptr = CandidateTypes[0].pointer_begin(),
6723 PtrEnd = CandidateTypes[0].pointer_end();
6724 Ptr != PtrEnd; ++Ptr) {
6725 QualType ParamTy = *Ptr;
6726 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6727 }
6728 }
6729
6730 // C++ [over.built]p10:
6731 // For every promoted integral type T, there exist candidate
6732 // operator functions of the form
6733 //
6734 // T operator~(T);
6735 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006736 if (!HasArithmeticOrEnumeralCandidateType)
6737 return;
6738
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006739 for (unsigned Int = FirstPromotedIntegralType;
6740 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006741 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006742 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6743 }
6744
6745 // Extension: We also add this operator for vector types.
6746 for (BuiltinCandidateTypeSet::iterator
6747 Vec = CandidateTypes[0].vector_begin(),
6748 VecEnd = CandidateTypes[0].vector_end();
6749 Vec != VecEnd; ++Vec) {
6750 QualType VecTy = *Vec;
6751 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6752 }
6753 }
6754
6755 // C++ [over.match.oper]p16:
6756 // For every pointer to member type T, there exist candidate operator
6757 // functions of the form
6758 //
6759 // bool operator==(T,T);
6760 // bool operator!=(T,T);
6761 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6762 /// Set of (canonical) types that we've already handled.
6763 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6764
6765 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6766 for (BuiltinCandidateTypeSet::iterator
6767 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6768 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6769 MemPtr != MemPtrEnd;
6770 ++MemPtr) {
6771 // Don't add the same builtin candidate twice.
6772 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6773 continue;
6774
6775 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6776 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6777 CandidateSet);
6778 }
6779 }
6780 }
6781
6782 // C++ [over.built]p15:
6783 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006784 // For every T, where T is an enumeration type, a pointer type, or
6785 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006786 //
6787 // bool operator<(T, T);
6788 // bool operator>(T, T);
6789 // bool operator<=(T, T);
6790 // bool operator>=(T, T);
6791 // bool operator==(T, T);
6792 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006793 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00006794 // C++ [over.match.oper]p3:
6795 // [...]the built-in candidates include all of the candidate operator
6796 // functions defined in 13.6 that, compared to the given operator, [...]
6797 // do not have the same parameter-type-list as any non-template non-member
6798 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006799 //
Eli Friedman14f082b2012-09-18 21:52:24 +00006800 // Note that in practice, this only affects enumeration types because there
6801 // aren't any built-in candidates of record type, and a user-defined operator
6802 // must have an operand of record or enumeration type. Also, the only other
6803 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006804 // cannot be overloaded for enumeration types, so this is the only place
6805 // where we must suppress candidates like this.
6806 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6807 UserDefinedBinaryOperators;
6808
6809 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6810 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6811 CandidateTypes[ArgIdx].enumeration_end()) {
6812 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6813 CEnd = CandidateSet.end();
6814 C != CEnd; ++C) {
6815 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6816 continue;
6817
Eli Friedman14f082b2012-09-18 21:52:24 +00006818 if (C->Function->isFunctionTemplateSpecialization())
6819 continue;
6820
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006821 QualType FirstParamType =
6822 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6823 QualType SecondParamType =
6824 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6825
6826 // Skip if either parameter isn't of enumeral type.
6827 if (!FirstParamType->isEnumeralType() ||
6828 !SecondParamType->isEnumeralType())
6829 continue;
6830
6831 // Add this operator to the set of known user-defined operators.
6832 UserDefinedBinaryOperators.insert(
6833 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6834 S.Context.getCanonicalType(SecondParamType)));
6835 }
6836 }
6837 }
6838
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006839 /// Set of (canonical) types that we've already handled.
6840 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6841
6842 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6843 for (BuiltinCandidateTypeSet::iterator
6844 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6845 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6846 Ptr != PtrEnd; ++Ptr) {
6847 // Don't add the same builtin candidate twice.
6848 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6849 continue;
6850
6851 QualType ParamTypes[2] = { *Ptr, *Ptr };
6852 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6853 CandidateSet);
6854 }
6855 for (BuiltinCandidateTypeSet::iterator
6856 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6857 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6858 Enum != EnumEnd; ++Enum) {
6859 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6860
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006861 // Don't add the same builtin candidate twice, or if a user defined
6862 // candidate exists.
6863 if (!AddedTypes.insert(CanonType) ||
6864 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6865 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006866 continue;
6867
6868 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006869 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6870 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006871 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006872
6873 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6874 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6875 if (AddedTypes.insert(NullPtrTy) &&
6876 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6877 NullPtrTy))) {
6878 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6879 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6880 CandidateSet);
6881 }
6882 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006883 }
6884 }
6885
6886 // C++ [over.built]p13:
6887 //
6888 // For every cv-qualified or cv-unqualified object type T
6889 // there exist candidate operator functions of the form
6890 //
6891 // T* operator+(T*, ptrdiff_t);
6892 // T& operator[](T*, ptrdiff_t); [BELOW]
6893 // T* operator-(T*, ptrdiff_t);
6894 // T* operator+(ptrdiff_t, T*);
6895 // T& operator[](ptrdiff_t, T*); [BELOW]
6896 //
6897 // C++ [over.built]p14:
6898 //
6899 // For every T, where T is a pointer to object type, there
6900 // exist candidate operator functions of the form
6901 //
6902 // ptrdiff_t operator-(T, T);
6903 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6904 /// Set of (canonical) types that we've already handled.
6905 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6906
6907 for (int Arg = 0; Arg < 2; ++Arg) {
6908 QualType AsymetricParamTypes[2] = {
6909 S.Context.getPointerDiffType(),
6910 S.Context.getPointerDiffType(),
6911 };
6912 for (BuiltinCandidateTypeSet::iterator
6913 Ptr = CandidateTypes[Arg].pointer_begin(),
6914 PtrEnd = CandidateTypes[Arg].pointer_end();
6915 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006916 QualType PointeeTy = (*Ptr)->getPointeeType();
6917 if (!PointeeTy->isObjectType())
6918 continue;
6919
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006920 AsymetricParamTypes[Arg] = *Ptr;
6921 if (Arg == 0 || Op == OO_Plus) {
6922 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6923 // T* operator+(ptrdiff_t, T*);
6924 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6925 CandidateSet);
6926 }
6927 if (Op == OO_Minus) {
6928 // ptrdiff_t operator-(T, T);
6929 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6930 continue;
6931
6932 QualType ParamTypes[2] = { *Ptr, *Ptr };
6933 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6934 Args, 2, CandidateSet);
6935 }
6936 }
6937 }
6938 }
6939
6940 // C++ [over.built]p12:
6941 //
6942 // For every pair of promoted arithmetic types L and R, there
6943 // exist candidate operator functions of the form
6944 //
6945 // LR operator*(L, R);
6946 // LR operator/(L, R);
6947 // LR operator+(L, R);
6948 // LR operator-(L, R);
6949 // bool operator<(L, R);
6950 // bool operator>(L, R);
6951 // bool operator<=(L, R);
6952 // bool operator>=(L, R);
6953 // bool operator==(L, R);
6954 // bool operator!=(L, R);
6955 //
6956 // where LR is the result of the usual arithmetic conversions
6957 // between types L and R.
6958 //
6959 // C++ [over.built]p24:
6960 //
6961 // For every pair of promoted arithmetic types L and R, there exist
6962 // candidate operator functions of the form
6963 //
6964 // LR operator?(bool, L, R);
6965 //
6966 // where LR is the result of the usual arithmetic conversions
6967 // between types L and R.
6968 // Our candidates ignore the first parameter.
6969 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006970 if (!HasArithmeticOrEnumeralCandidateType)
6971 return;
6972
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006973 for (unsigned Left = FirstPromotedArithmeticType;
6974 Left < LastPromotedArithmeticType; ++Left) {
6975 for (unsigned Right = FirstPromotedArithmeticType;
6976 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006977 QualType LandR[2] = { getArithmeticType(Left),
6978 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006979 QualType Result =
6980 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006981 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006982 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6983 }
6984 }
6985
6986 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6987 // conditional operator for vector types.
6988 for (BuiltinCandidateTypeSet::iterator
6989 Vec1 = CandidateTypes[0].vector_begin(),
6990 Vec1End = CandidateTypes[0].vector_end();
6991 Vec1 != Vec1End; ++Vec1) {
6992 for (BuiltinCandidateTypeSet::iterator
6993 Vec2 = CandidateTypes[1].vector_begin(),
6994 Vec2End = CandidateTypes[1].vector_end();
6995 Vec2 != Vec2End; ++Vec2) {
6996 QualType LandR[2] = { *Vec1, *Vec2 };
6997 QualType Result = S.Context.BoolTy;
6998 if (!isComparison) {
6999 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7000 Result = *Vec1;
7001 else
7002 Result = *Vec2;
7003 }
7004
7005 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7006 }
7007 }
7008 }
7009
7010 // C++ [over.built]p17:
7011 //
7012 // For every pair of promoted integral types L and R, there
7013 // exist candidate operator functions of the form
7014 //
7015 // LR operator%(L, R);
7016 // LR operator&(L, R);
7017 // LR operator^(L, R);
7018 // LR operator|(L, R);
7019 // L operator<<(L, R);
7020 // L operator>>(L, R);
7021 //
7022 // where LR is the result of the usual arithmetic conversions
7023 // between types L and R.
7024 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007025 if (!HasArithmeticOrEnumeralCandidateType)
7026 return;
7027
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007028 for (unsigned Left = FirstPromotedIntegralType;
7029 Left < LastPromotedIntegralType; ++Left) {
7030 for (unsigned Right = FirstPromotedIntegralType;
7031 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007032 QualType LandR[2] = { getArithmeticType(Left),
7033 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007034 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7035 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007036 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007037 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7038 }
7039 }
7040 }
7041
7042 // C++ [over.built]p20:
7043 //
7044 // For every pair (T, VQ), where T is an enumeration or
7045 // pointer to member type and VQ is either volatile or
7046 // empty, there exist candidate operator functions of the form
7047 //
7048 // VQ T& operator=(VQ T&, T);
7049 void addAssignmentMemberPointerOrEnumeralOverloads() {
7050 /// Set of (canonical) types that we've already handled.
7051 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7052
7053 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7054 for (BuiltinCandidateTypeSet::iterator
7055 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7056 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7057 Enum != EnumEnd; ++Enum) {
7058 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7059 continue;
7060
7061 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7062 CandidateSet);
7063 }
7064
7065 for (BuiltinCandidateTypeSet::iterator
7066 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7067 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7068 MemPtr != MemPtrEnd; ++MemPtr) {
7069 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7070 continue;
7071
7072 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7073 CandidateSet);
7074 }
7075 }
7076 }
7077
7078 // C++ [over.built]p19:
7079 //
7080 // For every pair (T, VQ), where T is any type and VQ is either
7081 // volatile or empty, there exist candidate operator functions
7082 // of the form
7083 //
7084 // T*VQ& operator=(T*VQ&, T*);
7085 //
7086 // C++ [over.built]p21:
7087 //
7088 // For every pair (T, VQ), where T is a cv-qualified or
7089 // cv-unqualified object type and VQ is either volatile or
7090 // empty, there exist candidate operator functions of the form
7091 //
7092 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7093 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7094 void addAssignmentPointerOverloads(bool isEqualOp) {
7095 /// Set of (canonical) types that we've already handled.
7096 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7097
7098 for (BuiltinCandidateTypeSet::iterator
7099 Ptr = CandidateTypes[0].pointer_begin(),
7100 PtrEnd = CandidateTypes[0].pointer_end();
7101 Ptr != PtrEnd; ++Ptr) {
7102 // If this is operator=, keep track of the builtin candidates we added.
7103 if (isEqualOp)
7104 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007105 else if (!(*Ptr)->getPointeeType()->isObjectType())
7106 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007107
7108 // non-volatile version
7109 QualType ParamTypes[2] = {
7110 S.Context.getLValueReferenceType(*Ptr),
7111 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7112 };
7113 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7114 /*IsAssigmentOperator=*/ isEqualOp);
7115
Douglas Gregor5bee2582012-06-04 00:15:09 +00007116 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7117 VisibleTypeConversionsQuals.hasVolatile();
7118 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007119 // volatile version
7120 ParamTypes[0] =
7121 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7122 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7123 /*IsAssigmentOperator=*/isEqualOp);
7124 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007125
7126 if (!(*Ptr).isRestrictQualified() &&
7127 VisibleTypeConversionsQuals.hasRestrict()) {
7128 // restrict version
7129 ParamTypes[0]
7130 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7131 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7132 /*IsAssigmentOperator=*/isEqualOp);
7133
7134 if (NeedVolatile) {
7135 // volatile restrict version
7136 ParamTypes[0]
7137 = S.Context.getLValueReferenceType(
7138 S.Context.getCVRQualifiedType(*Ptr,
7139 (Qualifiers::Volatile |
7140 Qualifiers::Restrict)));
7141 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7142 CandidateSet,
7143 /*IsAssigmentOperator=*/isEqualOp);
7144 }
7145 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007146 }
7147
7148 if (isEqualOp) {
7149 for (BuiltinCandidateTypeSet::iterator
7150 Ptr = CandidateTypes[1].pointer_begin(),
7151 PtrEnd = CandidateTypes[1].pointer_end();
7152 Ptr != PtrEnd; ++Ptr) {
7153 // Make sure we don't add the same candidate twice.
7154 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7155 continue;
7156
Chandler Carruth8e543b32010-12-12 08:17:55 +00007157 QualType ParamTypes[2] = {
7158 S.Context.getLValueReferenceType(*Ptr),
7159 *Ptr,
7160 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007161
7162 // non-volatile version
7163 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7164 /*IsAssigmentOperator=*/true);
7165
Douglas Gregor5bee2582012-06-04 00:15:09 +00007166 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7167 VisibleTypeConversionsQuals.hasVolatile();
7168 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007169 // volatile version
7170 ParamTypes[0] =
7171 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00007172 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7173 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007174 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007175
7176 if (!(*Ptr).isRestrictQualified() &&
7177 VisibleTypeConversionsQuals.hasRestrict()) {
7178 // restrict version
7179 ParamTypes[0]
7180 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7181 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7182 CandidateSet, /*IsAssigmentOperator=*/true);
7183
7184 if (NeedVolatile) {
7185 // volatile restrict version
7186 ParamTypes[0]
7187 = S.Context.getLValueReferenceType(
7188 S.Context.getCVRQualifiedType(*Ptr,
7189 (Qualifiers::Volatile |
7190 Qualifiers::Restrict)));
7191 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7192 CandidateSet, /*IsAssigmentOperator=*/true);
7193
7194 }
7195 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007196 }
7197 }
7198 }
7199
7200 // C++ [over.built]p18:
7201 //
7202 // For every triple (L, VQ, R), where L is an arithmetic type,
7203 // VQ is either volatile or empty, and R is a promoted
7204 // arithmetic type, there exist candidate operator functions of
7205 // the form
7206 //
7207 // VQ L& operator=(VQ L&, R);
7208 // VQ L& operator*=(VQ L&, R);
7209 // VQ L& operator/=(VQ L&, R);
7210 // VQ L& operator+=(VQ L&, R);
7211 // VQ L& operator-=(VQ L&, R);
7212 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007213 if (!HasArithmeticOrEnumeralCandidateType)
7214 return;
7215
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007216 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7217 for (unsigned Right = FirstPromotedArithmeticType;
7218 Right < LastPromotedArithmeticType; ++Right) {
7219 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007220 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007221
7222 // Add this built-in operator as a candidate (VQ is empty).
7223 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007224 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007225 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7226 /*IsAssigmentOperator=*/isEqualOp);
7227
7228 // Add this built-in operator as a candidate (VQ is 'volatile').
7229 if (VisibleTypeConversionsQuals.hasVolatile()) {
7230 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007231 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007232 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007233 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7234 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007235 /*IsAssigmentOperator=*/isEqualOp);
7236 }
7237 }
7238 }
7239
7240 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7241 for (BuiltinCandidateTypeSet::iterator
7242 Vec1 = CandidateTypes[0].vector_begin(),
7243 Vec1End = CandidateTypes[0].vector_end();
7244 Vec1 != Vec1End; ++Vec1) {
7245 for (BuiltinCandidateTypeSet::iterator
7246 Vec2 = CandidateTypes[1].vector_begin(),
7247 Vec2End = CandidateTypes[1].vector_end();
7248 Vec2 != Vec2End; ++Vec2) {
7249 QualType ParamTypes[2];
7250 ParamTypes[1] = *Vec2;
7251 // Add this built-in operator as a candidate (VQ is empty).
7252 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7253 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7254 /*IsAssigmentOperator=*/isEqualOp);
7255
7256 // Add this built-in operator as a candidate (VQ is 'volatile').
7257 if (VisibleTypeConversionsQuals.hasVolatile()) {
7258 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7259 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007260 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7261 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007262 /*IsAssigmentOperator=*/isEqualOp);
7263 }
7264 }
7265 }
7266 }
7267
7268 // C++ [over.built]p22:
7269 //
7270 // For every triple (L, VQ, R), where L is an integral type, VQ
7271 // is either volatile or empty, and R is a promoted integral
7272 // type, there exist candidate operator functions of the form
7273 //
7274 // VQ L& operator%=(VQ L&, R);
7275 // VQ L& operator<<=(VQ L&, R);
7276 // VQ L& operator>>=(VQ L&, R);
7277 // VQ L& operator&=(VQ L&, R);
7278 // VQ L& operator^=(VQ L&, R);
7279 // VQ L& operator|=(VQ L&, R);
7280 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007281 if (!HasArithmeticOrEnumeralCandidateType)
7282 return;
7283
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007284 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7285 for (unsigned Right = FirstPromotedIntegralType;
7286 Right < LastPromotedIntegralType; ++Right) {
7287 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007288 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007289
7290 // Add this built-in operator as a candidate (VQ is empty).
7291 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007292 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007293 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7294 if (VisibleTypeConversionsQuals.hasVolatile()) {
7295 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007296 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007297 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7298 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7299 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7300 CandidateSet);
7301 }
7302 }
7303 }
7304 }
7305
7306 // C++ [over.operator]p23:
7307 //
7308 // There also exist candidate operator functions of the form
7309 //
7310 // bool operator!(bool);
7311 // bool operator&&(bool, bool);
7312 // bool operator||(bool, bool);
7313 void addExclaimOverload() {
7314 QualType ParamTy = S.Context.BoolTy;
7315 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7316 /*IsAssignmentOperator=*/false,
7317 /*NumContextualBoolArguments=*/1);
7318 }
7319 void addAmpAmpOrPipePipeOverload() {
7320 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7321 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7322 /*IsAssignmentOperator=*/false,
7323 /*NumContextualBoolArguments=*/2);
7324 }
7325
7326 // C++ [over.built]p13:
7327 //
7328 // For every cv-qualified or cv-unqualified object type T there
7329 // exist candidate operator functions of the form
7330 //
7331 // T* operator+(T*, ptrdiff_t); [ABOVE]
7332 // T& operator[](T*, ptrdiff_t);
7333 // T* operator-(T*, ptrdiff_t); [ABOVE]
7334 // T* operator+(ptrdiff_t, T*); [ABOVE]
7335 // T& operator[](ptrdiff_t, T*);
7336 void addSubscriptOverloads() {
7337 for (BuiltinCandidateTypeSet::iterator
7338 Ptr = CandidateTypes[0].pointer_begin(),
7339 PtrEnd = CandidateTypes[0].pointer_end();
7340 Ptr != PtrEnd; ++Ptr) {
7341 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7342 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007343 if (!PointeeType->isObjectType())
7344 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007345
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007346 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7347
7348 // T& operator[](T*, ptrdiff_t)
7349 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7350 }
7351
7352 for (BuiltinCandidateTypeSet::iterator
7353 Ptr = CandidateTypes[1].pointer_begin(),
7354 PtrEnd = CandidateTypes[1].pointer_end();
7355 Ptr != PtrEnd; ++Ptr) {
7356 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7357 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007358 if (!PointeeType->isObjectType())
7359 continue;
7360
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007361 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7362
7363 // T& operator[](ptrdiff_t, T*)
7364 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7365 }
7366 }
7367
7368 // C++ [over.built]p11:
7369 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7370 // C1 is the same type as C2 or is a derived class of C2, T is an object
7371 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7372 // there exist candidate operator functions of the form
7373 //
7374 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7375 //
7376 // where CV12 is the union of CV1 and CV2.
7377 void addArrowStarOverloads() {
7378 for (BuiltinCandidateTypeSet::iterator
7379 Ptr = CandidateTypes[0].pointer_begin(),
7380 PtrEnd = CandidateTypes[0].pointer_end();
7381 Ptr != PtrEnd; ++Ptr) {
7382 QualType C1Ty = (*Ptr);
7383 QualType C1;
7384 QualifierCollector Q1;
7385 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7386 if (!isa<RecordType>(C1))
7387 continue;
7388 // heuristic to reduce number of builtin candidates in the set.
7389 // Add volatile/restrict version only if there are conversions to a
7390 // volatile/restrict type.
7391 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7392 continue;
7393 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7394 continue;
7395 for (BuiltinCandidateTypeSet::iterator
7396 MemPtr = CandidateTypes[1].member_pointer_begin(),
7397 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7398 MemPtr != MemPtrEnd; ++MemPtr) {
7399 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7400 QualType C2 = QualType(mptr->getClass(), 0);
7401 C2 = C2.getUnqualifiedType();
7402 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7403 break;
7404 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7405 // build CV12 T&
7406 QualType T = mptr->getPointeeType();
7407 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7408 T.isVolatileQualified())
7409 continue;
7410 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7411 T.isRestrictQualified())
7412 continue;
7413 T = Q1.apply(S.Context, T);
7414 QualType ResultTy = S.Context.getLValueReferenceType(T);
7415 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7416 }
7417 }
7418 }
7419
7420 // Note that we don't consider the first argument, since it has been
7421 // contextually converted to bool long ago. The candidates below are
7422 // therefore added as binary.
7423 //
7424 // C++ [over.built]p25:
7425 // For every type T, where T is a pointer, pointer-to-member, or scoped
7426 // enumeration type, there exist candidate operator functions of the form
7427 //
7428 // T operator?(bool, T, T);
7429 //
7430 void addConditionalOperatorOverloads() {
7431 /// Set of (canonical) types that we've already handled.
7432 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7433
7434 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7435 for (BuiltinCandidateTypeSet::iterator
7436 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7437 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7438 Ptr != PtrEnd; ++Ptr) {
7439 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7440 continue;
7441
7442 QualType ParamTypes[2] = { *Ptr, *Ptr };
7443 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7444 }
7445
7446 for (BuiltinCandidateTypeSet::iterator
7447 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7448 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7449 MemPtr != MemPtrEnd; ++MemPtr) {
7450 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7451 continue;
7452
7453 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7454 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7455 }
7456
David Blaikiebbafb8a2012-03-11 07:00:24 +00007457 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007458 for (BuiltinCandidateTypeSet::iterator
7459 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7460 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7461 Enum != EnumEnd; ++Enum) {
7462 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7463 continue;
7464
7465 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7466 continue;
7467
7468 QualType ParamTypes[2] = { *Enum, *Enum };
7469 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7470 }
7471 }
7472 }
7473 }
7474};
7475
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007476} // end anonymous namespace
7477
7478/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7479/// operator overloads to the candidate set (C++ [over.built]), based
7480/// on the operator @p Op and the arguments given. For example, if the
7481/// operator is a binary '+', this routine might add "int
7482/// operator+(int, int)" to cover integer addition.
7483void
7484Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7485 SourceLocation OpLoc,
7486 Expr **Args, unsigned NumArgs,
7487 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007488 // Find all of the types that the arguments can convert to, but only
7489 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007490 // that make use of these types. Also record whether we encounter non-record
7491 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007492 Qualifiers VisibleTypeConversionsQuals;
7493 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007494 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7495 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007496
7497 bool HasNonRecordCandidateType = false;
7498 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007499 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007500 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7501 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7502 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7503 OpLoc,
7504 true,
7505 (Op == OO_Exclaim ||
7506 Op == OO_AmpAmp ||
7507 Op == OO_PipePipe),
7508 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007509 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7510 CandidateTypes[ArgIdx].hasNonRecordTypes();
7511 HasArithmeticOrEnumeralCandidateType =
7512 HasArithmeticOrEnumeralCandidateType ||
7513 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007514 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007515
Chandler Carruth00a38332010-12-13 01:44:01 +00007516 // Exit early when no non-record types have been added to the candidate set
7517 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007518 //
7519 // We can't exit early for !, ||, or &&, since there we have always have
7520 // 'bool' overloads.
7521 if (!HasNonRecordCandidateType &&
7522 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007523 return;
7524
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007525 // Setup an object to manage the common state for building overloads.
7526 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7527 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007528 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007529 CandidateTypes, CandidateSet);
7530
7531 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007532 switch (Op) {
7533 case OO_None:
7534 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007535 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007536
Chandler Carruth5184de02010-12-12 08:51:33 +00007537 case OO_New:
7538 case OO_Delete:
7539 case OO_Array_New:
7540 case OO_Array_Delete:
7541 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007542 llvm_unreachable(
7543 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007544
7545 case OO_Comma:
7546 case OO_Arrow:
7547 // C++ [over.match.oper]p3:
7548 // -- For the operator ',', the unary operator '&', or the
7549 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007550 break;
7551
7552 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007553 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007554 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007555 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007556
7557 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00007558 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007559 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007560 } else {
7561 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7562 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7563 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007564 break;
7565
Chandler Carruth5184de02010-12-12 08:51:33 +00007566 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00007567 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007568 OpBuilder.addUnaryStarPointerOverloads();
7569 else
7570 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7571 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007572
Chandler Carruth5184de02010-12-12 08:51:33 +00007573 case OO_Slash:
7574 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007575 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007576
7577 case OO_PlusPlus:
7578 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007579 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7580 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007581 break;
7582
Douglas Gregor84605ae2009-08-24 13:43:27 +00007583 case OO_EqualEqual:
7584 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007585 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007586 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007587
Douglas Gregora11693b2008-11-12 17:17:38 +00007588 case OO_Less:
7589 case OO_Greater:
7590 case OO_LessEqual:
7591 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007592 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007593 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7594 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007595
Douglas Gregora11693b2008-11-12 17:17:38 +00007596 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007597 case OO_Caret:
7598 case OO_Pipe:
7599 case OO_LessLess:
7600 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007601 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007602 break;
7603
Chandler Carruth5184de02010-12-12 08:51:33 +00007604 case OO_Amp: // '&' is either unary or binary
7605 if (NumArgs == 1)
7606 // C++ [over.match.oper]p3:
7607 // -- For the operator ',', the unary operator '&', or the
7608 // operator '->', the built-in candidates set is empty.
7609 break;
7610
7611 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7612 break;
7613
7614 case OO_Tilde:
7615 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7616 break;
7617
Douglas Gregora11693b2008-11-12 17:17:38 +00007618 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007619 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007620 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00007621
7622 case OO_PlusEqual:
7623 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007624 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007625 // Fall through.
7626
7627 case OO_StarEqual:
7628 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007629 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007630 break;
7631
7632 case OO_PercentEqual:
7633 case OO_LessLessEqual:
7634 case OO_GreaterGreaterEqual:
7635 case OO_AmpEqual:
7636 case OO_CaretEqual:
7637 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007638 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007639 break;
7640
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007641 case OO_Exclaim:
7642 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00007643 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007644
Douglas Gregora11693b2008-11-12 17:17:38 +00007645 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007646 case OO_PipePipe:
7647 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00007648 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007649
7650 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007651 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007652 break;
7653
7654 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007655 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007656 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00007657
7658 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007659 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007660 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7661 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007662 }
7663}
7664
Douglas Gregore254f902009-02-04 00:32:51 +00007665/// \brief Add function candidates found via argument-dependent lookup
7666/// to the set of overloading candidates.
7667///
7668/// This routine performs argument-dependent name lookup based on the
7669/// given function name (which may also be an operator name) and adds
7670/// all of the overload candidates found by ADL to the overload
7671/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00007672void
Douglas Gregore254f902009-02-04 00:32:51 +00007673Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00007674 bool Operator, SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007675 llvm::ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007676 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007677 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00007678 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00007679 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00007680
John McCall91f61fc2010-01-26 06:04:06 +00007681 // FIXME: This approach for uniquing ADL results (and removing
7682 // redundant candidates from the set) relies on pointer-equality,
7683 // which means we need to key off the canonical decl. However,
7684 // always going back to the canonical decl might not get us the
7685 // right set of default arguments. What default arguments are
7686 // we supposed to consider on ADL candidates, anyway?
7687
Douglas Gregorcabea402009-09-22 15:41:20 +00007688 // FIXME: Pass in the explicit template arguments?
Richard Smithb6626742012-10-18 17:56:02 +00007689 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00007690
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007691 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007692 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7693 CandEnd = CandidateSet.end();
7694 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00007695 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00007696 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00007697 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00007698 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00007699 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007700
7701 // For each of the ADL candidates we found, add it to the overload
7702 // set.
John McCall8fe68082010-01-26 07:16:45 +00007703 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00007704 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00007705 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00007706 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00007707 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007708
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007709 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7710 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007711 } else
John McCall4c4c1df2010-01-26 03:27:55 +00007712 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00007713 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007714 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00007715 }
Douglas Gregore254f902009-02-04 00:32:51 +00007716}
7717
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007718/// isBetterOverloadCandidate - Determines whether the first overload
7719/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00007720bool
John McCall5c32be02010-08-24 20:38:10 +00007721isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007722 const OverloadCandidate &Cand1,
7723 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007724 SourceLocation Loc,
7725 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007726 // Define viable functions to be better candidates than non-viable
7727 // functions.
7728 if (!Cand2.Viable)
7729 return Cand1.Viable;
7730 else if (!Cand1.Viable)
7731 return false;
7732
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007733 // C++ [over.match.best]p1:
7734 //
7735 // -- if F is a static member function, ICS1(F) is defined such
7736 // that ICS1(F) is neither better nor worse than ICS1(G) for
7737 // any function G, and, symmetrically, ICS1(G) is neither
7738 // better nor worse than ICS1(F).
7739 unsigned StartArg = 0;
7740 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7741 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007742
Douglas Gregord3cb3562009-07-07 23:38:56 +00007743 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007744 // A viable function F1 is defined to be a better function than another
7745 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007746 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007747 unsigned NumArgs = Cand1.NumConversions;
7748 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007749 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007750 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007751 switch (CompareImplicitConversionSequences(S,
7752 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007753 Cand2.Conversions[ArgIdx])) {
7754 case ImplicitConversionSequence::Better:
7755 // Cand1 has a better conversion sequence.
7756 HasBetterConversion = true;
7757 break;
7758
7759 case ImplicitConversionSequence::Worse:
7760 // Cand1 can't be better than Cand2.
7761 return false;
7762
7763 case ImplicitConversionSequence::Indistinguishable:
7764 // Do nothing.
7765 break;
7766 }
7767 }
7768
Mike Stump11289f42009-09-09 15:08:12 +00007769 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007770 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007771 if (HasBetterConversion)
7772 return true;
7773
Mike Stump11289f42009-09-09 15:08:12 +00007774 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007775 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007776 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007777 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7778 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007779
7780 // -- F1 and F2 are function template specializations, and the function
7781 // template for F1 is more specialized than the template for F2
7782 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007783 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007784 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007785 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007786 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007787 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7788 Cand2.Function->getPrimaryTemplate(),
7789 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007790 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007791 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007792 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007793 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007794 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007795
Douglas Gregora1f013e2008-11-07 22:36:19 +00007796 // -- the context is an initialization by user-defined conversion
7797 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7798 // from the return type of F1 to the destination type (i.e.,
7799 // the type of the entity being initialized) is a better
7800 // conversion sequence than the standard conversion sequence
7801 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007802 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007803 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007804 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00007805 // First check whether we prefer one of the conversion functions over the
7806 // other. This only distinguishes the results in non-standard, extension
7807 // cases such as the conversion from a lambda closure type to a function
7808 // pointer or block.
7809 ImplicitConversionSequence::CompareKind FuncResult
7810 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7811 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7812 return FuncResult;
7813
John McCall5c32be02010-08-24 20:38:10 +00007814 switch (CompareStandardConversionSequences(S,
7815 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007816 Cand2.FinalConversion)) {
7817 case ImplicitConversionSequence::Better:
7818 // Cand1 has a better conversion sequence.
7819 return true;
7820
7821 case ImplicitConversionSequence::Worse:
7822 // Cand1 can't be better than Cand2.
7823 return false;
7824
7825 case ImplicitConversionSequence::Indistinguishable:
7826 // Do nothing
7827 break;
7828 }
7829 }
7830
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007831 return false;
7832}
7833
Mike Stump11289f42009-09-09 15:08:12 +00007834/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007835/// within an overload candidate set.
7836///
James Dennettffad8b72012-06-22 08:10:18 +00007837/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007838/// which overload resolution occurs.
7839///
James Dennettffad8b72012-06-22 08:10:18 +00007840/// \param Best If overload resolution was successful or found a deleted
7841/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007842///
7843/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007844OverloadingResult
7845OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007846 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007847 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007848 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007849 Best = end();
7850 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7851 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007852 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007853 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007854 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007855 }
7856
7857 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007858 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007859 return OR_No_Viable_Function;
7860
7861 // Make sure that this function is better than every other viable
7862 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007863 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007864 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007865 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007866 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007867 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007868 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007869 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007870 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007871 }
Mike Stump11289f42009-09-09 15:08:12 +00007872
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007873 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007874 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007875 (Best->Function->isDeleted() ||
7876 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007877 return OR_Deleted;
7878
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007879 return OR_Success;
7880}
7881
John McCall53262c92010-01-12 02:15:36 +00007882namespace {
7883
7884enum OverloadCandidateKind {
7885 oc_function,
7886 oc_method,
7887 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007888 oc_function_template,
7889 oc_method_template,
7890 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007891 oc_implicit_default_constructor,
7892 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007893 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007894 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007895 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007896 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007897};
7898
John McCalle1ac8d12010-01-13 00:25:19 +00007899OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7900 FunctionDecl *Fn,
7901 std::string &Description) {
7902 bool isTemplate = false;
7903
7904 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7905 isTemplate = true;
7906 Description = S.getTemplateArgumentBindingsText(
7907 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7908 }
John McCallfd0b2f82010-01-06 09:43:14 +00007909
7910 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007911 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007912 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007913
Sebastian Redl08905022011-02-05 19:23:19 +00007914 if (Ctor->getInheritedConstructor())
7915 return oc_implicit_inherited_constructor;
7916
Alexis Hunt119c10e2011-05-25 23:16:36 +00007917 if (Ctor->isDefaultConstructor())
7918 return oc_implicit_default_constructor;
7919
7920 if (Ctor->isMoveConstructor())
7921 return oc_implicit_move_constructor;
7922
7923 assert(Ctor->isCopyConstructor() &&
7924 "unexpected sort of implicit constructor");
7925 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007926 }
7927
7928 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7929 // This actually gets spelled 'candidate function' for now, but
7930 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007931 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007932 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007933
Alexis Hunt119c10e2011-05-25 23:16:36 +00007934 if (Meth->isMoveAssignmentOperator())
7935 return oc_implicit_move_assignment;
7936
Douglas Gregor12695102012-02-10 08:36:38 +00007937 if (Meth->isCopyAssignmentOperator())
7938 return oc_implicit_copy_assignment;
7939
7940 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7941 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00007942 }
7943
John McCalle1ac8d12010-01-13 00:25:19 +00007944 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007945}
7946
Sebastian Redl08905022011-02-05 19:23:19 +00007947void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7948 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7949 if (!Ctor) return;
7950
7951 Ctor = Ctor->getInheritedConstructor();
7952 if (!Ctor) return;
7953
7954 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7955}
7956
John McCall53262c92010-01-12 02:15:36 +00007957} // end anonymous namespace
7958
7959// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007960void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007961 std::string FnDesc;
7962 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007963 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7964 << (unsigned) K << FnDesc;
7965 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7966 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007967 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007968}
7969
Douglas Gregorb491ed32011-02-19 21:32:49 +00007970//Notes the location of all overload candidates designated through
7971// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007972void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007973 assert(OverloadedExpr->getType() == Context.OverloadTy);
7974
7975 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7976 OverloadExpr *OvlExpr = Ovl.Expression;
7977
7978 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7979 IEnd = OvlExpr->decls_end();
7980 I != IEnd; ++I) {
7981 if (FunctionTemplateDecl *FunTmpl =
7982 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007983 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007984 } else if (FunctionDecl *Fun
7985 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007986 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007987 }
7988 }
7989}
7990
John McCall0d1da222010-01-12 00:44:57 +00007991/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7992/// "lead" diagnostic; it will be given two arguments, the source and
7993/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007994void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7995 Sema &S,
7996 SourceLocation CaretLoc,
7997 const PartialDiagnostic &PDiag) const {
7998 S.Diag(CaretLoc, PDiag)
7999 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008000 // FIXME: The note limiting machinery is borrowed from
8001 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8002 // refactoring here.
8003 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8004 unsigned CandsShown = 0;
8005 AmbiguousConversionSequence::const_iterator I, E;
8006 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8007 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8008 break;
8009 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008010 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008011 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008012 if (I != E)
8013 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008014}
8015
John McCall0d1da222010-01-12 00:44:57 +00008016namespace {
8017
John McCall6a61b522010-01-13 09:16:55 +00008018void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8019 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8020 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008021 assert(Cand->Function && "for now, candidate must be a function");
8022 FunctionDecl *Fn = Cand->Function;
8023
8024 // There's a conversion slot for the object argument if this is a
8025 // non-constructor method. Note that 'I' corresponds the
8026 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008027 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008028 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008029 if (I == 0)
8030 isObjectArgument = true;
8031 else
8032 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008033 }
8034
John McCalle1ac8d12010-01-13 00:25:19 +00008035 std::string FnDesc;
8036 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8037
John McCall6a61b522010-01-13 09:16:55 +00008038 Expr *FromExpr = Conv.Bad.FromExpr;
8039 QualType FromTy = Conv.Bad.getFromType();
8040 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008041
John McCallfb7ad0f2010-02-02 02:42:52 +00008042 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008043 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008044 Expr *E = FromExpr->IgnoreParens();
8045 if (isa<UnaryOperator>(E))
8046 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008047 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008048
8049 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8050 << (unsigned) FnKind << FnDesc
8051 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8052 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008053 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008054 return;
8055 }
8056
John McCall6d174642010-01-23 08:10:49 +00008057 // Do some hand-waving analysis to see if the non-viability is due
8058 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008059 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8060 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8061 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8062 CToTy = RT->getPointeeType();
8063 else {
8064 // TODO: detect and diagnose the full richness of const mismatches.
8065 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8066 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8067 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8068 }
8069
8070 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8071 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008072 Qualifiers FromQs = CFromTy.getQualifiers();
8073 Qualifiers ToQs = CToTy.getQualifiers();
8074
8075 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8076 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8077 << (unsigned) FnKind << FnDesc
8078 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8079 << FromTy
8080 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8081 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008082 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008083 return;
8084 }
8085
John McCall31168b02011-06-15 23:02:42 +00008086 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008087 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008088 << (unsigned) FnKind << FnDesc
8089 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8090 << FromTy
8091 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8092 << (unsigned) isObjectArgument << I+1;
8093 MaybeEmitInheritedConstructorNote(S, Fn);
8094 return;
8095 }
8096
Douglas Gregoraec25842011-04-26 23:16:46 +00008097 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8098 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8099 << (unsigned) FnKind << FnDesc
8100 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8101 << FromTy
8102 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8103 << (unsigned) isObjectArgument << I+1;
8104 MaybeEmitInheritedConstructorNote(S, Fn);
8105 return;
8106 }
8107
John McCall47000992010-01-14 03:28:57 +00008108 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8109 assert(CVR && "unexpected qualifiers mismatch");
8110
8111 if (isObjectArgument) {
8112 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8113 << (unsigned) FnKind << FnDesc
8114 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8115 << FromTy << (CVR - 1);
8116 } else {
8117 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8118 << (unsigned) FnKind << FnDesc
8119 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8120 << FromTy << (CVR - 1) << I+1;
8121 }
Sebastian Redl08905022011-02-05 19:23:19 +00008122 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008123 return;
8124 }
8125
Sebastian Redla72462c2011-09-24 17:48:32 +00008126 // Special diagnostic for failure to convert an initializer list, since
8127 // telling the user that it has type void is not useful.
8128 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8129 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8130 << (unsigned) FnKind << FnDesc
8131 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8132 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8133 MaybeEmitInheritedConstructorNote(S, Fn);
8134 return;
8135 }
8136
John McCall6d174642010-01-23 08:10:49 +00008137 // Diagnose references or pointers to incomplete types differently,
8138 // since it's far from impossible that the incompleteness triggered
8139 // the failure.
8140 QualType TempFromTy = FromTy.getNonReferenceType();
8141 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8142 TempFromTy = PTy->getPointeeType();
8143 if (TempFromTy->isIncompleteType()) {
8144 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8145 << (unsigned) FnKind << FnDesc
8146 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8147 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008148 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008149 return;
8150 }
8151
Douglas Gregor56f2e342010-06-30 23:01:39 +00008152 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008153 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008154 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8155 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8156 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8157 FromPtrTy->getPointeeType()) &&
8158 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8159 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008160 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008161 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008162 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008163 }
8164 } else if (const ObjCObjectPointerType *FromPtrTy
8165 = FromTy->getAs<ObjCObjectPointerType>()) {
8166 if (const ObjCObjectPointerType *ToPtrTy
8167 = ToTy->getAs<ObjCObjectPointerType>())
8168 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8169 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8170 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8171 FromPtrTy->getPointeeType()) &&
8172 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008173 BaseToDerivedConversion = 2;
8174 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008175 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8176 !FromTy->isIncompleteType() &&
8177 !ToRefTy->getPointeeType()->isIncompleteType() &&
8178 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8179 BaseToDerivedConversion = 3;
8180 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8181 ToTy.getNonReferenceType().getCanonicalType() ==
8182 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008183 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8184 << (unsigned) FnKind << FnDesc
8185 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8186 << (unsigned) isObjectArgument << I + 1;
8187 MaybeEmitInheritedConstructorNote(S, Fn);
8188 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008189 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008190 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008191
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008192 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008193 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008194 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008195 << (unsigned) FnKind << FnDesc
8196 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008197 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008198 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008199 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008200 return;
8201 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008202
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008203 if (isa<ObjCObjectPointerType>(CFromTy) &&
8204 isa<PointerType>(CToTy)) {
8205 Qualifiers FromQs = CFromTy.getQualifiers();
8206 Qualifiers ToQs = CToTy.getQualifiers();
8207 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8208 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8209 << (unsigned) FnKind << FnDesc
8210 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8211 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8212 MaybeEmitInheritedConstructorNote(S, Fn);
8213 return;
8214 }
8215 }
8216
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008217 // Emit the generic diagnostic and, optionally, add the hints to it.
8218 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8219 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008220 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008221 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8222 << (unsigned) (Cand->Fix.Kind);
8223
8224 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008225 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8226 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008227 FDiag << *HI;
8228 S.Diag(Fn->getLocation(), FDiag);
8229
Sebastian Redl08905022011-02-05 19:23:19 +00008230 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008231}
8232
8233void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8234 unsigned NumFormalArgs) {
8235 // TODO: treat calls to a missing default constructor as a special case
8236
8237 FunctionDecl *Fn = Cand->Function;
8238 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8239
8240 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008241
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008242 // With invalid overloaded operators, it's possible that we think we
8243 // have an arity mismatch when it fact it looks like we have the
8244 // right number of arguments, because only overloaded operators have
8245 // the weird behavior of overloading member and non-member functions.
8246 // Just don't report anything.
8247 if (Fn->isInvalidDecl() &&
8248 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8249 return;
8250
John McCall6a61b522010-01-13 09:16:55 +00008251 // at least / at most / exactly
8252 unsigned mode, modeCount;
8253 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008254 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8255 (Cand->FailureKind == ovl_fail_bad_deduction &&
8256 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008257 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00008258 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008259 mode = 0; // "at least"
8260 else
8261 mode = 2; // "exactly"
8262 modeCount = MinParams;
8263 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008264 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8265 (Cand->FailureKind == ovl_fail_bad_deduction &&
8266 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00008267 if (MinParams != FnTy->getNumArgs())
8268 mode = 1; // "at most"
8269 else
8270 mode = 2; // "exactly"
8271 modeCount = FnTy->getNumArgs();
8272 }
8273
8274 std::string Description;
8275 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8276
Richard Smith10ff50d2012-05-11 05:16:41 +00008277 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8278 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8279 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8280 << Fn->getParamDecl(0) << NumFormalArgs;
8281 else
8282 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8283 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8284 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008285 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008286}
8287
John McCall8b9ed552010-02-01 18:53:26 +00008288/// Diagnose a failed template-argument deduction.
8289void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008290 unsigned NumArgs) {
John McCall8b9ed552010-02-01 18:53:26 +00008291 FunctionDecl *Fn = Cand->Function; // pattern
8292
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008293 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008294 NamedDecl *ParamD;
8295 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8296 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8297 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00008298 switch (Cand->DeductionFailure.Result) {
8299 case Sema::TDK_Success:
8300 llvm_unreachable("TDK_success while diagnosing bad deduction");
8301
8302 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008303 assert(ParamD && "no parameter found for incomplete deduction result");
8304 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8305 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00008306 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008307 return;
8308 }
8309
John McCall42d7d192010-08-05 09:05:08 +00008310 case Sema::TDK_Underqualified: {
8311 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8312 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8313
8314 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8315
8316 // Param will have been canonicalized, but it should just be a
8317 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008318 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008319 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008320 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008321 assert(S.Context.hasSameType(Param, NonCanonParam));
8322
8323 // Arg has also been canonicalized, but there's nothing we can do
8324 // about that. It also doesn't matter as much, because it won't
8325 // have any template parameters in it (because deduction isn't
8326 // done on dependent types).
8327 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8328
8329 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8330 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00008331 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00008332 return;
8333 }
8334
8335 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008336 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008337 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008338 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008339 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008340 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008341 which = 1;
8342 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008343 which = 2;
8344 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008345
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008346 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008347 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008348 << *Cand->DeductionFailure.getFirstArg()
8349 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00008350 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008351 return;
8352 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008353
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008354 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008355 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008356 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008357 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008358 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8359 << ParamD->getDeclName();
8360 else {
8361 int index = 0;
8362 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8363 index = TTP->getIndex();
8364 else if (NonTypeTemplateParmDecl *NTTP
8365 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8366 index = NTTP->getIndex();
8367 else
8368 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008369 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008370 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8371 << (index + 1);
8372 }
Sebastian Redl08905022011-02-05 19:23:19 +00008373 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008374 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008375
Douglas Gregor02eb4832010-05-08 18:13:28 +00008376 case Sema::TDK_TooManyArguments:
8377 case Sema::TDK_TooFewArguments:
8378 DiagnoseArityMismatch(S, Cand, NumArgs);
8379 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008380
8381 case Sema::TDK_InstantiationDepth:
8382 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00008383 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008384 return;
8385
8386 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00008387 // Format the template argument list into the argument string.
8388 llvm::SmallString<128> TemplateArgString;
8389 if (TemplateArgumentList *Args =
8390 Cand->DeductionFailure.getTemplateArgumentList()) {
8391 TemplateArgString = " ";
8392 TemplateArgString += S.getTemplateArgumentBindingsText(
8393 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8394 }
8395
Richard Smith6f8d2c62012-05-09 05:17:00 +00008396 // If this candidate was disabled by enable_if, say so.
8397 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8398 if (PDiag && PDiag->second.getDiagID() ==
8399 diag::err_typename_nested_not_found_enable_if) {
8400 // FIXME: Use the source range of the condition, and the fully-qualified
8401 // name of the enable_if template. These are both present in PDiag.
8402 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8403 << "'enable_if'" << TemplateArgString;
8404 return;
8405 }
8406
Richard Smith9ca64612012-05-07 09:03:25 +00008407 // Format the SFINAE diagnostic into the argument string.
8408 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8409 // formatted message in another diagnostic.
8410 llvm::SmallString<128> SFINAEArgString;
8411 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008412 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00008413 SFINAEArgString = ": ";
8414 R = SourceRange(PDiag->first, PDiag->first);
8415 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8416 }
8417
Douglas Gregord09efd42010-05-08 20:07:26 +00008418 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smith9ca64612012-05-07 09:03:25 +00008419 << TemplateArgString << SFINAEArgString << R;
Sebastian Redl08905022011-02-05 19:23:19 +00008420 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008421 return;
8422 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008423
John McCall8b9ed552010-02-01 18:53:26 +00008424 // TODO: diagnose these individually, then kill off
8425 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00008426 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00008427 case Sema::TDK_FailedOverloadResolution:
8428 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00008429 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008430 return;
8431 }
8432}
8433
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008434/// CUDA: diagnose an invalid call across targets.
8435void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8436 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8437 FunctionDecl *Callee = Cand->Function;
8438
8439 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8440 CalleeTarget = S.IdentifyCUDATarget(Callee);
8441
8442 std::string FnDesc;
8443 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8444
8445 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8446 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8447}
8448
John McCall8b9ed552010-02-01 18:53:26 +00008449/// Generates a 'note' diagnostic for an overload candidate. We've
8450/// already generated a primary error at the call site.
8451///
8452/// It really does need to be a single diagnostic with its caret
8453/// pointed at the candidate declaration. Yes, this creates some
8454/// major challenges of technical writing. Yes, this makes pointing
8455/// out problems with specific arguments quite awkward. It's still
8456/// better than generating twenty screens of text for every failed
8457/// overload.
8458///
8459/// It would be great to be able to express per-candidate problems
8460/// more richly for those diagnostic clients that cared, but we'd
8461/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00008462void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008463 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00008464 FunctionDecl *Fn = Cand->Function;
8465
John McCall12f97bc2010-01-08 04:41:39 +00008466 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008467 if (Cand->Viable && (Fn->isDeleted() ||
8468 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00008469 std::string FnDesc;
8470 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00008471
8472 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00008473 << FnKind << FnDesc
8474 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00008475 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00008476 return;
John McCall12f97bc2010-01-08 04:41:39 +00008477 }
8478
John McCalle1ac8d12010-01-13 00:25:19 +00008479 // We don't really have anything else to say about viable candidates.
8480 if (Cand->Viable) {
8481 S.NoteOverloadCandidate(Fn);
8482 return;
8483 }
John McCall0d1da222010-01-12 00:44:57 +00008484
John McCall6a61b522010-01-13 09:16:55 +00008485 switch (Cand->FailureKind) {
8486 case ovl_fail_too_many_arguments:
8487 case ovl_fail_too_few_arguments:
8488 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00008489
John McCall6a61b522010-01-13 09:16:55 +00008490 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008491 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00008492
John McCallfe796dd2010-01-23 05:17:32 +00008493 case ovl_fail_trivial_conversion:
8494 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00008495 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00008496 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008497
John McCall65eb8792010-02-25 01:37:24 +00008498 case ovl_fail_bad_conversion: {
8499 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008500 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00008501 if (Cand->Conversions[I].isBad())
8502 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008503
John McCall6a61b522010-01-13 09:16:55 +00008504 // FIXME: this currently happens when we're called from SemaInit
8505 // when user-conversion overload fails. Figure out how to handle
8506 // those conditions and diagnose them well.
8507 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008508 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008509
8510 case ovl_fail_bad_target:
8511 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00008512 }
John McCalld3224162010-01-08 00:58:21 +00008513}
8514
8515void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8516 // Desugar the type of the surrogate down to a function type,
8517 // retaining as many typedefs as possible while still showing
8518 // the function type (and, therefore, its parameter types).
8519 QualType FnType = Cand->Surrogate->getConversionType();
8520 bool isLValueReference = false;
8521 bool isRValueReference = false;
8522 bool isPointer = false;
8523 if (const LValueReferenceType *FnTypeRef =
8524 FnType->getAs<LValueReferenceType>()) {
8525 FnType = FnTypeRef->getPointeeType();
8526 isLValueReference = true;
8527 } else if (const RValueReferenceType *FnTypeRef =
8528 FnType->getAs<RValueReferenceType>()) {
8529 FnType = FnTypeRef->getPointeeType();
8530 isRValueReference = true;
8531 }
8532 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8533 FnType = FnTypePtr->getPointeeType();
8534 isPointer = true;
8535 }
8536 // Desugar down to a function type.
8537 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8538 // Reconstruct the pointer/reference as appropriate.
8539 if (isPointer) FnType = S.Context.getPointerType(FnType);
8540 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8541 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8542
8543 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8544 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00008545 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00008546}
8547
8548void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie1d202a62012-10-08 01:11:04 +00008549 StringRef Opc,
John McCalld3224162010-01-08 00:58:21 +00008550 SourceLocation OpLoc,
8551 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008552 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00008553 std::string TypeStr("operator");
8554 TypeStr += Opc;
8555 TypeStr += "(";
8556 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00008557 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00008558 TypeStr += ")";
8559 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8560 } else {
8561 TypeStr += ", ";
8562 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8563 TypeStr += ")";
8564 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8565 }
8566}
8567
8568void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8569 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008570 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00008571 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8572 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00008573 if (ICS.isBad()) break; // all meaningless after first invalid
8574 if (!ICS.isAmbiguous()) continue;
8575
John McCall5c32be02010-08-24 20:38:10 +00008576 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008577 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00008578 }
8579}
8580
John McCall3712d9e2010-01-15 23:32:50 +00008581SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8582 if (Cand->Function)
8583 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00008584 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00008585 return Cand->Surrogate->getLocation();
8586 return SourceLocation();
8587}
8588
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008589static unsigned
8590RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00008591 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008592 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00008593 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008594
Douglas Gregorc5c01a62012-09-13 21:01:57 +00008595 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008596 case Sema::TDK_Incomplete:
8597 return 1;
8598
8599 case Sema::TDK_Underqualified:
8600 case Sema::TDK_Inconsistent:
8601 return 2;
8602
8603 case Sema::TDK_SubstitutionFailure:
8604 case Sema::TDK_NonDeducedMismatch:
8605 return 3;
8606
8607 case Sema::TDK_InstantiationDepth:
8608 case Sema::TDK_FailedOverloadResolution:
8609 return 4;
8610
8611 case Sema::TDK_InvalidExplicitArguments:
8612 return 5;
8613
8614 case Sema::TDK_TooManyArguments:
8615 case Sema::TDK_TooFewArguments:
8616 return 6;
8617 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008618 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008619}
8620
John McCallad2587a2010-01-12 00:48:53 +00008621struct CompareOverloadCandidatesForDisplay {
8622 Sema &S;
8623 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00008624
8625 bool operator()(const OverloadCandidate *L,
8626 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00008627 // Fast-path this check.
8628 if (L == R) return false;
8629
John McCall12f97bc2010-01-08 04:41:39 +00008630 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00008631 if (L->Viable) {
8632 if (!R->Viable) return true;
8633
8634 // TODO: introduce a tri-valued comparison for overload
8635 // candidates. Would be more worthwhile if we had a sort
8636 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00008637 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8638 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00008639 } else if (R->Viable)
8640 return false;
John McCall12f97bc2010-01-08 04:41:39 +00008641
John McCall3712d9e2010-01-15 23:32:50 +00008642 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00008643
John McCall3712d9e2010-01-15 23:32:50 +00008644 // Criteria by which we can sort non-viable candidates:
8645 if (!L->Viable) {
8646 // 1. Arity mismatches come after other candidates.
8647 if (L->FailureKind == ovl_fail_too_many_arguments ||
8648 L->FailureKind == ovl_fail_too_few_arguments)
8649 return false;
8650 if (R->FailureKind == ovl_fail_too_many_arguments ||
8651 R->FailureKind == ovl_fail_too_few_arguments)
8652 return true;
John McCall12f97bc2010-01-08 04:41:39 +00008653
John McCallfe796dd2010-01-23 05:17:32 +00008654 // 2. Bad conversions come first and are ordered by the number
8655 // of bad conversions and quality of good conversions.
8656 if (L->FailureKind == ovl_fail_bad_conversion) {
8657 if (R->FailureKind != ovl_fail_bad_conversion)
8658 return true;
8659
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008660 // The conversion that can be fixed with a smaller number of changes,
8661 // comes first.
8662 unsigned numLFixes = L->Fix.NumConversionsFixed;
8663 unsigned numRFixes = R->Fix.NumConversionsFixed;
8664 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8665 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008666 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008667 if (numLFixes < numRFixes)
8668 return true;
8669 else
8670 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008671 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008672
John McCallfe796dd2010-01-23 05:17:32 +00008673 // If there's any ordering between the defined conversions...
8674 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00008675 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00008676
8677 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00008678 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008679 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00008680 switch (CompareImplicitConversionSequences(S,
8681 L->Conversions[I],
8682 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00008683 case ImplicitConversionSequence::Better:
8684 leftBetter++;
8685 break;
8686
8687 case ImplicitConversionSequence::Worse:
8688 leftBetter--;
8689 break;
8690
8691 case ImplicitConversionSequence::Indistinguishable:
8692 break;
8693 }
8694 }
8695 if (leftBetter > 0) return true;
8696 if (leftBetter < 0) return false;
8697
8698 } else if (R->FailureKind == ovl_fail_bad_conversion)
8699 return false;
8700
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008701 if (L->FailureKind == ovl_fail_bad_deduction) {
8702 if (R->FailureKind != ovl_fail_bad_deduction)
8703 return true;
8704
8705 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8706 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00008707 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00008708 } else if (R->FailureKind == ovl_fail_bad_deduction)
8709 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008710
John McCall3712d9e2010-01-15 23:32:50 +00008711 // TODO: others?
8712 }
8713
8714 // Sort everything else by location.
8715 SourceLocation LLoc = GetLocationForCandidate(L);
8716 SourceLocation RLoc = GetLocationForCandidate(R);
8717
8718 // Put candidates without locations (e.g. builtins) at the end.
8719 if (LLoc.isInvalid()) return false;
8720 if (RLoc.isInvalid()) return true;
8721
8722 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00008723 }
8724};
8725
John McCallfe796dd2010-01-23 05:17:32 +00008726/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008727/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00008728void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008729 llvm::ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00008730 assert(!Cand->Viable);
8731
8732 // Don't do anything on failures other than bad conversion.
8733 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8734
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008735 // We only want the FixIts if all the arguments can be corrected.
8736 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00008737 // Use a implicit copy initialization to check conversion fixes.
8738 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008739
John McCallfe796dd2010-01-23 05:17:32 +00008740 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00008741 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008742 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00008743 while (true) {
8744 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8745 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008746 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00008747 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00008748 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008749 }
John McCallfe796dd2010-01-23 05:17:32 +00008750 }
8751
8752 if (ConvIdx == ConvCount)
8753 return;
8754
John McCall65eb8792010-02-25 01:37:24 +00008755 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8756 "remaining conversion is initialized?");
8757
Douglas Gregoradc7a702010-04-16 17:45:54 +00008758 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00008759 // operation somehow.
8760 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00008761
8762 const FunctionProtoType* Proto;
8763 unsigned ArgIdx = ConvIdx;
8764
8765 if (Cand->IsSurrogate) {
8766 QualType ConvType
8767 = Cand->Surrogate->getConversionType().getNonReferenceType();
8768 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8769 ConvType = ConvPtrType->getPointeeType();
8770 Proto = ConvType->getAs<FunctionProtoType>();
8771 ArgIdx--;
8772 } else if (Cand->Function) {
8773 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8774 if (isa<CXXMethodDecl>(Cand->Function) &&
8775 !isa<CXXConstructorDecl>(Cand->Function))
8776 ArgIdx--;
8777 } else {
8778 // Builtin binary operator with a bad first conversion.
8779 assert(ConvCount <= 3);
8780 for (; ConvIdx != ConvCount; ++ConvIdx)
8781 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008782 = TryCopyInitialization(S, Args[ConvIdx],
8783 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008784 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008785 /*InOverloadResolution*/ true,
8786 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008787 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008788 return;
8789 }
8790
8791 // Fill in the rest of the conversions.
8792 unsigned NumArgsInProto = Proto->getNumArgs();
8793 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008794 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008795 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008796 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008797 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008798 /*InOverloadResolution=*/true,
8799 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008800 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008801 // Store the FixIt in the candidate if it exists.
8802 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008803 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008804 }
John McCallfe796dd2010-01-23 05:17:32 +00008805 else
8806 Cand->Conversions[ConvIdx].setEllipsis();
8807 }
8808}
8809
John McCalld3224162010-01-08 00:58:21 +00008810} // end anonymous namespace
8811
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008812/// PrintOverloadCandidates - When overload resolution fails, prints
8813/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008814/// set.
John McCall5c32be02010-08-24 20:38:10 +00008815void OverloadCandidateSet::NoteCandidates(Sema &S,
8816 OverloadCandidateDisplayKind OCD,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008817 llvm::ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00008818 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00008819 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008820 // Sort the candidates by viability and position. Sorting directly would
8821 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008822 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008823 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8824 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008825 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008826 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008827 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008828 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008829 if (Cand->Function || Cand->IsSurrogate)
8830 Cands.push_back(Cand);
8831 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8832 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008833 }
8834 }
8835
John McCallad2587a2010-01-12 00:48:53 +00008836 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008837 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008838
John McCall0d1da222010-01-12 00:44:57 +00008839 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008840
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008841 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00008842 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008843 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008844 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8845 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008846
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008847 // Set an arbitrary limit on the number of candidate functions we'll spam
8848 // the user with. FIXME: This limit should depend on details of the
8849 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00008850 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008851 break;
8852 }
8853 ++CandsShown;
8854
John McCalld3224162010-01-08 00:58:21 +00008855 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008856 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00008857 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008858 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008859 else {
8860 assert(Cand->Viable &&
8861 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008862 // Generally we only see ambiguities including viable builtin
8863 // operators if overload resolution got screwed up by an
8864 // ambiguous user-defined conversion.
8865 //
8866 // FIXME: It's quite possible for different conversions to see
8867 // different ambiguities, though.
8868 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008869 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008870 ReportedAmbiguousConversions = true;
8871 }
John McCalld3224162010-01-08 00:58:21 +00008872
John McCall0d1da222010-01-12 00:44:57 +00008873 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008874 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008875 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008876 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008877
8878 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008879 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008880}
8881
Douglas Gregorb491ed32011-02-19 21:32:49 +00008882// [PossiblyAFunctionType] --> [Return]
8883// NonFunctionType --> NonFunctionType
8884// R (A) --> R(A)
8885// R (*)(A) --> R (A)
8886// R (&)(A) --> R (A)
8887// R (S::*)(A) --> R (A)
8888QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8889 QualType Ret = PossiblyAFunctionType;
8890 if (const PointerType *ToTypePtr =
8891 PossiblyAFunctionType->getAs<PointerType>())
8892 Ret = ToTypePtr->getPointeeType();
8893 else if (const ReferenceType *ToTypeRef =
8894 PossiblyAFunctionType->getAs<ReferenceType>())
8895 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008896 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008897 PossiblyAFunctionType->getAs<MemberPointerType>())
8898 Ret = MemTypePtr->getPointeeType();
8899 Ret =
8900 Context.getCanonicalType(Ret).getUnqualifiedType();
8901 return Ret;
8902}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008903
Douglas Gregorb491ed32011-02-19 21:32:49 +00008904// A helper class to help with address of function resolution
8905// - allows us to avoid passing around all those ugly parameters
8906class AddressOfFunctionResolver
8907{
8908 Sema& S;
8909 Expr* SourceExpr;
8910 const QualType& TargetType;
8911 QualType TargetFunctionType; // Extracted function type from target type
8912
8913 bool Complain;
8914 //DeclAccessPair& ResultFunctionAccessPair;
8915 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008916
Douglas Gregorb491ed32011-02-19 21:32:49 +00008917 bool TargetTypeIsNonStaticMemberFunction;
8918 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008919
Douglas Gregorb491ed32011-02-19 21:32:49 +00008920 OverloadExpr::FindResult OvlExprInfo;
8921 OverloadExpr *OvlExpr;
8922 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008923 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008924
Douglas Gregorb491ed32011-02-19 21:32:49 +00008925public:
8926 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8927 const QualType& TargetType, bool Complain)
8928 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8929 Complain(Complain), Context(S.getASTContext()),
8930 TargetTypeIsNonStaticMemberFunction(
8931 !!TargetType->getAs<MemberPointerType>()),
8932 FoundNonTemplateFunction(false),
8933 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8934 OvlExpr(OvlExprInfo.Expression)
8935 {
8936 ExtractUnqualifiedFunctionTypeFromTargetType();
8937
8938 if (!TargetFunctionType->isFunctionType()) {
8939 if (OvlExpr->hasExplicitTemplateArgs()) {
8940 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008941 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008942 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008943
8944 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8945 if (!Method->isStatic()) {
8946 // If the target type is a non-function type and the function
8947 // found is a non-static member function, pretend as if that was
8948 // the target, it's the only possible type to end up with.
8949 TargetTypeIsNonStaticMemberFunction = true;
8950
8951 // And skip adding the function if its not in the proper form.
8952 // We'll diagnose this due to an empty set of functions.
8953 if (!OvlExprInfo.HasFormOfMemberPointer)
8954 return;
8955 }
8956 }
8957
Douglas Gregorb491ed32011-02-19 21:32:49 +00008958 Matches.push_back(std::make_pair(dap,Fn));
8959 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008960 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008961 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008962 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008963
8964 if (OvlExpr->hasExplicitTemplateArgs())
8965 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008966
Douglas Gregorb491ed32011-02-19 21:32:49 +00008967 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8968 // C++ [over.over]p4:
8969 // If more than one function is selected, [...]
8970 if (Matches.size() > 1) {
8971 if (FoundNonTemplateFunction)
8972 EliminateAllTemplateMatches();
8973 else
8974 EliminateAllExceptMostSpecializedTemplate();
8975 }
8976 }
8977 }
8978
8979private:
8980 bool isTargetTypeAFunction() const {
8981 return TargetFunctionType->isFunctionType();
8982 }
8983
8984 // [ToType] [Return]
8985
8986 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8987 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8988 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8989 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8990 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8991 }
8992
8993 // return true if any matching specializations were found
8994 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8995 const DeclAccessPair& CurAccessFunPair) {
8996 if (CXXMethodDecl *Method
8997 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8998 // Skip non-static function templates when converting to pointer, and
8999 // static when converting to member pointer.
9000 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9001 return false;
9002 }
9003 else if (TargetTypeIsNonStaticMemberFunction)
9004 return false;
9005
9006 // C++ [over.over]p2:
9007 // If the name is a function template, template argument deduction is
9008 // done (14.8.2.2), and if the argument deduction succeeds, the
9009 // resulting template argument list is used to generate a single
9010 // function template specialization, which is added to the set of
9011 // overloaded functions considered.
9012 FunctionDecl *Specialization = 0;
Craig Toppere6706e42012-09-19 02:26:47 +00009013 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009014 if (Sema::TemplateDeductionResult Result
9015 = S.DeduceTemplateArguments(FunctionTemplate,
9016 &OvlExplicitTemplateArgs,
9017 TargetFunctionType, Specialization,
9018 Info)) {
9019 // FIXME: make a note of the failed deduction for diagnostics.
9020 (void)Result;
9021 return false;
9022 }
9023
9024 // Template argument deduction ensures that we have an exact match.
9025 // This function template specicalization works.
9026 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9027 assert(TargetFunctionType
9028 == Context.getCanonicalType(Specialization->getType()));
9029 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9030 return true;
9031 }
9032
9033 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9034 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009035 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009036 // Skip non-static functions when converting to pointer, and static
9037 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009038 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9039 return false;
9040 }
9041 else if (TargetTypeIsNonStaticMemberFunction)
9042 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009043
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009044 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009045 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009046 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9047 if (S.CheckCUDATarget(Caller, FunDecl))
9048 return false;
9049
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009050 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009051 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9052 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009053 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9054 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009055 Matches.push_back(std::make_pair(CurAccessFunPair,
9056 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009057 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009058 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009059 }
Mike Stump11289f42009-09-09 15:08:12 +00009060 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009061
9062 return false;
9063 }
9064
9065 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9066 bool Ret = false;
9067
9068 // If the overload expression doesn't have the form of a pointer to
9069 // member, don't try to convert it to a pointer-to-member type.
9070 if (IsInvalidFormOfPointerToMemberFunction())
9071 return false;
9072
9073 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9074 E = OvlExpr->decls_end();
9075 I != E; ++I) {
9076 // Look through any using declarations to find the underlying function.
9077 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9078
9079 // C++ [over.over]p3:
9080 // Non-member functions and static member functions match
9081 // targets of type "pointer-to-function" or "reference-to-function."
9082 // Nonstatic member functions match targets of
9083 // type "pointer-to-member-function."
9084 // Note that according to DR 247, the containing class does not matter.
9085 if (FunctionTemplateDecl *FunctionTemplate
9086 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9087 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9088 Ret = true;
9089 }
9090 // If we have explicit template arguments supplied, skip non-templates.
9091 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9092 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9093 Ret = true;
9094 }
9095 assert(Ret || Matches.empty());
9096 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009097 }
9098
Douglas Gregorb491ed32011-02-19 21:32:49 +00009099 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00009100 // [...] and any given function template specialization F1 is
9101 // eliminated if the set contains a second function template
9102 // specialization whose function template is more specialized
9103 // than the function template of F1 according to the partial
9104 // ordering rules of 14.5.5.2.
9105
9106 // The algorithm specified above is quadratic. We instead use a
9107 // two-pass algorithm (similar to the one used to identify the
9108 // best viable function in an overload set) that identifies the
9109 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00009110
9111 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9112 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9113 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009114
John McCall58cc69d2010-01-27 01:50:18 +00009115 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009116 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9117 TPOC_Other, 0, SourceExpr->getLocStart(),
9118 S.PDiag(),
9119 S.PDiag(diag::err_addr_ovl_ambiguous)
9120 << Matches[0].second->getDeclName(),
9121 S.PDiag(diag::note_ovl_candidate)
9122 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00009123 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009124
Douglas Gregorb491ed32011-02-19 21:32:49 +00009125 if (Result != MatchesCopy.end()) {
9126 // Make it the first and only element
9127 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9128 Matches[0].second = cast<FunctionDecl>(*Result);
9129 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00009130 }
9131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009132
Douglas Gregorb491ed32011-02-19 21:32:49 +00009133 void EliminateAllTemplateMatches() {
9134 // [...] any function template specializations in the set are
9135 // eliminated if the set also contains a non-template function, [...]
9136 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9137 if (Matches[I].second->getPrimaryTemplate() == 0)
9138 ++I;
9139 else {
9140 Matches[I] = Matches[--N];
9141 Matches.set_size(N);
9142 }
9143 }
9144 }
9145
9146public:
9147 void ComplainNoMatchesFound() const {
9148 assert(Matches.empty());
9149 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9150 << OvlExpr->getName() << TargetFunctionType
9151 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009152 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009153 }
9154
9155 bool IsInvalidFormOfPointerToMemberFunction() const {
9156 return TargetTypeIsNonStaticMemberFunction &&
9157 !OvlExprInfo.HasFormOfMemberPointer;
9158 }
9159
9160 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9161 // TODO: Should we condition this on whether any functions might
9162 // have matched, or is it more appropriate to do that in callers?
9163 // TODO: a fixit wouldn't hurt.
9164 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9165 << TargetType << OvlExpr->getSourceRange();
9166 }
9167
9168 void ComplainOfInvalidConversion() const {
9169 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9170 << OvlExpr->getName() << TargetType;
9171 }
9172
9173 void ComplainMultipleMatchesFound() const {
9174 assert(Matches.size() > 1);
9175 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9176 << OvlExpr->getName()
9177 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009178 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009179 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009180
9181 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9182
Douglas Gregorb491ed32011-02-19 21:32:49 +00009183 int getNumMatches() const { return Matches.size(); }
9184
9185 FunctionDecl* getMatchingFunctionDecl() const {
9186 if (Matches.size() != 1) return 0;
9187 return Matches[0].second;
9188 }
9189
9190 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9191 if (Matches.size() != 1) return 0;
9192 return &Matches[0].first;
9193 }
9194};
9195
9196/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9197/// an overloaded function (C++ [over.over]), where @p From is an
9198/// expression with overloaded function type and @p ToType is the type
9199/// we're trying to resolve to. For example:
9200///
9201/// @code
9202/// int f(double);
9203/// int f(int);
9204///
9205/// int (*pfd)(double) = f; // selects f(double)
9206/// @endcode
9207///
9208/// This routine returns the resulting FunctionDecl if it could be
9209/// resolved, and NULL otherwise. When @p Complain is true, this
9210/// routine will emit diagnostics if there is an error.
9211FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009212Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9213 QualType TargetType,
9214 bool Complain,
9215 DeclAccessPair &FoundResult,
9216 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009217 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009218
9219 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9220 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009221 int NumMatches = Resolver.getNumMatches();
9222 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009223 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009224 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9225 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9226 else
9227 Resolver.ComplainNoMatchesFound();
9228 }
9229 else if (NumMatches > 1 && Complain)
9230 Resolver.ComplainMultipleMatchesFound();
9231 else if (NumMatches == 1) {
9232 Fn = Resolver.getMatchingFunctionDecl();
9233 assert(Fn);
9234 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00009235 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00009236 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00009237 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009238
9239 if (pHadMultipleCandidates)
9240 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009241 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009242}
9243
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009244/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009245/// resolve that overloaded function expression down to a single function.
9246///
9247/// This routine can only resolve template-ids that refer to a single function
9248/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009249/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009250/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00009251FunctionDecl *
9252Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9253 bool Complain,
9254 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009255 // C++ [over.over]p1:
9256 // [...] [Note: any redundant set of parentheses surrounding the
9257 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009258 // C++ [over.over]p1:
9259 // [...] The overloaded function name can be preceded by the &
9260 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009261
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009262 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009263 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009264 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009265
9266 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009267 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009268
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009269 // Look through all of the overloaded functions, searching for one
9270 // whose type matches exactly.
9271 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009272 for (UnresolvedSetIterator I = ovl->decls_begin(),
9273 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009274 // C++0x [temp.arg.explicit]p3:
9275 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009276 // where deduction is not done, if a template argument list is
9277 // specified and it, along with any default template arguments,
9278 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009279 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009280 FunctionTemplateDecl *FunctionTemplate
9281 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009282
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009283 // C++ [over.over]p2:
9284 // If the name is a function template, template argument deduction is
9285 // done (14.8.2.2), and if the argument deduction succeeds, the
9286 // resulting template argument list is used to generate a single
9287 // function template specialization, which is added to the set of
9288 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009289 FunctionDecl *Specialization = 0;
Craig Toppere6706e42012-09-19 02:26:47 +00009290 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009291 if (TemplateDeductionResult Result
9292 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9293 Specialization, Info)) {
9294 // FIXME: make a note of the failed deduction for diagnostics.
9295 (void)Result;
9296 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009297 }
9298
John McCall0009fcc2011-04-26 20:42:42 +00009299 assert(Specialization && "no specialization and no error?");
9300
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009301 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009302 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009303 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00009304 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9305 << ovl->getName();
9306 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009307 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009308 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00009309 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009310
John McCall0009fcc2011-04-26 20:42:42 +00009311 Matched = Specialization;
9312 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009313 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009314
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009315 return Matched;
9316}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009317
Douglas Gregor1beec452011-03-12 01:48:56 +00009318
9319
9320
John McCall50a2c2c2011-10-11 23:14:30 +00009321// Resolve and fix an overloaded expression that can be resolved
9322// because it identifies a single function template specialization.
9323//
Douglas Gregor1beec452011-03-12 01:48:56 +00009324// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00009325//
9326// Return true if it was logically possible to so resolve the
9327// expression, regardless of whether or not it succeeded. Always
9328// returns true if 'complain' is set.
9329bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9330 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9331 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00009332 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00009333 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00009334 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00009335
John McCall50a2c2c2011-10-11 23:14:30 +00009336 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00009337
John McCall0009fcc2011-04-26 20:42:42 +00009338 DeclAccessPair found;
9339 ExprResult SingleFunctionExpression;
9340 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9341 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009342 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +00009343 SrcExpr = ExprError();
9344 return true;
9345 }
John McCall0009fcc2011-04-26 20:42:42 +00009346
9347 // It is only correct to resolve to an instance method if we're
9348 // resolving a form that's permitted to be a pointer to member.
9349 // Otherwise we'll end up making a bound member expression, which
9350 // is illegal in all the contexts we resolve like this.
9351 if (!ovl.HasFormOfMemberPointer &&
9352 isa<CXXMethodDecl>(fn) &&
9353 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00009354 if (!complain) return false;
9355
9356 Diag(ovl.Expression->getExprLoc(),
9357 diag::err_bound_member_function)
9358 << 0 << ovl.Expression->getSourceRange();
9359
9360 // TODO: I believe we only end up here if there's a mix of
9361 // static and non-static candidates (otherwise the expression
9362 // would have 'bound member' type, not 'overload' type).
9363 // Ideally we would note which candidate was chosen and why
9364 // the static candidates were rejected.
9365 SrcExpr = ExprError();
9366 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009367 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009368
Sylvestre Ledrua5202662012-07-31 06:56:50 +00009369 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +00009370 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00009371 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00009372
9373 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00009374 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00009375 SingleFunctionExpression =
9376 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00009377 if (SingleFunctionExpression.isInvalid()) {
9378 SrcExpr = ExprError();
9379 return true;
9380 }
9381 }
John McCall0009fcc2011-04-26 20:42:42 +00009382 }
9383
9384 if (!SingleFunctionExpression.isUsable()) {
9385 if (complain) {
9386 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9387 << ovl.Expression->getName()
9388 << DestTypeForComplaining
9389 << OpRangeForComplaining
9390 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00009391 NoteAllOverloadCandidates(SrcExpr.get());
9392
9393 SrcExpr = ExprError();
9394 return true;
9395 }
9396
9397 return false;
John McCall0009fcc2011-04-26 20:42:42 +00009398 }
9399
John McCall50a2c2c2011-10-11 23:14:30 +00009400 SrcExpr = SingleFunctionExpression;
9401 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009402}
9403
Douglas Gregorcabea402009-09-22 15:41:20 +00009404/// \brief Add a single candidate to the overload set.
9405static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00009406 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00009407 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009408 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009409 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00009410 bool PartialOverloading,
9411 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00009412 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00009413 if (isa<UsingShadowDecl>(Callee))
9414 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9415
Douglas Gregorcabea402009-09-22 15:41:20 +00009416 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00009417 if (ExplicitTemplateArgs) {
9418 assert(!KnownValid && "Explicit template arguments?");
9419 return;
9420 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009421 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9422 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009423 return;
John McCalld14a8642009-11-21 08:51:07 +00009424 }
9425
9426 if (FunctionTemplateDecl *FuncTemplate
9427 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00009428 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009429 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00009430 return;
9431 }
9432
Richard Smith95ce4f62011-06-26 22:19:54 +00009433 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00009434}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009435
Douglas Gregorcabea402009-09-22 15:41:20 +00009436/// \brief Add the overload candidates named by callee and/or found by argument
9437/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00009438void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009439 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009440 OverloadCandidateSet &CandidateSet,
9441 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00009442
9443#ifndef NDEBUG
9444 // Verify that ArgumentDependentLookup is consistent with the rules
9445 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00009446 //
Douglas Gregorcabea402009-09-22 15:41:20 +00009447 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9448 // and let Y be the lookup set produced by argument dependent
9449 // lookup (defined as follows). If X contains
9450 //
9451 // -- a declaration of a class member, or
9452 //
9453 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00009454 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00009455 //
9456 // -- a declaration that is neither a function or a function
9457 // template
9458 //
9459 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00009460
John McCall57500772009-12-16 12:17:52 +00009461 if (ULE->requiresADL()) {
9462 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9463 E = ULE->decls_end(); I != E; ++I) {
9464 assert(!(*I)->getDeclContext()->isRecord());
9465 assert(isa<UsingShadowDecl>(*I) ||
9466 !(*I)->getDeclContext()->isFunctionOrMethod());
9467 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00009468 }
9469 }
9470#endif
9471
John McCall57500772009-12-16 12:17:52 +00009472 // It would be nice to avoid this copy.
9473 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00009474 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009475 if (ULE->hasExplicitTemplateArgs()) {
9476 ULE->copyTemplateArgumentsInto(TABuffer);
9477 ExplicitTemplateArgs = &TABuffer;
9478 }
9479
9480 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9481 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009482 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9483 CandidateSet, PartialOverloading,
9484 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00009485
John McCall57500772009-12-16 12:17:52 +00009486 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00009487 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +00009488 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009489 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +00009490 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009491}
John McCalld681c392009-12-16 08:11:27 +00009492
Richard Smith998a5912011-06-05 22:42:48 +00009493/// Attempt to recover from an ill-formed use of a non-dependent name in a
9494/// template, where the non-dependent name was declared after the template
9495/// was defined. This is common in code written for a compilers which do not
9496/// correctly implement two-stage name lookup.
9497///
9498/// Returns true if a viable candidate was found and a diagnostic was issued.
9499static bool
9500DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9501 const CXXScopeSpec &SS, LookupResult &R,
9502 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009503 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009504 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9505 return false;
9506
9507 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +00009508 if (DC->isTransparentContext())
9509 continue;
9510
Richard Smith998a5912011-06-05 22:42:48 +00009511 SemaRef.LookupQualifiedName(R, DC);
9512
9513 if (!R.empty()) {
9514 R.suppressDiagnostics();
9515
9516 if (isa<CXXRecordDecl>(DC)) {
9517 // Don't diagnose names we find in classes; we get much better
9518 // diagnostics for these from DiagnoseEmptyLookup.
9519 R.clear();
9520 return false;
9521 }
9522
9523 OverloadCandidateSet Candidates(FnLoc);
9524 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9525 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009526 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +00009527 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00009528
9529 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00009530 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00009531 // No viable functions. Don't bother the user with notes for functions
9532 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00009533 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00009534 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00009535 }
Richard Smith998a5912011-06-05 22:42:48 +00009536
9537 // Find the namespaces where ADL would have looked, and suggest
9538 // declaring the function there instead.
9539 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9540 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00009541 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +00009542 AssociatedNamespaces,
9543 AssociatedClasses);
Nick Lewyckya21719d2012-11-13 00:08:34 +00009544 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00009545 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Nick Lewyckya21719d2012-11-13 00:08:34 +00009546 DeclContext *Std = SemaRef.getStdNamespace();
9547 for (Sema::AssociatedNamespaceSet::iterator
9548 it = AssociatedNamespaces.begin(),
9549 end = AssociatedNamespaces.end(); it != end; ++it) {
9550 NamespaceDecl *Assoc = cast<NamespaceDecl>(*it);
9551 if ((!Std || !Std->Encloses(Assoc)) &&
9552 Assoc->getQualifiedNameAsString().find("__") == std::string::npos)
9553 SuggestedNamespaces.insert(Assoc);
Richard Smith998a5912011-06-05 22:42:48 +00009554 }
9555
9556 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9557 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00009558 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00009559 SemaRef.Diag(Best->Function->getLocation(),
9560 diag::note_not_found_by_two_phase_lookup)
9561 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00009562 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00009563 SemaRef.Diag(Best->Function->getLocation(),
9564 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00009565 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00009566 } else {
9567 // FIXME: It would be useful to list the associated namespaces here,
9568 // but the diagnostics infrastructure doesn't provide a way to produce
9569 // a localized representation of a list of items.
9570 SemaRef.Diag(Best->Function->getLocation(),
9571 diag::note_not_found_by_two_phase_lookup)
9572 << R.getLookupName() << 2;
9573 }
9574
9575 // Try to recover by calling this function.
9576 return true;
9577 }
9578
9579 R.clear();
9580 }
9581
9582 return false;
9583}
9584
9585/// Attempt to recover from ill-formed use of a non-dependent operator in a
9586/// template, where the non-dependent operator was declared after the template
9587/// was defined.
9588///
9589/// Returns true if a viable candidate was found and a diagnostic was issued.
9590static bool
9591DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9592 SourceLocation OpLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009593 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009594 DeclarationName OpName =
9595 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9596 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9597 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009598 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +00009599}
9600
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009601namespace {
9602// Callback to limit the allowed keywords and to only accept typo corrections
9603// that are keywords or whose decls refer to functions (or template functions)
9604// that accept the given number of arguments.
9605class RecoveryCallCCC : public CorrectionCandidateCallback {
9606 public:
9607 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9608 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009609 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009610 WantRemainingKeywords = false;
9611 }
9612
9613 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9614 if (!candidate.getCorrectionDecl())
9615 return candidate.isKeyword();
9616
9617 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9618 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9619 FunctionDecl *FD = 0;
9620 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9621 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9622 FD = FTD->getTemplatedDecl();
9623 if (!HasExplicitTemplateArgs && !FD) {
9624 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9625 // If the Decl is neither a function nor a template function,
9626 // determine if it is a pointer or reference to a function. If so,
9627 // check against the number of arguments expected for the pointee.
9628 QualType ValType = cast<ValueDecl>(ND)->getType();
9629 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9630 ValType = ValType->getPointeeType();
9631 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9632 if (FPT->getNumArgs() == NumArgs)
9633 return true;
9634 }
9635 }
9636 if (FD && FD->getNumParams() >= NumArgs &&
9637 FD->getMinRequiredArguments() <= NumArgs)
9638 return true;
9639 }
9640 return false;
9641 }
9642
9643 private:
9644 unsigned NumArgs;
9645 bool HasExplicitTemplateArgs;
9646};
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009647
9648// Callback that effectively disabled typo correction
9649class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9650 public:
9651 NoTypoCorrectionCCC() {
9652 WantTypeSpecifiers = false;
9653 WantExpressionKeywords = false;
9654 WantCXXNamedCasts = false;
9655 WantRemainingKeywords = false;
9656 }
9657
9658 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9659 return false;
9660 }
9661};
Richard Smith88d67f32012-09-25 04:46:05 +00009662
9663class BuildRecoveryCallExprRAII {
9664 Sema &SemaRef;
9665public:
9666 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9667 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9668 SemaRef.IsBuildingRecoveryCallExpr = true;
9669 }
9670
9671 ~BuildRecoveryCallExprRAII() {
9672 SemaRef.IsBuildingRecoveryCallExpr = false;
9673 }
9674};
9675
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009676}
9677
John McCalld681c392009-12-16 08:11:27 +00009678/// Attempts to recover from a call where no functions were found.
9679///
9680/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00009681static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009682BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00009683 UnresolvedLookupExpr *ULE,
9684 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009685 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +00009686 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009687 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +00009688 // Do not try to recover if it is already building a recovery call.
9689 // This stops infinite loops for template instantiations like
9690 //
9691 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9692 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9693 //
9694 if (SemaRef.IsBuildingRecoveryCallExpr)
9695 return ExprError();
9696 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +00009697
9698 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00009699 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00009700 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +00009701
John McCall57500772009-12-16 12:17:52 +00009702 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00009703 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009704 if (ULE->hasExplicitTemplateArgs()) {
9705 ULE->copyTemplateArgumentsInto(TABuffer);
9706 ExplicitTemplateArgs = &TABuffer;
9707 }
9708
John McCalld681c392009-12-16 08:11:27 +00009709 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9710 Sema::LookupOrdinaryName);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009711 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009712 NoTypoCorrectionCCC RejectAll;
9713 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9714 (CorrectionCandidateCallback*)&Validator :
9715 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +00009716 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009717 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +00009718 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009719 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009720 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +00009721 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00009722
John McCall57500772009-12-16 12:17:52 +00009723 assert(!R.empty() && "lookup results empty despite recovery");
9724
9725 // Build an implicit member call if appropriate. Just drop the
9726 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00009727 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00009728 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009729 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9730 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009731 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009732 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009733 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00009734 else
9735 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9736
9737 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009738 return ExprError();
John McCall57500772009-12-16 12:17:52 +00009739
9740 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00009741 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00009742 // end up here.
John McCallb268a282010-08-23 23:25:46 +00009743 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009744 MultiExprArg(Args.data(), Args.size()),
9745 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00009746}
Douglas Gregor4038cf42010-06-08 17:35:15 +00009747
Sam Panzer0f384432012-08-21 00:52:01 +00009748/// \brief Constructs and populates an OverloadedCandidateSet from
9749/// the given function.
9750/// \returns true when an the ExprResult output parameter has been set.
9751bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9752 UnresolvedLookupExpr *ULE,
9753 Expr **Args, unsigned NumArgs,
9754 SourceLocation RParenLoc,
9755 OverloadCandidateSet *CandidateSet,
9756 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +00009757#ifndef NDEBUG
9758 if (ULE->requiresADL()) {
9759 // To do ADL, we must have found an unqualified name.
9760 assert(!ULE->getQualifier() && "qualified name with ADL");
9761
9762 // We don't perform ADL for implicit declarations of builtins.
9763 // Verify that this was correctly set up.
9764 FunctionDecl *F;
9765 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9766 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9767 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00009768 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009769
John McCall57500772009-12-16 12:17:52 +00009770 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009771 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +00009772 }
John McCall57500772009-12-16 12:17:52 +00009773#endif
9774
John McCall4124c492011-10-17 18:40:02 +00009775 UnbridgedCastsSet UnbridgedCasts;
Sam Panzer0f384432012-08-21 00:52:01 +00009776 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9777 *Result = ExprError();
9778 return true;
9779 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00009780
John McCall57500772009-12-16 12:17:52 +00009781 // Add the functions denoted by the callee to the set of candidate
9782 // functions, including those from argument-dependent lookup.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009783 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
Sam Panzer0f384432012-08-21 00:52:01 +00009784 *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00009785
9786 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00009787 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9788 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +00009789 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009790 // In Microsoft mode, if we are inside a template class member function then
9791 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00009792 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009793 // classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009794 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00009795 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00009796 CallExpr *CE = new (Context) CallExpr(Context, Fn,
9797 llvm::makeArrayRef(Args, NumArgs),
9798 Context.DependentTy, VK_RValue,
9799 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009800 CE->setTypeDependent(true);
Sam Panzer0f384432012-08-21 00:52:01 +00009801 *Result = Owned(CE);
9802 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009803 }
Sam Panzer0f384432012-08-21 00:52:01 +00009804 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +00009805 }
John McCalld681c392009-12-16 08:11:27 +00009806
John McCall4124c492011-10-17 18:40:02 +00009807 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +00009808 return false;
9809}
John McCall4124c492011-10-17 18:40:02 +00009810
Sam Panzer0f384432012-08-21 00:52:01 +00009811/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9812/// the completed call expression. If overload resolution fails, emits
9813/// diagnostics and returns ExprError()
9814static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9815 UnresolvedLookupExpr *ULE,
9816 SourceLocation LParenLoc,
9817 Expr **Args, unsigned NumArgs,
9818 SourceLocation RParenLoc,
9819 Expr *ExecConfig,
9820 OverloadCandidateSet *CandidateSet,
9821 OverloadCandidateSet::iterator *Best,
9822 OverloadingResult OverloadResult,
9823 bool AllowTypoCorrection) {
9824 if (CandidateSet->empty())
9825 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9826 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9827 RParenLoc, /*EmptyLookup=*/true,
9828 AllowTypoCorrection);
9829
9830 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +00009831 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +00009832 FunctionDecl *FDecl = (*Best)->Function;
9833 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9834 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9835 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9836 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9837 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9838 RParenLoc, ExecConfig);
John McCall57500772009-12-16 12:17:52 +00009839 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009840
Richard Smith998a5912011-06-05 22:42:48 +00009841 case OR_No_Viable_Function: {
9842 // Try to recover by looking for viable functions which the user might
9843 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +00009844 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009845 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9846 RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009847 /*EmptyLookup=*/false,
9848 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +00009849 if (!Recovery.isInvalid())
9850 return Recovery;
9851
Sam Panzer0f384432012-08-21 00:52:01 +00009852 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009853 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00009854 << ULE->getName() << Fn->getSourceRange();
Sam Panzer0f384432012-08-21 00:52:01 +00009855 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9856 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009857 break;
Richard Smith998a5912011-06-05 22:42:48 +00009858 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009859
9860 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +00009861 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00009862 << ULE->getName() << Fn->getSourceRange();
Sam Panzer0f384432012-08-21 00:52:01 +00009863 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9864 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009865 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009866
Sam Panzer0f384432012-08-21 00:52:01 +00009867 case OR_Deleted: {
9868 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9869 << (*Best)->Function->isDeleted()
9870 << ULE->getName()
9871 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9872 << Fn->getSourceRange();
9873 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9874 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00009875
Sam Panzer0f384432012-08-21 00:52:01 +00009876 // We emitted an error for the unvailable/deleted function call but keep
9877 // the call in the AST.
9878 FunctionDecl *FDecl = (*Best)->Function;
9879 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9880 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9881 RParenLoc, ExecConfig);
9882 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009883 }
9884
Douglas Gregorb412e172010-07-25 18:17:45 +00009885 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009886 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009887}
9888
Sam Panzer0f384432012-08-21 00:52:01 +00009889/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9890/// (which eventually refers to the declaration Func) and the call
9891/// arguments Args/NumArgs, attempt to resolve the function call down
9892/// to a specific function. If overload resolution succeeds, returns
9893/// the call expression produced by overload resolution.
9894/// Otherwise, emits diagnostics and returns ExprError.
9895ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9896 UnresolvedLookupExpr *ULE,
9897 SourceLocation LParenLoc,
9898 Expr **Args, unsigned NumArgs,
9899 SourceLocation RParenLoc,
9900 Expr *ExecConfig,
9901 bool AllowTypoCorrection) {
9902 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9903 ExprResult result;
9904
9905 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9906 &CandidateSet, &result))
9907 return result;
9908
9909 OverloadCandidateSet::iterator Best;
9910 OverloadingResult OverloadResult =
9911 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
9912
9913 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9914 RParenLoc, ExecConfig, &CandidateSet,
9915 &Best, OverloadResult,
9916 AllowTypoCorrection);
9917}
9918
John McCall4c4c1df2010-01-26 03:27:55 +00009919static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009920 return Functions.size() > 1 ||
9921 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9922}
9923
Douglas Gregor084d8552009-03-13 23:49:33 +00009924/// \brief Create a unary operation that may resolve to an overloaded
9925/// operator.
9926///
9927/// \param OpLoc The location of the operator itself (e.g., '*').
9928///
9929/// \param OpcIn The UnaryOperator::Opcode that describes this
9930/// operator.
9931///
James Dennett18348b62012-06-22 08:52:37 +00009932/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +00009933/// considered by overload resolution. The caller needs to build this
9934/// set based on the context using, e.g.,
9935/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9936/// set should not contain any member functions; those will be added
9937/// by CreateOverloadedUnaryOp().
9938///
James Dennett91738ff2012-06-22 10:32:46 +00009939/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009940ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009941Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9942 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009943 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009944 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009945
9946 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9947 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9948 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009949 // TODO: provide better source location info.
9950 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009951
John McCall4124c492011-10-17 18:40:02 +00009952 if (checkPlaceholderForOverload(*this, Input))
9953 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009954
Douglas Gregor084d8552009-03-13 23:49:33 +00009955 Expr *Args[2] = { Input, 0 };
9956 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009957
Douglas Gregor084d8552009-03-13 23:49:33 +00009958 // For post-increment and post-decrement, add the implicit '0' as
9959 // the second argument, so that we know this is a post-increment or
9960 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009961 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009962 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009963 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9964 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009965 NumArgs = 2;
9966 }
9967
9968 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009969 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009970 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009971 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009972 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009973 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009974 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009975
John McCall58cc69d2010-01-27 01:50:18 +00009976 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009977 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009978 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009979 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009980 /*ADL*/ true, IsOverloaded(Fns),
9981 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009982 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +00009983 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor084d8552009-03-13 23:49:33 +00009984 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009985 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +00009986 OpLoc, false));
Douglas Gregor084d8552009-03-13 23:49:33 +00009987 }
9988
9989 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009990 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009991
9992 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009993 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9994 false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009995
9996 // Add operator candidates that are member functions.
9997 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9998
John McCall4c4c1df2010-01-26 03:27:55 +00009999 // Add candidates from ADL.
10000 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010001 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall4c4c1df2010-01-26 03:27:55 +000010002 /*ExplicitTemplateArgs*/ 0,
10003 CandidateSet);
10004
Douglas Gregor084d8552009-03-13 23:49:33 +000010005 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +000010006 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010007
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010008 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10009
Douglas Gregor084d8552009-03-13 23:49:33 +000010010 // Perform overload resolution.
10011 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010012 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010013 case OR_Success: {
10014 // We found a built-in operator or an overloaded operator.
10015 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010016
Douglas Gregor084d8552009-03-13 23:49:33 +000010017 if (FnDecl) {
10018 // We matched an overloaded operator. Build a call to that
10019 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010020
Eli Friedmanfa0df832012-02-02 03:46:19 +000010021 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010022
Douglas Gregor084d8552009-03-13 23:49:33 +000010023 // Convert the arguments.
10024 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +000010025 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010026
John Wiegley01296292011-04-08 18:41:53 +000010027 ExprResult InputRes =
10028 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10029 Best->FoundDecl, Method);
10030 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010031 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010032 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010033 } else {
10034 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010035 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010036 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010037 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010038 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010039 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010040 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010041 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010042 return ExprError();
John McCallb268a282010-08-23 23:25:46 +000010043 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010044 }
10045
John McCall4fa0d5f2010-05-06 18:15:07 +000010046 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10047
John McCall7decc9e2010-11-18 06:31:45 +000010048 // Determine the result type.
10049 QualType ResultTy = FnDecl->getResultType();
10050 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10051 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +000010052
Douglas Gregor084d8552009-03-13 23:49:33 +000010053 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010054 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010055 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010056 if (FnExpr.isInvalid())
10057 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000010058
Eli Friedman030eee42009-11-18 03:58:17 +000010059 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000010060 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010061 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000010062 llvm::makeArrayRef(Args, NumArgs),
Lang Hames5de91cc2012-10-02 04:45:10 +000010063 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000010064
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010065 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +000010066 FnDecl))
10067 return ExprError();
10068
John McCallb268a282010-08-23 23:25:46 +000010069 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000010070 } else {
10071 // We matched a built-in operator. Convert the arguments, then
10072 // break out so that we will build the appropriate built-in
10073 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010074 ExprResult InputRes =
10075 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10076 Best->Conversions[0], AA_Passing);
10077 if (InputRes.isInvalid())
10078 return ExprError();
10079 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010080 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000010081 }
John Wiegley01296292011-04-08 18:41:53 +000010082 }
10083
10084 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000010085 // This is an erroneous use of an operator which can be overloaded by
10086 // a non-member function. Check for non-member operators which were
10087 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010088 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10089 llvm::makeArrayRef(Args, NumArgs)))
Richard Smith998a5912011-06-05 22:42:48 +000010090 // FIXME: Recover by calling the found function.
10091 return ExprError();
10092
John Wiegley01296292011-04-08 18:41:53 +000010093 // No viable function; fall through to handling this as a
10094 // built-in operator, which will produce an error message for us.
10095 break;
10096
10097 case OR_Ambiguous:
10098 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10099 << UnaryOperator::getOpcodeStr(Opc)
10100 << Input->getType()
10101 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010102 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10103 llvm::makeArrayRef(Args, NumArgs),
John Wiegley01296292011-04-08 18:41:53 +000010104 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10105 return ExprError();
10106
10107 case OR_Deleted:
10108 Diag(OpLoc, diag::err_ovl_deleted_oper)
10109 << Best->Function->isDeleted()
10110 << UnaryOperator::getOpcodeStr(Opc)
10111 << getDeletedOrUnavailableSuffix(Best->Function)
10112 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010113 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10114 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010115 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010116 return ExprError();
10117 }
Douglas Gregor084d8552009-03-13 23:49:33 +000010118
10119 // Either we found no viable overloaded operator or we matched a
10120 // built-in operator. In either case, fall through to trying to
10121 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000010122 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000010123}
10124
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010125/// \brief Create a binary operation that may resolve to an overloaded
10126/// operator.
10127///
10128/// \param OpLoc The location of the operator itself (e.g., '+').
10129///
10130/// \param OpcIn The BinaryOperator::Opcode that describes this
10131/// operator.
10132///
James Dennett18348b62012-06-22 08:52:37 +000010133/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010134/// considered by overload resolution. The caller needs to build this
10135/// set based on the context using, e.g.,
10136/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10137/// set should not contain any member functions; those will be added
10138/// by CreateOverloadedBinOp().
10139///
10140/// \param LHS Left-hand argument.
10141/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000010142ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010143Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000010144 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000010145 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010146 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010147 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +000010148 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010149
10150 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10151 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10152 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10153
10154 // If either side is type-dependent, create an appropriate dependent
10155 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000010156 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000010157 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010158 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000010159 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000010160 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +000010161 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +000010162 Context.DependentTy,
10163 VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +000010164 OpLoc,
10165 FPFeatures.fp_contract));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010166
Douglas Gregor5287f092009-11-05 00:51:44 +000010167 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10168 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010169 VK_LValue,
10170 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +000010171 Context.DependentTy,
10172 Context.DependentTy,
Lang Hames5de91cc2012-10-02 04:45:10 +000010173 OpLoc,
10174 FPFeatures.fp_contract));
Douglas Gregor5287f092009-11-05 00:51:44 +000010175 }
John McCall4c4c1df2010-01-26 03:27:55 +000010176
10177 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +000010178 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010179 // TODO: provide better source location info in DNLoc component.
10180 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000010181 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000010182 = UnresolvedLookupExpr::Create(Context, NamingClass,
10183 NestedNameSpecifierLoc(), OpNameInfo,
10184 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010185 Fns.begin(), Fns.end());
Lang Hames5de91cc2012-10-02 04:45:10 +000010186 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10187 Context.DependentTy, VK_RValue,
10188 OpLoc, FPFeatures.fp_contract));
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010189 }
10190
John McCall4124c492011-10-17 18:40:02 +000010191 // Always do placeholder-like conversions on the RHS.
10192 if (checkPlaceholderForOverload(*this, Args[1]))
10193 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010194
John McCall526ab472011-10-25 17:37:35 +000010195 // Do placeholder-like conversion on the LHS; note that we should
10196 // not get here with a PseudoObject LHS.
10197 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000010198 if (checkPlaceholderForOverload(*this, Args[0]))
10199 return ExprError();
10200
Sebastian Redl6a96bf72009-11-18 23:10:33 +000010201 // If this is the assignment operator, we only perform overload resolution
10202 // if the left-hand side is a class or enumeration type. This is actually
10203 // a hack. The standard requires that we do overload resolution between the
10204 // various built-in candidates, but as DR507 points out, this can lead to
10205 // problems. So we do it this way, which pretty much follows what GCC does.
10206 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000010207 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000010208 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010209
John McCalle26a8722010-12-04 08:14:53 +000010210 // If this is the .* operator, which is not overloadable, just
10211 // create a built-in binary operator.
10212 if (Opc == BO_PtrMemD)
10213 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10214
Douglas Gregor084d8552009-03-13 23:49:33 +000010215 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010216 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010217
10218 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010219 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010220
10221 // Add operator candidates that are member functions.
10222 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10223
John McCall4c4c1df2010-01-26 03:27:55 +000010224 // Add candidates from ADL.
10225 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010226 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +000010227 /*ExplicitTemplateArgs*/ 0,
10228 CandidateSet);
10229
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010230 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +000010231 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010232
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010233 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10234
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010235 // Perform overload resolution.
10236 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010237 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000010238 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010239 // We found a built-in operator or an overloaded operator.
10240 FunctionDecl *FnDecl = Best->Function;
10241
10242 if (FnDecl) {
10243 // We matched an overloaded operator. Build a call to that
10244 // operator.
10245
Eli Friedmanfa0df832012-02-02 03:46:19 +000010246 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010247
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010248 // Convert the arguments.
10249 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000010250 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000010251 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010252
Chandler Carruth8e543b32010-12-12 08:17:55 +000010253 ExprResult Arg1 =
10254 PerformCopyInitialization(
10255 InitializedEntity::InitializeParameter(Context,
10256 FnDecl->getParamDecl(0)),
10257 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010258 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010259 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010260
John Wiegley01296292011-04-08 18:41:53 +000010261 ExprResult Arg0 =
10262 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10263 Best->FoundDecl, Method);
10264 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010265 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010266 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010267 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010268 } else {
10269 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000010270 ExprResult Arg0 = PerformCopyInitialization(
10271 InitializedEntity::InitializeParameter(Context,
10272 FnDecl->getParamDecl(0)),
10273 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010274 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010275 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010276
Chandler Carruth8e543b32010-12-12 08:17:55 +000010277 ExprResult Arg1 =
10278 PerformCopyInitialization(
10279 InitializedEntity::InitializeParameter(Context,
10280 FnDecl->getParamDecl(1)),
10281 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010282 if (Arg1.isInvalid())
10283 return ExprError();
10284 Args[0] = LHS = Arg0.takeAs<Expr>();
10285 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010286 }
10287
John McCall4fa0d5f2010-05-06 18:15:07 +000010288 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10289
John McCall7decc9e2010-11-18 06:31:45 +000010290 // Determine the result type.
10291 QualType ResultTy = FnDecl->getResultType();
10292 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10293 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010294
10295 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010296 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10297 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010298 if (FnExpr.isInvalid())
10299 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010300
John McCallb268a282010-08-23 23:25:46 +000010301 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010302 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000010303 Args, ResultTy, VK, OpLoc,
10304 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010305
10306 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010307 FnDecl))
10308 return ExprError();
10309
John McCallb268a282010-08-23 23:25:46 +000010310 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010311 } else {
10312 // We matched a built-in operator. Convert the arguments, then
10313 // break out so that we will build the appropriate built-in
10314 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010315 ExprResult ArgsRes0 =
10316 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10317 Best->Conversions[0], AA_Passing);
10318 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010319 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010320 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010321
John Wiegley01296292011-04-08 18:41:53 +000010322 ExprResult ArgsRes1 =
10323 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10324 Best->Conversions[1], AA_Passing);
10325 if (ArgsRes1.isInvalid())
10326 return ExprError();
10327 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010328 break;
10329 }
10330 }
10331
Douglas Gregor66950a32009-09-30 21:46:01 +000010332 case OR_No_Viable_Function: {
10333 // C++ [over.match.oper]p9:
10334 // If the operator is the operator , [...] and there are no
10335 // viable functions, then the operator is assumed to be the
10336 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000010337 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000010338 break;
10339
Chandler Carruth8e543b32010-12-12 08:17:55 +000010340 // For class as left operand for assignment or compound assigment
10341 // operator do not fall through to handling in built-in, but report that
10342 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000010343 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010344 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000010345 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000010346 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10347 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000010348 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +000010349 } else {
Richard Smith998a5912011-06-05 22:42:48 +000010350 // This is an erroneous use of an operator which can be overloaded by
10351 // a non-member function. Check for non-member operators which were
10352 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010353 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000010354 // FIXME: Recover by calling the found function.
10355 return ExprError();
10356
Douglas Gregor66950a32009-09-30 21:46:01 +000010357 // No viable function; try to create a built-in operation, which will
10358 // produce an error. Then, show the non-viable candidates.
10359 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000010360 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010361 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000010362 "C++ binary operator overloading is missing candidates!");
10363 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010364 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010365 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010366 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000010367 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010368
10369 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010370 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010371 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000010372 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000010373 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010374 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010375 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010376 return ExprError();
10377
10378 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000010379 if (isImplicitlyDeleted(Best->Function)) {
10380 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10381 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10382 << getSpecialMember(Method)
10383 << BinaryOperator::getOpcodeStr(Opc)
10384 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith6f1e2c62012-04-02 20:59:25 +000010385
10386 if (getSpecialMember(Method) != CXXInvalid) {
10387 // The user probably meant to call this special member. Just
10388 // explain why it's deleted.
10389 NoteDeletedFunction(Method);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010390 return ExprError();
10391 }
10392 } else {
10393 Diag(OpLoc, diag::err_ovl_deleted_oper)
10394 << Best->Function->isDeleted()
10395 << BinaryOperator::getOpcodeStr(Opc)
10396 << getDeletedOrUnavailableSuffix(Best->Function)
10397 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10398 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010399 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010400 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010401 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000010402 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010403
Douglas Gregor66950a32009-09-30 21:46:01 +000010404 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000010405 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010406}
10407
John McCalldadc5752010-08-24 06:29:42 +000010408ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000010409Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10410 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000010411 Expr *Base, Expr *Idx) {
10412 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000010413 DeclarationName OpName =
10414 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10415
10416 // If either side is type-dependent, create an appropriate dependent
10417 // expression.
10418 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10419
John McCall58cc69d2010-01-27 01:50:18 +000010420 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010421 // CHECKME: no 'operator' keyword?
10422 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10423 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000010424 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010425 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010426 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010427 /*ADL*/ true, /*Overloaded*/ false,
10428 UnresolvedSetIterator(),
10429 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000010430 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000010431
Sebastian Redladba46e2009-10-29 20:17:01 +000010432 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010433 Args,
Sebastian Redladba46e2009-10-29 20:17:01 +000010434 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010435 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000010436 RLoc, false));
Sebastian Redladba46e2009-10-29 20:17:01 +000010437 }
10438
John McCall4124c492011-10-17 18:40:02 +000010439 // Handle placeholders on both operands.
10440 if (checkPlaceholderForOverload(*this, Args[0]))
10441 return ExprError();
10442 if (checkPlaceholderForOverload(*this, Args[1]))
10443 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010444
Sebastian Redladba46e2009-10-29 20:17:01 +000010445 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010446 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010447
10448 // Subscript can only be overloaded as a member function.
10449
10450 // Add operator candidates that are member functions.
10451 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10452
10453 // Add builtin operator candidates.
10454 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10455
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010456 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10457
Sebastian Redladba46e2009-10-29 20:17:01 +000010458 // Perform overload resolution.
10459 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010460 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000010461 case OR_Success: {
10462 // We found a built-in operator or an overloaded operator.
10463 FunctionDecl *FnDecl = Best->Function;
10464
10465 if (FnDecl) {
10466 // We matched an overloaded operator. Build a call to that
10467 // operator.
10468
Eli Friedmanfa0df832012-02-02 03:46:19 +000010469 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010470
John McCalla0296f72010-03-19 07:35:19 +000010471 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010472 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +000010473
Sebastian Redladba46e2009-10-29 20:17:01 +000010474 // Convert the arguments.
10475 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000010476 ExprResult Arg0 =
10477 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10478 Best->FoundDecl, Method);
10479 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010480 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010481 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010482
Anders Carlssona68e51e2010-01-29 18:37:50 +000010483 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010484 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000010485 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010486 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000010487 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010488 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000010489 Owned(Args[1]));
10490 if (InputInit.isInvalid())
10491 return ExprError();
10492
10493 Args[1] = InputInit.takeAs<Expr>();
10494
Sebastian Redladba46e2009-10-29 20:17:01 +000010495 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +000010496 QualType ResultTy = FnDecl->getResultType();
10497 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10498 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +000010499
10500 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010501 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10502 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010503 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10504 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010505 OpLocInfo.getLoc(),
10506 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010507 if (FnExpr.isInvalid())
10508 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010509
John McCallb268a282010-08-23 23:25:46 +000010510 CXXOperatorCallExpr *TheCall =
10511 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010512 FnExpr.take(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000010513 ResultTy, VK, RLoc,
10514 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000010515
John McCallb268a282010-08-23 23:25:46 +000010516 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000010517 FnDecl))
10518 return ExprError();
10519
John McCallb268a282010-08-23 23:25:46 +000010520 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000010521 } else {
10522 // We matched a built-in operator. Convert the arguments, then
10523 // break out so that we will build the appropriate built-in
10524 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010525 ExprResult ArgsRes0 =
10526 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10527 Best->Conversions[0], AA_Passing);
10528 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010529 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010530 Args[0] = ArgsRes0.take();
10531
10532 ExprResult ArgsRes1 =
10533 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10534 Best->Conversions[1], AA_Passing);
10535 if (ArgsRes1.isInvalid())
10536 return ExprError();
10537 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010538
10539 break;
10540 }
10541 }
10542
10543 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000010544 if (CandidateSet.empty())
10545 Diag(LLoc, diag::err_ovl_no_oper)
10546 << Args[0]->getType() << /*subscript*/ 0
10547 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10548 else
10549 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10550 << Args[0]->getType()
10551 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010552 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010553 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000010554 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010555 }
10556
10557 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010558 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010559 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000010560 << Args[0]->getType() << Args[1]->getType()
10561 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010562 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010563 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010564 return ExprError();
10565
10566 case OR_Deleted:
10567 Diag(LLoc, diag::err_ovl_deleted_oper)
10568 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010569 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000010570 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010571 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010572 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010573 return ExprError();
10574 }
10575
10576 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000010577 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010578}
10579
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010580/// BuildCallToMemberFunction - Build a call to a member
10581/// function. MemExpr is the expression that refers to the member
10582/// function (and includes the object parameter), Args/NumArgs are the
10583/// arguments to the function call (not including the object
10584/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000010585/// expression refers to a non-static member function or an overloaded
10586/// member function.
John McCalldadc5752010-08-24 06:29:42 +000010587ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000010588Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10589 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +000010590 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000010591 assert(MemExprE->getType() == Context.BoundMemberTy ||
10592 MemExprE->getType() == Context.OverloadTy);
10593
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010594 // Dig out the member expression. This holds both the object
10595 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000010596 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010597
John McCall0009fcc2011-04-26 20:42:42 +000010598 // Determine whether this is a call to a pointer-to-member function.
10599 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10600 assert(op->getType() == Context.BoundMemberTy);
10601 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10602
10603 QualType fnType =
10604 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10605
10606 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10607 QualType resultType = proto->getCallResultType(Context);
10608 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10609
10610 // Check that the object type isn't more qualified than the
10611 // member function we're calling.
10612 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10613
10614 QualType objectType = op->getLHS()->getType();
10615 if (op->getOpcode() == BO_PtrMemI)
10616 objectType = objectType->castAs<PointerType>()->getPointeeType();
10617 Qualifiers objectQuals = objectType.getQualifiers();
10618
10619 Qualifiers difference = objectQuals - funcQuals;
10620 difference.removeObjCGCAttr();
10621 difference.removeAddressSpace();
10622 if (difference) {
10623 std::string qualsString = difference.getAsString();
10624 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10625 << fnType.getUnqualifiedType()
10626 << qualsString
10627 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10628 }
10629
10630 CXXMemberCallExpr *call
Benjamin Kramerc215e762012-08-24 11:54:20 +000010631 = new (Context) CXXMemberCallExpr(Context, MemExprE,
10632 llvm::makeArrayRef(Args, NumArgs),
John McCall0009fcc2011-04-26 20:42:42 +000010633 resultType, valueKind, RParenLoc);
10634
10635 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010636 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000010637 call, 0))
10638 return ExprError();
10639
10640 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10641 return ExprError();
10642
10643 return MaybeBindToTemporary(call);
10644 }
10645
John McCall4124c492011-10-17 18:40:02 +000010646 UnbridgedCastsSet UnbridgedCasts;
10647 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10648 return ExprError();
10649
John McCall10eae182009-11-30 22:42:35 +000010650 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010651 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000010652 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010653 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000010654 if (isa<MemberExpr>(NakedMemExpr)) {
10655 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000010656 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000010657 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010658 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000010659 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000010660 } else {
10661 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010662 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010663
John McCall6e9f8f62009-12-03 04:06:58 +000010664 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000010665 Expr::Classification ObjectClassification
10666 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10667 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000010668
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010669 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000010670 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000010671
John McCall2d74de92009-12-01 22:10:20 +000010672 // FIXME: avoid copy.
10673 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10674 if (UnresExpr->hasExplicitTemplateArgs()) {
10675 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10676 TemplateArgs = &TemplateArgsBuffer;
10677 }
10678
John McCall10eae182009-11-30 22:42:35 +000010679 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10680 E = UnresExpr->decls_end(); I != E; ++I) {
10681
John McCall6e9f8f62009-12-03 04:06:58 +000010682 NamedDecl *Func = *I;
10683 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10684 if (isa<UsingShadowDecl>(Func))
10685 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10686
Douglas Gregor02824322011-01-26 19:30:28 +000010687
Francois Pichet64225792011-01-18 05:04:39 +000010688 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010689 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010690 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10691 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000010692 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000010693 // If explicit template arguments were provided, we can't call a
10694 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000010695 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000010696 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010697
John McCalla0296f72010-03-19 07:35:19 +000010698 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010699 ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010700 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000010701 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010702 } else {
John McCall10eae182009-11-30 22:42:35 +000010703 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000010704 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010705 ObjectType, ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010706 llvm::makeArrayRef(Args, NumArgs),
10707 CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010708 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010709 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010710 }
Mike Stump11289f42009-09-09 15:08:12 +000010711
John McCall10eae182009-11-30 22:42:35 +000010712 DeclarationName DeclName = UnresExpr->getMemberName();
10713
John McCall4124c492011-10-17 18:40:02 +000010714 UnbridgedCasts.restore();
10715
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010716 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010717 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000010718 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010719 case OR_Success:
10720 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010721 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +000010722 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000010723 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010724 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010725 break;
10726
10727 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000010728 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010729 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010730 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010731 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10732 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010733 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010734 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010735
10736 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000010737 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010738 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010739 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10740 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010741 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010742 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010743
10744 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000010745 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000010746 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010747 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010748 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010749 << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010750 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10751 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010752 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010753 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010754 }
10755
John McCall16df1e52010-03-30 21:47:33 +000010756 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000010757
John McCall2d74de92009-12-01 22:10:20 +000010758 // If overload resolution picked a static member, build a
10759 // non-member call based on that function.
10760 if (Method->isStatic()) {
10761 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10762 Args, NumArgs, RParenLoc);
10763 }
10764
John McCall10eae182009-11-30 22:42:35 +000010765 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010766 }
10767
John McCall7decc9e2010-11-18 06:31:45 +000010768 QualType ResultType = Method->getResultType();
10769 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10770 ResultType = ResultType.getNonLValueExprType(Context);
10771
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010772 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010773 CXXMemberCallExpr *TheCall =
Benjamin Kramerc215e762012-08-24 11:54:20 +000010774 new (Context) CXXMemberCallExpr(Context, MemExprE,
10775 llvm::makeArrayRef(Args, NumArgs),
John McCall7decc9e2010-11-18 06:31:45 +000010776 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010777
Anders Carlssonc4859ba2009-10-10 00:06:20 +000010778 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010779 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000010780 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000010781 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010782
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010783 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000010784 // We only need to do this if there was actually an overload; otherwise
10785 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000010786 if (!Method->isStatic()) {
10787 ExprResult ObjectArg =
10788 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10789 FoundDecl, Method);
10790 if (ObjectArg.isInvalid())
10791 return ExprError();
10792 MemExpr->setBase(ObjectArg.take());
10793 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010794
10795 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000010796 const FunctionProtoType *Proto =
10797 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +000010798 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010799 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000010800 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010801
Eli Friedmanff4b4072012-02-18 04:48:30 +000010802 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10803
Richard Smith55ce3522012-06-25 20:30:08 +000010804 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000010805 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000010806
Anders Carlsson47061ee2011-05-06 14:25:31 +000010807 if ((isa<CXXConstructorDecl>(CurContext) ||
10808 isa<CXXDestructorDecl>(CurContext)) &&
10809 TheCall->getMethodDecl()->isPure()) {
10810 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10811
Chandler Carruth59259262011-06-27 08:31:58 +000010812 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000010813 Diag(MemExpr->getLocStart(),
10814 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10815 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10816 << MD->getParent()->getDeclName();
10817
10818 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000010819 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000010820 }
John McCallb268a282010-08-23 23:25:46 +000010821 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010822}
10823
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010824/// BuildCallToObjectOfClassType - Build a call to an object of class
10825/// type (C++ [over.call.object]), which can end up invoking an
10826/// overloaded function call operator (@c operator()) or performing a
10827/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000010828ExprResult
John Wiegley01296292011-04-08 18:41:53 +000010829Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000010830 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010831 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010832 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000010833 if (checkPlaceholderForOverload(*this, Obj))
10834 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010835 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000010836
10837 UnbridgedCastsSet UnbridgedCasts;
10838 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10839 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010840
John Wiegley01296292011-04-08 18:41:53 +000010841 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10842 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000010843
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010844 // C++ [over.call.object]p1:
10845 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000010846 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010847 // candidate functions includes at least the function call
10848 // operators of T. The function call operators of T are obtained by
10849 // ordinary lookup of the name operator() in the context of
10850 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000010851 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000010852 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010853
John Wiegley01296292011-04-08 18:41:53 +000010854 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010855 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010856 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010857
John McCall27b18f82009-11-17 02:14:36 +000010858 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10859 LookupQualifiedName(R, Record->getDecl());
10860 R.suppressDiagnostics();
10861
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010862 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000010863 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000010864 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10865 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000010866 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000010867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010868
Douglas Gregorab7897a2008-11-19 22:57:39 +000010869 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010870 // In addition, for each (non-explicit in C++0x) conversion function
10871 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000010872 //
10873 // operator conversion-type-id () cv-qualifier;
10874 //
10875 // where cv-qualifier is the same cv-qualification as, or a
10876 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000010877 // denotes the type "pointer to function of (P1,...,Pn) returning
10878 // R", or the type "reference to pointer to function of
10879 // (P1,...,Pn) returning R", or the type "reference to function
10880 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000010881 // is also considered as a candidate function. Similarly,
10882 // surrogate call functions are added to the set of candidate
10883 // functions for each conversion function declared in an
10884 // accessible base class provided the function is not hidden
10885 // within T by another intervening declaration.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000010886 std::pair<CXXRecordDecl::conversion_iterator,
10887 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000010888 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000010889 for (CXXRecordDecl::conversion_iterator
10890 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000010891 NamedDecl *D = *I;
10892 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10893 if (isa<UsingShadowDecl>(D))
10894 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010895
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010896 // Skip over templated conversion functions; they aren't
10897 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000010898 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010899 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000010900
John McCall6e9f8f62009-12-03 04:06:58 +000010901 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010902 if (!Conv->isExplicit()) {
10903 // Strip the reference type (if any) and then the pointer type (if
10904 // any) to get down to what might be a function type.
10905 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10906 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10907 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000010908
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010909 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10910 {
10911 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010912 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10913 CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010914 }
10915 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000010916 }
Mike Stump11289f42009-09-09 15:08:12 +000010917
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010918 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10919
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010920 // Perform overload resolution.
10921 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000010922 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000010923 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010924 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000010925 // Overload resolution succeeded; we'll build the appropriate call
10926 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010927 break;
10928
10929 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000010930 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010931 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000010932 << Object.get()->getType() << /*call*/ 1
10933 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000010934 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010935 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000010936 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010937 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010938 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10939 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010940 break;
10941
10942 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010943 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010944 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010945 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010946 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10947 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010948 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010949
10950 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010951 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010952 diag::err_ovl_deleted_object_call)
10953 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010954 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010955 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010956 << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010957 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10958 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010959 break;
Mike Stump11289f42009-09-09 15:08:12 +000010960 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010961
Douglas Gregorb412e172010-07-25 18:17:45 +000010962 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010963 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010964
John McCall4124c492011-10-17 18:40:02 +000010965 UnbridgedCasts.restore();
10966
Douglas Gregorab7897a2008-11-19 22:57:39 +000010967 if (Best->Function == 0) {
10968 // Since there is no function declaration, this is one of the
10969 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010970 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010971 = cast<CXXConversionDecl>(
10972 Best->Conversions[0].UserDefined.ConversionFunction);
10973
John Wiegley01296292011-04-08 18:41:53 +000010974 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010975 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010976
Douglas Gregorab7897a2008-11-19 22:57:39 +000010977 // We selected one of the surrogate functions that converts the
10978 // object parameter to a function pointer. Perform the conversion
10979 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010980
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010981 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010982 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010983 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10984 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010985 if (Call.isInvalid())
10986 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010987 // Record usage of conversion in an implicit cast.
10988 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10989 CK_UserDefinedConversion,
10990 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010991
Douglas Gregor668443e2011-01-20 00:18:04 +000010992 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010993 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010994 }
10995
Eli Friedmanfa0df832012-02-02 03:46:19 +000010996 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010997 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010998 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010999
Douglas Gregorab7897a2008-11-19 22:57:39 +000011000 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11001 // that calls this method, using Object for the implicit object
11002 // parameter and passing along the remaining arguments.
11003 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011004
11005 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011006 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011007 return ExprError();
11008
Chandler Carruth8e543b32010-12-12 08:17:55 +000011009 const FunctionProtoType *Proto =
11010 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011011
11012 unsigned NumArgsInProto = Proto->getNumArgs();
11013 unsigned NumArgsToCheck = NumArgs;
11014
11015 // Build the full argument list for the method call (the
11016 // implicit object parameter is placed at the beginning of the
11017 // list).
11018 Expr **MethodArgs;
11019 if (NumArgs < NumArgsInProto) {
11020 NumArgsToCheck = NumArgsInProto;
11021 MethodArgs = new Expr*[NumArgsInProto + 1];
11022 } else {
11023 MethodArgs = new Expr*[NumArgs + 1];
11024 }
John Wiegley01296292011-04-08 18:41:53 +000011025 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011026 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11027 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000011028
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011029 DeclarationNameInfo OpLocInfo(
11030 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11031 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011032 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011033 HadMultipleCandidates,
11034 OpLocInfo.getLoc(),
11035 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011036 if (NewFn.isInvalid())
11037 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011038
11039 // Once we've built TheCall, all of the expressions are properly
11040 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000011041 QualType ResultTy = Method->getResultType();
11042 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11043 ResultTy = ResultTy.getNonLValueExprType(Context);
11044
John McCallb268a282010-08-23 23:25:46 +000011045 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011046 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000011047 llvm::makeArrayRef(MethodArgs, NumArgs+1),
Lang Hames5de91cc2012-10-02 04:45:10 +000011048 ResultTy, VK, RParenLoc, false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011049 delete [] MethodArgs;
11050
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011051 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000011052 Method))
11053 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011054
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011055 // We may have default arguments. If so, we need to allocate more
11056 // slots in the call for them.
11057 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000011058 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011059 else if (NumArgs > NumArgsInProto)
11060 NumArgsToCheck = NumArgsInProto;
11061
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011062 bool IsError = false;
11063
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011064 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000011065 ExprResult ObjRes =
11066 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11067 Best->FoundDecl, Method);
11068 if (ObjRes.isInvalid())
11069 IsError = true;
11070 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011071 Object = ObjRes;
John Wiegley01296292011-04-08 18:41:53 +000011072 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011073
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011074 // Check the argument types.
11075 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011076 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011077 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011078 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000011079
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011080 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011081
John McCalldadc5752010-08-24 06:29:42 +000011082 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011083 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011084 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011085 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000011086 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011087
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011088 IsError |= InputInit.isInvalid();
11089 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011090 } else {
John McCalldadc5752010-08-24 06:29:42 +000011091 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011092 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11093 if (DefArg.isInvalid()) {
11094 IsError = true;
11095 break;
11096 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011097
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011098 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011099 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011100
11101 TheCall->setArg(i + 1, Arg);
11102 }
11103
11104 // If this is a variadic call, handle args passed through "...".
11105 if (Proto->isVariadic()) {
11106 // Promote the arguments (C99 6.5.2.2p7).
Aaron Ballman9bca21e2012-07-20 20:40:35 +000011107 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000011108 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11109 IsError |= Arg.isInvalid();
11110 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011111 }
11112 }
11113
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011114 if (IsError) return true;
11115
Eli Friedmanff4b4072012-02-18 04:48:30 +000011116 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11117
Richard Smith55ce3522012-06-25 20:30:08 +000011118 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000011119 return true;
11120
John McCalle172be52010-08-24 06:09:16 +000011121 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011122}
11123
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011124/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000011125/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011126/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000011127ExprResult
John McCallb268a282010-08-23 23:25:46 +000011128Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000011129 assert(Base->getType()->isRecordType() &&
11130 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000011131
John McCall4124c492011-10-17 18:40:02 +000011132 if (checkPlaceholderForOverload(*this, Base))
11133 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011134
John McCallbc077cf2010-02-08 23:07:23 +000011135 SourceLocation Loc = Base->getExprLoc();
11136
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011137 // C++ [over.ref]p1:
11138 //
11139 // [...] An expression x->m is interpreted as (x.operator->())->m
11140 // for a class object x of type T if T::operator->() exists and if
11141 // the operator is selected as the best match function by the
11142 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000011143 DeclarationName OpName =
11144 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000011145 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011146 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000011147
John McCallbc077cf2010-02-08 23:07:23 +000011148 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011149 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000011150 return ExprError();
11151
John McCall27b18f82009-11-17 02:14:36 +000011152 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11153 LookupQualifiedName(R, BaseRecord->getDecl());
11154 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000011155
11156 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000011157 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000011158 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11159 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000011160 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011161
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011162 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11163
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011164 // Perform overload resolution.
11165 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011166 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011167 case OR_Success:
11168 // Overload resolution succeeded; we'll build the call below.
11169 break;
11170
11171 case OR_No_Viable_Function:
11172 if (CandidateSet.empty())
11173 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000011174 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011175 else
11176 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000011177 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011178 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011179 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011180
11181 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011182 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11183 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011184 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011185 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011186
11187 case OR_Deleted:
11188 Diag(OpLoc, diag::err_ovl_deleted_oper)
11189 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011190 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011191 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011192 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011193 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011194 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011195 }
11196
Eli Friedmanfa0df832012-02-02 03:46:19 +000011197 MarkFunctionReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000011198 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000011199 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000011200
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011201 // Convert the object parameter.
11202 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000011203 ExprResult BaseResult =
11204 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11205 Best->FoundDecl, Method);
11206 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000011207 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011208 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000011209
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011210 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011211 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011212 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011213 if (FnExpr.isInvalid())
11214 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011215
John McCall7decc9e2010-11-18 06:31:45 +000011216 QualType ResultTy = Method->getResultType();
11217 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11218 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000011219 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011220 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011221 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011222
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011223 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011224 Method))
11225 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000011226
11227 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011228}
11229
Richard Smithbcc22fc2012-03-09 08:00:36 +000011230/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11231/// a literal operator described by the provided lookup results.
11232ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11233 DeclarationNameInfo &SuffixInfo,
11234 ArrayRef<Expr*> Args,
11235 SourceLocation LitEndLoc,
11236 TemplateArgumentListInfo *TemplateArgs) {
11237 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000011238
Richard Smithbcc22fc2012-03-09 08:00:36 +000011239 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11240 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11241 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000011242
Richard Smithbcc22fc2012-03-09 08:00:36 +000011243 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11244
Richard Smithbcc22fc2012-03-09 08:00:36 +000011245 // Perform overload resolution. This will usually be trivial, but might need
11246 // to perform substitutions for a literal operator template.
11247 OverloadCandidateSet::iterator Best;
11248 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11249 case OR_Success:
11250 case OR_Deleted:
11251 break;
11252
11253 case OR_No_Viable_Function:
11254 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11255 << R.getLookupName();
11256 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11257 return ExprError();
11258
11259 case OR_Ambiguous:
11260 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11261 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11262 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000011263 }
11264
Richard Smithbcc22fc2012-03-09 08:00:36 +000011265 FunctionDecl *FD = Best->Function;
11266 MarkFunctionReferenced(UDSuffixLoc, FD);
11267 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smithc67fdd42012-03-07 08:35:16 +000011268
Richard Smithbcc22fc2012-03-09 08:00:36 +000011269 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11270 SuffixInfo.getLoc(),
11271 SuffixInfo.getInfo());
11272 if (Fn.isInvalid())
11273 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000011274
11275 // Check the argument types. This should almost always be a no-op, except
11276 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000011277 Expr *ConvArgs[2];
11278 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11279 ExprResult InputInit = PerformCopyInitialization(
11280 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11281 SourceLocation(), Args[ArgIdx]);
11282 if (InputInit.isInvalid())
11283 return true;
11284 ConvArgs[ArgIdx] = InputInit.take();
11285 }
11286
Richard Smithc67fdd42012-03-07 08:35:16 +000011287 QualType ResultTy = FD->getResultType();
11288 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11289 ResultTy = ResultTy.getNonLValueExprType(Context);
11290
Richard Smithc67fdd42012-03-07 08:35:16 +000011291 UserDefinedLiteral *UDL =
Benjamin Kramerc215e762012-08-24 11:54:20 +000011292 new (Context) UserDefinedLiteral(Context, Fn.take(),
11293 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000011294 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11295
11296 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11297 return ExprError();
11298
Richard Smith55ce3522012-06-25 20:30:08 +000011299 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smithc67fdd42012-03-07 08:35:16 +000011300 return ExprError();
11301
11302 return MaybeBindToTemporary(UDL);
11303}
11304
Sam Panzer0f384432012-08-21 00:52:01 +000011305/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11306/// given LookupResult is non-empty, it is assumed to describe a member which
11307/// will be invoked. Otherwise, the function will be found via argument
11308/// dependent lookup.
11309/// CallExpr is set to a valid expression and FRS_Success returned on success,
11310/// otherwise CallExpr is set to ExprError() and some non-success value
11311/// is returned.
11312Sema::ForRangeStatus
11313Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11314 SourceLocation RangeLoc, VarDecl *Decl,
11315 BeginEndFunction BEF,
11316 const DeclarationNameInfo &NameInfo,
11317 LookupResult &MemberLookup,
11318 OverloadCandidateSet *CandidateSet,
11319 Expr *Range, ExprResult *CallExpr) {
11320 CandidateSet->clear();
11321 if (!MemberLookup.empty()) {
11322 ExprResult MemberRef =
11323 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11324 /*IsPtr=*/false, CXXScopeSpec(),
11325 /*TemplateKWLoc=*/SourceLocation(),
11326 /*FirstQualifierInScope=*/0,
11327 MemberLookup,
11328 /*TemplateArgs=*/0);
11329 if (MemberRef.isInvalid()) {
11330 *CallExpr = ExprError();
11331 Diag(Range->getLocStart(), diag::note_in_for_range)
11332 << RangeLoc << BEF << Range->getType();
11333 return FRS_DiagnosticIssued;
11334 }
11335 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11336 if (CallExpr->isInvalid()) {
11337 *CallExpr = ExprError();
11338 Diag(Range->getLocStart(), diag::note_in_for_range)
11339 << RangeLoc << BEF << Range->getType();
11340 return FRS_DiagnosticIssued;
11341 }
11342 } else {
11343 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000011344 UnresolvedLookupExpr *Fn =
11345 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11346 NestedNameSpecifierLoc(), NameInfo,
11347 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000011348 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000011349
11350 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11351 CandidateSet, CallExpr);
11352 if (CandidateSet->empty() || CandidateSetError) {
11353 *CallExpr = ExprError();
11354 return FRS_NoViableFunction;
11355 }
11356 OverloadCandidateSet::iterator Best;
11357 OverloadingResult OverloadResult =
11358 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11359
11360 if (OverloadResult == OR_No_Viable_Function) {
11361 *CallExpr = ExprError();
11362 return FRS_NoViableFunction;
11363 }
11364 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11365 Loc, 0, CandidateSet, &Best,
11366 OverloadResult,
11367 /*AllowTypoCorrection=*/false);
11368 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11369 *CallExpr = ExprError();
11370 Diag(Range->getLocStart(), diag::note_in_for_range)
11371 << RangeLoc << BEF << Range->getType();
11372 return FRS_DiagnosticIssued;
11373 }
11374 }
11375 return FRS_Success;
11376}
11377
11378
Douglas Gregorcd695e52008-11-10 20:40:00 +000011379/// FixOverloadedFunctionReference - E is an expression that refers to
11380/// a C++ overloaded function (possibly with some parentheses and
11381/// perhaps a '&' around it). We have resolved the overloaded function
11382/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000011383/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000011384Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000011385 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000011386 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011387 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11388 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011389 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011390 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011391
Douglas Gregor51c538b2009-11-20 19:42:02 +000011392 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011393 }
11394
Douglas Gregor51c538b2009-11-20 19:42:02 +000011395 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011396 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11397 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011398 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000011399 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000011400 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000011401 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000011402 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011403 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011404
11405 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000011406 ICE->getCastKind(),
11407 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000011408 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011409 }
11410
Douglas Gregor51c538b2009-11-20 19:42:02 +000011411 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000011412 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000011413 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011414 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11415 if (Method->isStatic()) {
11416 // Do nothing: static member functions aren't any different
11417 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000011418 } else {
John McCalle66edc12009-11-24 19:00:30 +000011419 // Fix the sub expression, which really has to be an
11420 // UnresolvedLookupExpr holding an overloaded member function
11421 // or template.
John McCall16df1e52010-03-30 21:47:33 +000011422 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11423 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000011424 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011425 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011426
John McCalld14a8642009-11-21 08:51:07 +000011427 assert(isa<DeclRefExpr>(SubExpr)
11428 && "fixed to something other than a decl ref");
11429 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11430 && "fixed to a member ref with no nested name qualifier");
11431
11432 // We have taken the address of a pointer to member
11433 // function. Perform the computation here so that we get the
11434 // appropriate pointer to member type.
11435 QualType ClassType
11436 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11437 QualType MemPtrType
11438 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11439
John McCall7decc9e2010-11-18 06:31:45 +000011440 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11441 VK_RValue, OK_Ordinary,
11442 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011443 }
11444 }
John McCall16df1e52010-03-30 21:47:33 +000011445 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11446 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011447 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011448 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011449
John McCalle3027922010-08-25 11:45:40 +000011450 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011451 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000011452 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011453 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011454 }
John McCalld14a8642009-11-21 08:51:07 +000011455
11456 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000011457 // FIXME: avoid copy.
11458 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000011459 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000011460 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11461 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000011462 }
11463
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011464 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11465 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011466 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011467 Fn,
John McCall113bee02012-03-10 09:33:50 +000011468 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011469 ULE->getNameLoc(),
11470 Fn->getType(),
11471 VK_LValue,
11472 Found.getDecl(),
11473 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011474 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011475 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11476 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000011477 }
11478
John McCall10eae182009-11-30 22:42:35 +000011479 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000011480 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000011481 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11482 if (MemExpr->hasExplicitTemplateArgs()) {
11483 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11484 TemplateArgs = &TemplateArgsBuffer;
11485 }
John McCall6b51f282009-11-23 01:53:49 +000011486
John McCall2d74de92009-12-01 22:10:20 +000011487 Expr *Base;
11488
John McCall7decc9e2010-11-18 06:31:45 +000011489 // If we're filling in a static method where we used to have an
11490 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000011491 if (MemExpr->isImplicitAccess()) {
11492 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011493 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11494 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011495 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011496 Fn,
John McCall113bee02012-03-10 09:33:50 +000011497 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011498 MemExpr->getMemberLoc(),
11499 Fn->getType(),
11500 VK_LValue,
11501 Found.getDecl(),
11502 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011503 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011504 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11505 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000011506 } else {
11507 SourceLocation Loc = MemExpr->getMemberLoc();
11508 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000011509 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000011510 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000011511 Base = new (Context) CXXThisExpr(Loc,
11512 MemExpr->getBaseType(),
11513 /*isImplicit=*/true);
11514 }
John McCall2d74de92009-12-01 22:10:20 +000011515 } else
John McCallc3007a22010-10-26 07:05:15 +000011516 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000011517
John McCall4adb38c2011-04-27 00:36:17 +000011518 ExprValueKind valueKind;
11519 QualType type;
11520 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11521 valueKind = VK_LValue;
11522 type = Fn->getType();
11523 } else {
11524 valueKind = VK_RValue;
11525 type = Context.BoundMemberTy;
11526 }
11527
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011528 MemberExpr *ME = MemberExpr::Create(Context, Base,
11529 MemExpr->isArrow(),
11530 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011531 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011532 Fn,
11533 Found,
11534 MemExpr->getMemberNameInfo(),
11535 TemplateArgs,
11536 type, valueKind, OK_Ordinary);
11537 ME->setHadMultipleCandidates(true);
Richard Smith4f6a2c42012-11-14 07:06:31 +000011538 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011539 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011540 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011541
John McCallc3007a22010-10-26 07:05:15 +000011542 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000011543}
11544
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011545ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000011546 DeclAccessPair Found,
11547 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000011548 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000011549}
11550
Douglas Gregor5251f1b2008-10-21 16:13:35 +000011551} // end namespace clang