blob: 4d8795ea962f3cd1dcb08a189adf0b27e41b58cd [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
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000031#include "llvm/ADT/SmallString.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000033#include <algorithm>
34
35namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000036using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000037
John McCall7decc9e2010-11-18 06:31:45 +000038/// A convenience routine for creating a decayed reference to a
39/// function.
John Wiegley01296292011-04-08 18:41:53 +000040static ExprResult
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000041CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000042 SourceLocation Loc = SourceLocation(),
43 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
John McCall113bee02012-03-10 09:33:50 +000044 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000045 VK_LValue, Loc, LocInfo);
46 if (HadMultipleCandidates)
47 DRE->setHadMultipleCandidates(true);
48 ExprResult E = S.Owned(DRE);
John Wiegley01296292011-04-08 18:41:53 +000049 E = S.DefaultFunctionArrayConversion(E.take());
50 if (E.isInvalid())
51 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +000052 return E;
John McCall7decc9e2010-11-18 06:31:45 +000053}
54
John McCall5c32be02010-08-24 20:38:10 +000055static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
56 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000057 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000058 bool CStyle,
59 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000060
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000061static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
62 QualType &ToType,
63 bool InOverloadResolution,
64 StandardConversionSequence &SCS,
65 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000066static OverloadingResult
67IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
68 UserDefinedConversionSequence& User,
69 OverloadCandidateSet& Conversions,
70 bool AllowExplicit);
71
72
73static ImplicitConversionSequence::CompareKind
74CompareStandardConversionSequences(Sema &S,
75 const StandardConversionSequence& SCS1,
76 const StandardConversionSequence& SCS2);
77
78static ImplicitConversionSequence::CompareKind
79CompareQualificationConversions(Sema &S,
80 const StandardConversionSequence& SCS1,
81 const StandardConversionSequence& SCS2);
82
83static ImplicitConversionSequence::CompareKind
84CompareDerivedToBaseConversions(Sema &S,
85 const StandardConversionSequence& SCS1,
86 const StandardConversionSequence& SCS2);
87
88
89
Douglas Gregor5251f1b2008-10-21 16:13:35 +000090/// GetConversionCategory - Retrieve the implicit conversion
91/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000092ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000093GetConversionCategory(ImplicitConversionKind Kind) {
94 static const ImplicitConversionCategory
95 Category[(int)ICK_Num_Conversion_Kinds] = {
96 ICC_Identity,
97 ICC_Lvalue_Transformation,
98 ICC_Lvalue_Transformation,
99 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000100 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 ICC_Qualification_Adjustment,
102 ICC_Promotion,
103 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000104 ICC_Promotion,
105 ICC_Conversion,
106 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
111 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000112 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000113 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000114 ICC_Conversion,
115 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000116 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000117 ICC_Conversion
118 };
119 return Category[(int)Kind];
120}
121
122/// GetConversionRank - Retrieve the implicit conversion rank
123/// corresponding to the given implicit conversion kind.
124ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
125 static const ImplicitConversionRank
126 Rank[(int)ICK_Num_Conversion_Kinds] = {
127 ICR_Exact_Match,
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
131 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000132 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000133 ICR_Promotion,
134 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000135 ICR_Promotion,
136 ICR_Conversion,
137 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000143 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000144 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000145 ICR_Conversion,
146 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000147 ICR_Complex_Real_Conversion,
148 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000149 ICR_Conversion,
150 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151 };
152 return Rank[(int)Kind];
153}
154
155/// GetImplicitConversionName - Return the name of this kind of
156/// implicit conversion.
157const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000158 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000159 "No conversion",
160 "Lvalue-to-rvalue",
161 "Array-to-pointer",
162 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000163 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000164 "Qualification",
165 "Integral promotion",
166 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000167 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000168 "Integral conversion",
169 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000170 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000171 "Floating-integral conversion",
172 "Pointer conversion",
173 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000174 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000175 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000176 "Derived-to-base conversion",
177 "Vector conversion",
178 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000179 "Complex-real conversion",
180 "Block Pointer conversion",
181 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000182 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000183 };
184 return Name[Kind];
185}
186
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000187/// StandardConversionSequence - Set the standard conversion
188/// sequence to the identity conversion.
189void StandardConversionSequence::setAsIdentityConversion() {
190 First = ICK_Identity;
191 Second = ICK_Identity;
192 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000193 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000194 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000195 ReferenceBinding = false;
196 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000197 IsLvalueReference = true;
198 BindsToFunctionLvalue = false;
199 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000200 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000201 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000202 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000203}
204
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205/// getRank - Retrieve the rank of this standard conversion sequence
206/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
207/// implicit conversions.
208ImplicitConversionRank StandardConversionSequence::getRank() const {
209 ImplicitConversionRank Rank = ICR_Exact_Match;
210 if (GetConversionRank(First) > Rank)
211 Rank = GetConversionRank(First);
212 if (GetConversionRank(Second) > Rank)
213 Rank = GetConversionRank(Second);
214 if (GetConversionRank(Third) > Rank)
215 Rank = GetConversionRank(Third);
216 return Rank;
217}
218
219/// isPointerConversionToBool - Determines whether this conversion is
220/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000221/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000222/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000223bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000224 // Note that FromType has not necessarily been transformed by the
225 // array-to-pointer or function-to-pointer implicit conversions, so
226 // check for their presence as well as checking whether FromType is
227 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000228 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000229 (getFromType()->isPointerType() ||
230 getFromType()->isObjCObjectPointerType() ||
231 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000232 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000233 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
234 return true;
235
236 return false;
237}
238
Douglas Gregor5c407d92008-10-23 00:40:37 +0000239/// isPointerConversionToVoidPointer - Determines whether this
240/// conversion is a conversion of a pointer to a void pointer. This is
241/// used as part of the ranking of standard conversion sequences (C++
242/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000243bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000244StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000245isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000246 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000247 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000248
249 // Note that FromType has not necessarily been transformed by the
250 // array-to-pointer implicit conversion, so check for its presence
251 // and redo the conversion to get a pointer.
252 if (First == ICK_Array_To_Pointer)
253 FromType = Context.getArrayDecayedType(FromType);
254
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000257 return ToPtrType->getPointeeType()->isVoidType();
258
259 return false;
260}
261
Richard Smith66e05fe2012-01-18 05:21:49 +0000262/// Skip any implicit casts which could be either part of a narrowing conversion
263/// or after one in an implicit conversion.
264static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
265 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
266 switch (ICE->getCastKind()) {
267 case CK_NoOp:
268 case CK_IntegralCast:
269 case CK_IntegralToBoolean:
270 case CK_IntegralToFloating:
271 case CK_FloatingToIntegral:
272 case CK_FloatingToBoolean:
273 case CK_FloatingCast:
274 Converted = ICE->getSubExpr();
275 continue;
276
277 default:
278 return Converted;
279 }
280 }
281
282 return Converted;
283}
284
285/// Check if this standard conversion sequence represents a narrowing
286/// conversion, according to C++11 [dcl.init.list]p7.
287///
288/// \param Ctx The AST context.
289/// \param Converted The result of applying this standard conversion sequence.
290/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
291/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000292/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
293/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000294NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000295StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
296 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000297 APValue &ConstantValue,
298 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000299 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000300
301 // C++11 [dcl.init.list]p7:
302 // A narrowing conversion is an implicit conversion ...
303 QualType FromType = getToType(0);
304 QualType ToType = getToType(1);
305 switch (Second) {
306 // -- from a floating-point type to an integer type, or
307 //
308 // -- from an integer type or unscoped enumeration type to a floating-point
309 // type, except where the source is a constant expression and the actual
310 // value after conversion will fit into the target type and will produce
311 // the original value when converted back to the original type, or
312 case ICK_Floating_Integral:
313 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
314 return NK_Type_Narrowing;
315 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
316 llvm::APSInt IntConstantValue;
317 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
318 if (Initializer &&
319 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
320 // Convert the integer to the floating type.
321 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
322 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
323 llvm::APFloat::rmNearestTiesToEven);
324 // And back.
325 llvm::APSInt ConvertedValue = IntConstantValue;
326 bool ignored;
327 Result.convertToInteger(ConvertedValue,
328 llvm::APFloat::rmTowardZero, &ignored);
329 // If the resulting value is different, this was a narrowing conversion.
330 if (IntConstantValue != ConvertedValue) {
331 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000332 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000333 return NK_Constant_Narrowing;
334 }
335 } else {
336 // Variables are always narrowings.
337 return NK_Variable_Narrowing;
338 }
339 }
340 return NK_Not_Narrowing;
341
342 // -- from long double to double or float, or from double to float, except
343 // where the source is a constant expression and the actual value after
344 // conversion is within the range of values that can be represented (even
345 // if it cannot be represented exactly), or
346 case ICK_Floating_Conversion:
347 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
348 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
349 // FromType is larger than ToType.
350 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
351 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
352 // Constant!
353 assert(ConstantValue.isFloat());
354 llvm::APFloat FloatVal = ConstantValue.getFloat();
355 // Convert the source value into the target type.
356 bool ignored;
357 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
358 Ctx.getFloatTypeSemantics(ToType),
359 llvm::APFloat::rmNearestTiesToEven, &ignored);
360 // If there was no overflow, the source value is within the range of
361 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000362 if (ConvertStatus & llvm::APFloat::opOverflow) {
363 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000364 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000365 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000366 } else {
367 return NK_Variable_Narrowing;
368 }
369 }
370 return NK_Not_Narrowing;
371
372 // -- from an integer type or unscoped enumeration type to an integer type
373 // that cannot represent all the values of the original type, except where
374 // the source is a constant expression and the actual value after
375 // conversion will fit into the target type and will produce the original
376 // value when converted back to the original type.
377 case ICK_Boolean_Conversion: // Bools are integers too.
378 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
379 // Boolean conversions can be from pointers and pointers to members
380 // [conv.bool], and those aren't considered narrowing conversions.
381 return NK_Not_Narrowing;
382 } // Otherwise, fall through to the integral case.
383 case ICK_Integral_Conversion: {
384 assert(FromType->isIntegralOrUnscopedEnumerationType());
385 assert(ToType->isIntegralOrUnscopedEnumerationType());
386 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
387 const unsigned FromWidth = Ctx.getIntWidth(FromType);
388 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
389 const unsigned ToWidth = Ctx.getIntWidth(ToType);
390
391 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000392 (FromWidth == ToWidth && FromSigned != ToSigned) ||
393 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000394 // Not all values of FromType can be represented in ToType.
395 llvm::APSInt InitializerValue;
396 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000397 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
398 // Such conversions on variables are always narrowing.
399 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000400 }
401 bool Narrowing = false;
402 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000403 // Negative -> unsigned is narrowing. Otherwise, more bits is never
404 // narrowing.
405 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000406 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000407 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000408 // Add a bit to the InitializerValue so we don't have to worry about
409 // signed vs. unsigned comparisons.
410 InitializerValue = InitializerValue.extend(
411 InitializerValue.getBitWidth() + 1);
412 // Convert the initializer to and from the target width and signed-ness.
413 llvm::APSInt ConvertedValue = InitializerValue;
414 ConvertedValue = ConvertedValue.trunc(ToWidth);
415 ConvertedValue.setIsSigned(ToSigned);
416 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
417 ConvertedValue.setIsSigned(InitializerValue.isSigned());
418 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000419 if (ConvertedValue != InitializerValue)
420 Narrowing = true;
421 }
422 if (Narrowing) {
423 ConstantType = Initializer->getType();
424 ConstantValue = APValue(InitializerValue);
425 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000426 }
427 }
428 return NK_Not_Narrowing;
429 }
430
431 default:
432 // Other kinds of conversions are not narrowings.
433 return NK_Not_Narrowing;
434 }
435}
436
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000437/// DebugPrint - Print this standard conversion sequence to standard
438/// error. Useful for debugging overloading issues.
439void StandardConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000440 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000441 bool PrintedSomething = false;
442 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000443 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000444 PrintedSomething = true;
445 }
446
447 if (Second != ICK_Identity) {
448 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000449 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000450 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000451 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000452
453 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000454 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000455 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000456 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000457 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000458 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000459 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000460 PrintedSomething = true;
461 }
462
463 if (Third != ICK_Identity) {
464 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000465 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000466 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000467 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000468 PrintedSomething = true;
469 }
470
471 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000472 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000473 }
474}
475
476/// DebugPrint - Print this user-defined conversion sequence to standard
477/// error. Useful for debugging overloading issues.
478void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000479 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480 if (Before.First || Before.Second || Before.Third) {
481 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000482 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000483 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000484 if (ConversionFunction)
485 OS << '\'' << *ConversionFunction << '\'';
486 else
487 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000488 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000489 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000490 After.DebugPrint();
491 }
492}
493
494/// DebugPrint - Print this implicit conversion sequence to standard
495/// error. Useful for debugging overloading issues.
496void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000497 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498 switch (ConversionKind) {
499 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000500 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000501 Standard.DebugPrint();
502 break;
503 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000504 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505 UserDefined.DebugPrint();
506 break;
507 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000508 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000509 break;
John McCall0d1da222010-01-12 00:44:57 +0000510 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000511 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000512 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000514 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000515 break;
516 }
517
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000518 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000519}
520
John McCall0d1da222010-01-12 00:44:57 +0000521void AmbiguousConversionSequence::construct() {
522 new (&conversions()) ConversionSet();
523}
524
525void AmbiguousConversionSequence::destruct() {
526 conversions().~ConversionSet();
527}
528
529void
530AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
531 FromTypePtr = O.FromTypePtr;
532 ToTypePtr = O.ToTypePtr;
533 new (&conversions()) ConversionSet(O.conversions());
534}
535
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000536namespace {
537 // Structure used by OverloadCandidate::DeductionFailureInfo to store
538 // template parameter and template argument information.
539 struct DFIParamWithArguments {
540 TemplateParameter Param;
541 TemplateArgument FirstArg;
542 TemplateArgument SecondArg;
543 };
544}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000545
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000546/// \brief Convert from Sema's representation of template deduction information
547/// to the form used in overload-candidate information.
548OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000549static MakeDeductionFailureInfo(ASTContext &Context,
550 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000551 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000552 OverloadCandidate::DeductionFailureInfo Result;
553 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000554 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000555 Result.Data = 0;
556 switch (TDK) {
557 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000558 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000559 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000560 case Sema::TDK_TooManyArguments:
561 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000562 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000563
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000564 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000565 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000566 Result.Data = Info.Param.getOpaqueValue();
567 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000568
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000569 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000570 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000571 // FIXME: Should allocate from normal heap so that we can free this later.
572 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000573 Saved->Param = Info.Param;
574 Saved->FirstArg = Info.FirstArg;
575 Saved->SecondArg = Info.SecondArg;
576 Result.Data = Saved;
577 break;
578 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000579
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000580 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000581 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000582 if (Info.hasSFINAEDiagnostic()) {
583 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
584 SourceLocation(), PartialDiagnostic::NullDiagnostic());
585 Info.takeSFINAEDiagnostic(*Diag);
586 Result.HasDiagnostic = true;
587 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000588 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000590 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000591 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000592 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000595 return Result;
596}
John McCall0d1da222010-01-12 00:44:57 +0000597
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000598void OverloadCandidate::DeductionFailureInfo::Destroy() {
599 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
600 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000601 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000602 case Sema::TDK_InstantiationDepth:
603 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000604 case Sema::TDK_TooManyArguments:
605 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000606 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000607 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000608
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000609 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000610 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000611 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000612 Data = 0;
613 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000614
615 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000616 // FIXME: Destroy the template argument list?
Douglas Gregord09efd42010-05-08 20:07:26 +0000617 Data = 0;
Richard Smith9ca64612012-05-07 09:03:25 +0000618 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
619 Diag->~PartialDiagnosticAt();
620 HasDiagnostic = false;
621 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000622 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000623
Douglas Gregor461761d2010-05-08 18:20:53 +0000624 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000625 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000626 case Sema::TDK_FailedOverloadResolution:
627 break;
628 }
629}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000630
Richard Smith9ca64612012-05-07 09:03:25 +0000631PartialDiagnosticAt *
632OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
633 if (HasDiagnostic)
634 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
635 return 0;
636}
637
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000638TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000639OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
640 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
641 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000642 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000643 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000644 case Sema::TDK_TooManyArguments:
645 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000646 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000647 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000648
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000649 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000650 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000651 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000652
653 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000654 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000655 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000657 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000658 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000659 case Sema::TDK_FailedOverloadResolution:
660 break;
661 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000662
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000663 return TemplateParameter();
664}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000665
Douglas Gregord09efd42010-05-08 20:07:26 +0000666TemplateArgumentList *
667OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
668 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
669 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000670 case Sema::TDK_Invalid:
Douglas Gregord09efd42010-05-08 20:07:26 +0000671 case Sema::TDK_InstantiationDepth:
672 case Sema::TDK_TooManyArguments:
673 case Sema::TDK_TooFewArguments:
674 case Sema::TDK_Incomplete:
675 case Sema::TDK_InvalidExplicitArguments:
676 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000677 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000678 return 0;
679
680 case Sema::TDK_SubstitutionFailure:
681 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000682
Douglas Gregord09efd42010-05-08 20:07:26 +0000683 // Unhandled
684 case Sema::TDK_NonDeducedMismatch:
685 case Sema::TDK_FailedOverloadResolution:
686 break;
687 }
688
689 return 0;
690}
691
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000692const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
693 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
694 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000695 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000696 case Sema::TDK_InstantiationDepth:
697 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000698 case Sema::TDK_TooManyArguments:
699 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000700 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000701 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000702 return 0;
703
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000704 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000705 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000706 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000707
Douglas Gregor461761d2010-05-08 18:20:53 +0000708 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000709 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000710 case Sema::TDK_FailedOverloadResolution:
711 break;
712 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000713
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000714 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000715}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000716
717const TemplateArgument *
718OverloadCandidate::DeductionFailureInfo::getSecondArg() {
719 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
720 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000721 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000722 case Sema::TDK_InstantiationDepth:
723 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000724 case Sema::TDK_TooManyArguments:
725 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000726 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000727 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000728 return 0;
729
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000730 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000731 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000732 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
733
Douglas Gregor461761d2010-05-08 18:20:53 +0000734 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000735 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000736 case Sema::TDK_FailedOverloadResolution:
737 break;
738 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000739
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000740 return 0;
741}
742
743void OverloadCandidateSet::clear() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000744 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000745 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
746 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000747 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
748 i->DeductionFailure.Destroy();
749 }
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000750 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000751 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000752 Functions.clear();
753}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000754
John McCall4124c492011-10-17 18:40:02 +0000755namespace {
756 class UnbridgedCastsSet {
757 struct Entry {
758 Expr **Addr;
759 Expr *Saved;
760 };
761 SmallVector<Entry, 2> Entries;
762
763 public:
764 void save(Sema &S, Expr *&E) {
765 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
766 Entry entry = { &E, E };
767 Entries.push_back(entry);
768 E = S.stripARCUnbridgedCast(E);
769 }
770
771 void restore() {
772 for (SmallVectorImpl<Entry>::iterator
773 i = Entries.begin(), e = Entries.end(); i != e; ++i)
774 *i->Addr = i->Saved;
775 }
776 };
777}
778
779/// checkPlaceholderForOverload - Do any interesting placeholder-like
780/// preprocessing on the given expression.
781///
782/// \param unbridgedCasts a collection to which to add unbridged casts;
783/// without this, they will be immediately diagnosed as errors
784///
785/// Return true on unrecoverable error.
786static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
787 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000788 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
789 // We can't handle overloaded expressions here because overload
790 // resolution might reasonably tweak them.
791 if (placeholder->getKind() == BuiltinType::Overload) return false;
792
793 // If the context potentially accepts unbridged ARC casts, strip
794 // the unbridged cast and add it to the collection for later restoration.
795 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
796 unbridgedCasts) {
797 unbridgedCasts->save(S, E);
798 return false;
799 }
800
801 // Go ahead and check everything else.
802 ExprResult result = S.CheckPlaceholderExpr(E);
803 if (result.isInvalid())
804 return true;
805
806 E = result.take();
807 return false;
808 }
809
810 // Nothing to do.
811 return false;
812}
813
814/// checkArgPlaceholdersForOverload - Check a set of call operands for
815/// placeholders.
816static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
817 unsigned numArgs,
818 UnbridgedCastsSet &unbridged) {
819 for (unsigned i = 0; i != numArgs; ++i)
820 if (checkPlaceholderForOverload(S, args[i], &unbridged))
821 return true;
822
823 return false;
824}
825
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000826// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000827// overload of the declarations in Old. This routine returns false if
828// New and Old cannot be overloaded, e.g., if New has the same
829// signature as some function in Old (C++ 1.3.10) or if the Old
830// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000831// it does return false, MatchedDecl will point to the decl that New
832// cannot be overloaded with. This decl may be a UsingShadowDecl on
833// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000834//
835// Example: Given the following input:
836//
837// void f(int, float); // #1
838// void f(int, int); // #2
839// int f(int, int); // #3
840//
841// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000842// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000843//
John McCall3d988d92009-12-02 08:47:38 +0000844// When we process #2, Old contains only the FunctionDecl for #1. By
845// comparing the parameter types, we see that #1 and #2 are overloaded
846// (since they have different signatures), so this routine returns
847// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000848//
John McCall3d988d92009-12-02 08:47:38 +0000849// When we process #3, Old is an overload set containing #1 and #2. We
850// compare the signatures of #3 to #1 (they're overloaded, so we do
851// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
852// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000853// signature), IsOverload returns false and MatchedDecl will be set to
854// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000855//
856// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
857// into a class by a using declaration. The rules for whether to hide
858// shadow declarations ignore some properties which otherwise figure
859// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000860Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000861Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
862 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000863 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000864 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000865 NamedDecl *OldD = *I;
866
867 bool OldIsUsingDecl = false;
868 if (isa<UsingShadowDecl>(OldD)) {
869 OldIsUsingDecl = true;
870
871 // We can always introduce two using declarations into the same
872 // context, even if they have identical signatures.
873 if (NewIsUsingDecl) continue;
874
875 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
876 }
877
878 // If either declaration was introduced by a using declaration,
879 // we'll need to use slightly different rules for matching.
880 // Essentially, these rules are the normal rules, except that
881 // function templates hide function templates with different
882 // return types or template parameter lists.
883 bool UseMemberUsingDeclRules =
884 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
885
John McCall3d988d92009-12-02 08:47:38 +0000886 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000887 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
888 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
889 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
890 continue;
891 }
892
John McCalldaa3d6b2009-12-09 03:35:25 +0000893 Match = *I;
894 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000895 }
John McCall3d988d92009-12-02 08:47:38 +0000896 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000897 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
898 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
899 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
900 continue;
901 }
902
John McCalldaa3d6b2009-12-09 03:35:25 +0000903 Match = *I;
904 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000905 }
John McCalla8987a2942010-11-10 03:01:53 +0000906 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000907 // We can overload with these, which can show up when doing
908 // redeclaration checks for UsingDecls.
909 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000910 } else if (isa<TagDecl>(OldD)) {
911 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000912 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
913 // Optimistically assume that an unresolved using decl will
914 // overload; if it doesn't, we'll have to diagnose during
915 // template instantiation.
916 } else {
John McCall1f82f242009-11-18 22:49:29 +0000917 // (C++ 13p1):
918 // Only function declarations can be overloaded; object and type
919 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000920 Match = *I;
921 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000922 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000923 }
John McCall1f82f242009-11-18 22:49:29 +0000924
John McCalldaa3d6b2009-12-09 03:35:25 +0000925 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000926}
927
John McCalle9cccd82010-06-16 08:42:20 +0000928bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
929 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000930 // If both of the functions are extern "C", then they are not
931 // overloads.
932 if (Old->isExternC() && New->isExternC())
933 return false;
934
John McCall1f82f242009-11-18 22:49:29 +0000935 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
936 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
937
938 // C++ [temp.fct]p2:
939 // A function template can be overloaded with other function templates
940 // and with normal (non-template) functions.
941 if ((OldTemplate == 0) != (NewTemplate == 0))
942 return true;
943
944 // Is the function New an overload of the function Old?
945 QualType OldQType = Context.getCanonicalType(Old->getType());
946 QualType NewQType = Context.getCanonicalType(New->getType());
947
948 // Compare the signatures (C++ 1.3.10) of the two functions to
949 // determine whether they are overloads. If we find any mismatch
950 // in the signature, they are overloads.
951
952 // If either of these functions is a K&R-style function (no
953 // prototype), then we consider them to have matching signatures.
954 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
955 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
956 return false;
957
John McCall424cec92011-01-19 06:33:43 +0000958 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
959 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000960
961 // The signature of a function includes the types of its
962 // parameters (C++ 1.3.10), which includes the presence or absence
963 // of the ellipsis; see C++ DR 357).
964 if (OldQType != NewQType &&
965 (OldType->getNumArgs() != NewType->getNumArgs() ||
966 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000967 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000968 return true;
969
970 // C++ [temp.over.link]p4:
971 // The signature of a function template consists of its function
972 // signature, its return type and its template parameter list. The names
973 // of the template parameters are significant only for establishing the
974 // relationship between the template parameters and the rest of the
975 // signature.
976 //
977 // We check the return type and template parameter lists for function
978 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000979 //
980 // However, we don't consider either of these when deciding whether
981 // a member introduced by a shadow declaration is hidden.
982 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000983 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
984 OldTemplate->getTemplateParameters(),
985 false, TPL_TemplateMatch) ||
986 OldType->getResultType() != NewType->getResultType()))
987 return true;
988
989 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000990 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000991 //
992 // As part of this, also check whether one of the member functions
993 // is static, in which case they are not overloads (C++
994 // 13.1p2). While not part of the definition of the signature,
995 // this check is important to determine whether these functions
996 // can be overloaded.
997 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
998 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
999 if (OldMethod && NewMethod &&
1000 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001001 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +00001002 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
1003 if (!UseUsingDeclRules &&
1004 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
1005 (OldMethod->getRefQualifier() == RQ_None ||
1006 NewMethod->getRefQualifier() == RQ_None)) {
1007 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001008 // - Member function declarations with the same name and the same
1009 // parameter-type-list as well as member function template
1010 // declarations with the same name, the same parameter-type-list, and
1011 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +00001012 // them, but not all, have a ref-qualifier (8.3.5).
1013 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1014 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1015 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1016 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001017
John McCall1f82f242009-11-18 22:49:29 +00001018 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001019 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001020
John McCall1f82f242009-11-18 22:49:29 +00001021 // The signatures match; this is not an overload.
1022 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001023}
1024
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001025/// \brief Checks availability of the function depending on the current
1026/// function context. Inside an unavailable function, unavailability is ignored.
1027///
1028/// \returns true if \arg FD is unavailable and current context is inside
1029/// an available function, false otherwise.
1030bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1031 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1032}
1033
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001034/// \brief Tries a user-defined conversion from From to ToType.
1035///
1036/// Produces an implicit conversion sequence for when a standard conversion
1037/// is not an option. See TryImplicitConversion for more information.
1038static ImplicitConversionSequence
1039TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1040 bool SuppressUserConversions,
1041 bool AllowExplicit,
1042 bool InOverloadResolution,
1043 bool CStyle,
1044 bool AllowObjCWritebackConversion) {
1045 ImplicitConversionSequence ICS;
1046
1047 if (SuppressUserConversions) {
1048 // We're not in the case above, so there is no conversion that
1049 // we can perform.
1050 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1051 return ICS;
1052 }
1053
1054 // Attempt user-defined conversion.
1055 OverloadCandidateSet Conversions(From->getExprLoc());
1056 OverloadingResult UserDefResult
1057 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1058 AllowExplicit);
1059
1060 if (UserDefResult == OR_Success) {
1061 ICS.setUserDefined();
1062 // C++ [over.ics.user]p4:
1063 // A conversion of an expression of class type to the same class
1064 // type is given Exact Match rank, and a conversion of an
1065 // expression of class type to a base class of that type is
1066 // given Conversion rank, in spite of the fact that a copy
1067 // constructor (i.e., a user-defined conversion function) is
1068 // called for those cases.
1069 if (CXXConstructorDecl *Constructor
1070 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1071 QualType FromCanon
1072 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1073 QualType ToCanon
1074 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1075 if (Constructor->isCopyConstructor() &&
1076 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1077 // Turn this into a "standard" conversion sequence, so that it
1078 // gets ranked with standard conversion sequences.
1079 ICS.setStandard();
1080 ICS.Standard.setAsIdentityConversion();
1081 ICS.Standard.setFromType(From->getType());
1082 ICS.Standard.setAllToTypes(ToType);
1083 ICS.Standard.CopyConstructor = Constructor;
1084 if (ToCanon != FromCanon)
1085 ICS.Standard.Second = ICK_Derived_To_Base;
1086 }
1087 }
1088
1089 // C++ [over.best.ics]p4:
1090 // However, when considering the argument of a user-defined
1091 // conversion function that is a candidate by 13.3.1.3 when
1092 // invoked for the copying of the temporary in the second step
1093 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1094 // 13.3.1.6 in all cases, only standard conversion sequences and
1095 // ellipsis conversion sequences are allowed.
1096 if (SuppressUserConversions && ICS.isUserDefined()) {
1097 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1098 }
1099 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1100 ICS.setAmbiguous();
1101 ICS.Ambiguous.setFromType(From->getType());
1102 ICS.Ambiguous.setToType(ToType);
1103 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1104 Cand != Conversions.end(); ++Cand)
1105 if (Cand->Viable)
1106 ICS.Ambiguous.addConversion(Cand->Function);
1107 } else {
1108 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1109 }
1110
1111 return ICS;
1112}
1113
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001114/// TryImplicitConversion - Attempt to perform an implicit conversion
1115/// from the given expression (Expr) to the given type (ToType). This
1116/// function returns an implicit conversion sequence that can be used
1117/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001118///
1119/// void f(float f);
1120/// void g(int i) { f(i); }
1121///
1122/// this routine would produce an implicit conversion sequence to
1123/// describe the initialization of f from i, which will be a standard
1124/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1125/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1126//
1127/// Note that this routine only determines how the conversion can be
1128/// performed; it does not actually perform the conversion. As such,
1129/// it will not produce any diagnostics if no conversion is available,
1130/// but will instead return an implicit conversion sequence of kind
1131/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001132///
1133/// If @p SuppressUserConversions, then user-defined conversions are
1134/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001135/// If @p AllowExplicit, then explicit user-defined conversions are
1136/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001137///
1138/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1139/// writeback conversion, which allows __autoreleasing id* parameters to
1140/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001141static ImplicitConversionSequence
1142TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1143 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001144 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001145 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001146 bool CStyle,
1147 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001148 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001149 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001150 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001151 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001152 return ICS;
1153 }
1154
David Blaikiebbafb8a2012-03-11 07:00:24 +00001155 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001156 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001157 return ICS;
1158 }
1159
Douglas Gregor836a7e82010-08-11 02:15:33 +00001160 // C++ [over.ics.user]p4:
1161 // A conversion of an expression of class type to the same class
1162 // type is given Exact Match rank, and a conversion of an
1163 // expression of class type to a base class of that type is
1164 // given Conversion rank, in spite of the fact that a copy/move
1165 // constructor (i.e., a user-defined conversion function) is
1166 // called for those cases.
1167 QualType FromType = From->getType();
1168 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001169 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1170 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001171 ICS.setStandard();
1172 ICS.Standard.setAsIdentityConversion();
1173 ICS.Standard.setFromType(FromType);
1174 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001175
Douglas Gregor5ab11652010-04-17 22:01:05 +00001176 // We don't actually check at this point whether there is a valid
1177 // copy/move constructor, since overloading just assumes that it
1178 // exists. When we actually perform initialization, we'll find the
1179 // appropriate constructor to copy the returned object, if needed.
1180 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001181
Douglas Gregor5ab11652010-04-17 22:01:05 +00001182 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001183 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001184 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001185
Douglas Gregor836a7e82010-08-11 02:15:33 +00001186 return ICS;
1187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001188
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001189 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1190 AllowExplicit, InOverloadResolution, CStyle,
1191 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001192}
1193
John McCall31168b02011-06-15 23:02:42 +00001194ImplicitConversionSequence
1195Sema::TryImplicitConversion(Expr *From, QualType ToType,
1196 bool SuppressUserConversions,
1197 bool AllowExplicit,
1198 bool InOverloadResolution,
1199 bool CStyle,
1200 bool AllowObjCWritebackConversion) {
1201 return clang::TryImplicitConversion(*this, From, ToType,
1202 SuppressUserConversions, AllowExplicit,
1203 InOverloadResolution, CStyle,
1204 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +00001205}
1206
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001207/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001208/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001209/// converted expression. Flavor is the kind of conversion we're
1210/// performing, used in the error message. If @p AllowExplicit,
1211/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001212ExprResult
1213Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001214 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001215 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001216 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001217}
1218
John Wiegley01296292011-04-08 18:41:53 +00001219ExprResult
1220Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001221 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001222 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001223 if (checkPlaceholderForOverload(*this, From))
1224 return ExprError();
1225
John McCall31168b02011-06-15 23:02:42 +00001226 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1227 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001228 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001229 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001230
John McCall5c32be02010-08-24 20:38:10 +00001231 ICS = clang::TryImplicitConversion(*this, From, ToType,
1232 /*SuppressUserConversions=*/false,
1233 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001234 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001235 /*CStyle=*/false,
1236 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001237 return PerformImplicitConversion(From, ToType, ICS, Action);
1238}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001239
1240/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001241/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001242bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1243 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001244 if (Context.hasSameUnqualifiedType(FromType, ToType))
1245 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001246
John McCall991eb4b2010-12-21 00:44:39 +00001247 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1248 // where F adds one of the following at most once:
1249 // - a pointer
1250 // - a member pointer
1251 // - a block pointer
1252 CanQualType CanTo = Context.getCanonicalType(ToType);
1253 CanQualType CanFrom = Context.getCanonicalType(FromType);
1254 Type::TypeClass TyClass = CanTo->getTypeClass();
1255 if (TyClass != CanFrom->getTypeClass()) return false;
1256 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1257 if (TyClass == Type::Pointer) {
1258 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1259 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1260 } else if (TyClass == Type::BlockPointer) {
1261 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1262 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1263 } else if (TyClass == Type::MemberPointer) {
1264 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1265 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1266 } else {
1267 return false;
1268 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001269
John McCall991eb4b2010-12-21 00:44:39 +00001270 TyClass = CanTo->getTypeClass();
1271 if (TyClass != CanFrom->getTypeClass()) return false;
1272 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1273 return false;
1274 }
1275
1276 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1277 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1278 if (!EInfo.getNoReturn()) return false;
1279
1280 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1281 assert(QualType(FromFn, 0).isCanonical());
1282 if (QualType(FromFn, 0) != CanTo) return false;
1283
1284 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001285 return true;
1286}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001287
Douglas Gregor46188682010-05-18 22:42:18 +00001288/// \brief Determine whether the conversion from FromType to ToType is a valid
1289/// vector conversion.
1290///
1291/// \param ICK Will be set to the vector conversion kind, if this is a vector
1292/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001293static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1294 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001295 // We need at least one of these types to be a vector type to have a vector
1296 // conversion.
1297 if (!ToType->isVectorType() && !FromType->isVectorType())
1298 return false;
1299
1300 // Identical types require no conversions.
1301 if (Context.hasSameUnqualifiedType(FromType, ToType))
1302 return false;
1303
1304 // There are no conversions between extended vector types, only identity.
1305 if (ToType->isExtVectorType()) {
1306 // There are no conversions between extended vector types other than the
1307 // identity conversion.
1308 if (FromType->isExtVectorType())
1309 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001310
Douglas Gregor46188682010-05-18 22:42:18 +00001311 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001312 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001313 ICK = ICK_Vector_Splat;
1314 return true;
1315 }
1316 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001317
1318 // We can perform the conversion between vector types in the following cases:
1319 // 1)vector types are equivalent AltiVec and GCC vector types
1320 // 2)lax vector conversions are permitted and the vector types are of the
1321 // same size
1322 if (ToType->isVectorType() && FromType->isVectorType()) {
1323 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001324 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruth9c524c12010-08-08 05:02:51 +00001325 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001326 ICK = ICK_Vector_Conversion;
1327 return true;
1328 }
Douglas Gregor46188682010-05-18 22:42:18 +00001329 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001330
Douglas Gregor46188682010-05-18 22:42:18 +00001331 return false;
1332}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001333
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001334static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1335 bool InOverloadResolution,
1336 StandardConversionSequence &SCS,
1337 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001338
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001339/// IsStandardConversion - Determines whether there is a standard
1340/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1341/// expression From to the type ToType. Standard conversion sequences
1342/// only consider non-class types; for conversions that involve class
1343/// types, use TryImplicitConversion. If a conversion exists, SCS will
1344/// contain the standard conversion sequence required to perform this
1345/// conversion and this routine will return true. Otherwise, this
1346/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001347static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1348 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001349 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001350 bool CStyle,
1351 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001352 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001353
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001354 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001355 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001356 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001357 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001358 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001359 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001360
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001361 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001362 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001363 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001364 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001365 return false;
1366
Mike Stump11289f42009-09-09 15:08:12 +00001367 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001368 }
1369
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001370 // The first conversion can be an lvalue-to-rvalue conversion,
1371 // array-to-pointer conversion, or function-to-pointer conversion
1372 // (C++ 4p1).
1373
John McCall5c32be02010-08-24 20:38:10 +00001374 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001375 DeclAccessPair AccessPair;
1376 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001377 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001378 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001379 // We were able to resolve the address of the overloaded function,
1380 // so we can convert to the type of that function.
1381 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001382
1383 // we can sometimes resolve &foo<int> regardless of ToType, so check
1384 // if the type matches (identity) or we are converting to bool
1385 if (!S.Context.hasSameUnqualifiedType(
1386 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1387 QualType resultTy;
1388 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001389 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001390 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1391 // otherwise, only a boolean conversion is standard
1392 if (!ToType->isBooleanType())
1393 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001394 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001395
Chandler Carruthffce2452011-03-29 08:08:18 +00001396 // Check if the "from" expression is taking the address of an overloaded
1397 // function and recompute the FromType accordingly. Take advantage of the
1398 // fact that non-static member functions *must* have such an address-of
1399 // expression.
1400 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1401 if (Method && !Method->isStatic()) {
1402 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1403 "Non-unary operator on non-static member address");
1404 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1405 == UO_AddrOf &&
1406 "Non-address-of operator on non-static member address");
1407 const Type *ClassType
1408 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1409 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001410 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1411 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1412 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001413 "Non-address-of operator for overloaded function expression");
1414 FromType = S.Context.getPointerType(FromType);
1415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001416
Douglas Gregor980fb162010-04-29 18:24:40 +00001417 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001418 assert(S.Context.hasSameType(
1419 FromType,
1420 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001421 } else {
1422 return false;
1423 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001424 }
John McCall154a2fd2011-08-30 00:57:29 +00001425 // Lvalue-to-rvalue conversion (C++11 4.1):
1426 // A glvalue (3.10) of a non-function, non-array type T can
1427 // be converted to a prvalue.
1428 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001429 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001430 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001431 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001432 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001433
Douglas Gregorc79862f2012-04-12 17:51:55 +00001434 // C11 6.3.2.1p2:
1435 // ... if the lvalue has atomic type, the value has the non-atomic version
1436 // of the type of the lvalue ...
1437 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1438 FromType = Atomic->getValueType();
1439
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001440 // If T is a non-class type, the type of the rvalue is the
1441 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001442 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1443 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001444 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001445 } else if (FromType->isArrayType()) {
1446 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001447 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001448
1449 // An lvalue or rvalue of type "array of N T" or "array of unknown
1450 // bound of T" can be converted to an rvalue of type "pointer to
1451 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001452 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001453
John McCall5c32be02010-08-24 20:38:10 +00001454 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001455 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001456 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001457
1458 // For the purpose of ranking in overload resolution
1459 // (13.3.3.1.1), this conversion is considered an
1460 // array-to-pointer conversion followed by a qualification
1461 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001462 SCS.Second = ICK_Identity;
1463 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001464 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001465 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001466 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001467 }
John McCall086a4642010-11-24 05:12:34 +00001468 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001469 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001470 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001471
1472 // An lvalue of function type T can be converted to an rvalue of
1473 // type "pointer to T." The result is a pointer to the
1474 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001475 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001476 } else {
1477 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001478 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001479 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001480 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001481
1482 // The second conversion can be an integral promotion, floating
1483 // point promotion, integral conversion, floating point conversion,
1484 // floating-integral conversion, pointer conversion,
1485 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001486 // For overloading in C, this can also be a "compatible-type"
1487 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001488 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001489 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001490 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001491 // The unqualified versions of the types are the same: there's no
1492 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001493 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001494 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001495 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001496 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001497 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001498 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001499 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001500 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001501 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001502 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001503 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001504 SCS.Second = ICK_Complex_Promotion;
1505 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001506 } else if (ToType->isBooleanType() &&
1507 (FromType->isArithmeticType() ||
1508 FromType->isAnyPointerType() ||
1509 FromType->isBlockPointerType() ||
1510 FromType->isMemberPointerType() ||
1511 FromType->isNullPtrType())) {
1512 // Boolean conversions (C++ 4.12).
1513 SCS.Second = ICK_Boolean_Conversion;
1514 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001515 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001516 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001517 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001518 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001519 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001520 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001521 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001522 SCS.Second = ICK_Complex_Conversion;
1523 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001524 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1525 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001526 // Complex-real conversions (C99 6.3.1.7)
1527 SCS.Second = ICK_Complex_Real;
1528 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001529 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001530 // Floating point conversions (C++ 4.8).
1531 SCS.Second = ICK_Floating_Conversion;
1532 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001533 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001534 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001535 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001536 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001537 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001538 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001539 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001540 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001541 SCS.Second = ICK_Block_Pointer_Conversion;
1542 } else if (AllowObjCWritebackConversion &&
1543 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1544 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001545 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1546 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001547 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001548 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001549 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001550 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001551 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001552 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001553 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001554 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001555 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001556 SCS.Second = SecondICK;
1557 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001558 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001559 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001560 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001561 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001562 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001563 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001564 // Treat a conversion that strips "noreturn" as an identity conversion.
1565 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001566 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1567 InOverloadResolution,
1568 SCS, CStyle)) {
1569 SCS.Second = ICK_TransparentUnionConversion;
1570 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001571 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1572 CStyle)) {
1573 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001574 // appropriately.
1575 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001576 } else {
1577 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001578 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001579 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001580 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001581
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001582 QualType CanonFrom;
1583 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001584 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001585 bool ObjCLifetimeConversion;
1586 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1587 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001588 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001589 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001590 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001591 CanonFrom = S.Context.getCanonicalType(FromType);
1592 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001593 } else {
1594 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001595 SCS.Third = ICK_Identity;
1596
Mike Stump11289f42009-09-09 15:08:12 +00001597 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001598 // [...] Any difference in top-level cv-qualification is
1599 // subsumed by the initialization itself and does not constitute
1600 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001601 CanonFrom = S.Context.getCanonicalType(FromType);
1602 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001603 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001604 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001605 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001606 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1607 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001608 FromType = ToType;
1609 CanonFrom = CanonTo;
1610 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001611 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001612 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001613
1614 // If we have not converted the argument type to the parameter type,
1615 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001616 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001617 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001618
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001619 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001620}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001621
1622static bool
1623IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1624 QualType &ToType,
1625 bool InOverloadResolution,
1626 StandardConversionSequence &SCS,
1627 bool CStyle) {
1628
1629 const RecordType *UT = ToType->getAsUnionType();
1630 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1631 return false;
1632 // The field to initialize within the transparent union.
1633 RecordDecl *UD = UT->getDecl();
1634 // It's compatible if the expression matches any of the fields.
1635 for (RecordDecl::field_iterator it = UD->field_begin(),
1636 itend = UD->field_end();
1637 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001638 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1639 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001640 ToType = it->getType();
1641 return true;
1642 }
1643 }
1644 return false;
1645}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001646
1647/// IsIntegralPromotion - Determines whether the conversion from the
1648/// expression From (whose potentially-adjusted type is FromType) to
1649/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1650/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001651bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001652 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001653 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001654 if (!To) {
1655 return false;
1656 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001657
1658 // An rvalue of type char, signed char, unsigned char, short int, or
1659 // unsigned short int can be converted to an rvalue of type int if
1660 // int can represent all the values of the source type; otherwise,
1661 // the source rvalue can be converted to an rvalue of type unsigned
1662 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001663 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1664 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001665 if (// We can promote any signed, promotable integer type to an int
1666 (FromType->isSignedIntegerType() ||
1667 // We can promote any unsigned integer type whose size is
1668 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001669 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001670 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001671 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001672 }
1673
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001674 return To->getKind() == BuiltinType::UInt;
1675 }
1676
Richard Smithb9c5a602012-09-13 21:18:54 +00001677 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001678 // A prvalue of an unscoped enumeration type whose underlying type is not
1679 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1680 // following types that can represent all the values of the enumeration
1681 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1682 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001683 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001684 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001685 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001686 // with lowest integer conversion rank (4.13) greater than the rank of long
1687 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001688 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001689 // C++11 [conv.prom]p4:
1690 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1691 // can be converted to a prvalue of its underlying type. Moreover, if
1692 // integral promotion can be applied to its underlying type, a prvalue of an
1693 // unscoped enumeration type whose underlying type is fixed can also be
1694 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001695 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1696 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1697 // provided for a scoped enumeration.
1698 if (FromEnumType->getDecl()->isScoped())
1699 return false;
1700
Richard Smithb9c5a602012-09-13 21:18:54 +00001701 // We can perform an integral promotion to the underlying type of the enum,
1702 // even if that's not the promoted type.
1703 if (FromEnumType->getDecl()->isFixed()) {
1704 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1705 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1706 IsIntegralPromotion(From, Underlying, ToType);
1707 }
1708
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001709 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001710 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001711 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001712 return Context.hasSameUnqualifiedType(ToType,
1713 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001714 }
John McCall56774992009-12-09 09:09:27 +00001715
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001716 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001717 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1718 // to an rvalue a prvalue of the first of the following types that can
1719 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001720 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001721 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001722 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001723 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001724 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001725 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001726 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001727 // Determine whether the type we're converting from is signed or
1728 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001729 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001730 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001731
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001732 // The types we'll try to promote to, in the appropriate
1733 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001734 QualType PromoteTypes[6] = {
1735 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001736 Context.LongTy, Context.UnsignedLongTy ,
1737 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001738 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001739 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001740 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1741 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001742 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001743 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1744 // We found the type that we can promote to. If this is the
1745 // type we wanted, we have a promotion. Otherwise, no
1746 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001747 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001748 }
1749 }
1750 }
1751
1752 // An rvalue for an integral bit-field (9.6) can be converted to an
1753 // rvalue of type int if int can represent all the values of the
1754 // bit-field; otherwise, it can be converted to unsigned int if
1755 // unsigned int can represent all the values of the bit-field. If
1756 // the bit-field is larger yet, no integral promotion applies to
1757 // it. If the bit-field has an enumerated type, it is treated as any
1758 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001759 // FIXME: We should delay checking of bit-fields until we actually perform the
1760 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001761 using llvm::APSInt;
1762 if (From)
1763 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001764 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001765 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001766 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1767 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1768 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001769
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001770 // Are we promoting to an int from a bitfield that fits in an int?
1771 if (BitWidth < ToSize ||
1772 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1773 return To->getKind() == BuiltinType::Int;
1774 }
Mike Stump11289f42009-09-09 15:08:12 +00001775
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001776 // Are we promoting to an unsigned int from an unsigned bitfield
1777 // that fits into an unsigned int?
1778 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1779 return To->getKind() == BuiltinType::UInt;
1780 }
Mike Stump11289f42009-09-09 15:08:12 +00001781
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001782 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001783 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001784 }
Mike Stump11289f42009-09-09 15:08:12 +00001785
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001786 // An rvalue of type bool can be converted to an rvalue of type int,
1787 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001788 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001789 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001790 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001791
1792 return false;
1793}
1794
1795/// IsFloatingPointPromotion - Determines whether the conversion from
1796/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1797/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001798bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001799 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1800 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001801 /// An rvalue of type float can be converted to an rvalue of type
1802 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001803 if (FromBuiltin->getKind() == BuiltinType::Float &&
1804 ToBuiltin->getKind() == BuiltinType::Double)
1805 return true;
1806
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001807 // C99 6.3.1.5p1:
1808 // When a float is promoted to double or long double, or a
1809 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001810 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001811 (FromBuiltin->getKind() == BuiltinType::Float ||
1812 FromBuiltin->getKind() == BuiltinType::Double) &&
1813 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1814 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001815
1816 // Half can be promoted to float.
1817 if (FromBuiltin->getKind() == BuiltinType::Half &&
1818 ToBuiltin->getKind() == BuiltinType::Float)
1819 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001820 }
1821
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001822 return false;
1823}
1824
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001825/// \brief Determine if a conversion is a complex promotion.
1826///
1827/// A complex promotion is defined as a complex -> complex conversion
1828/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001829/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001830bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001831 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001832 if (!FromComplex)
1833 return false;
1834
John McCall9dd450b2009-09-21 23:43:11 +00001835 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001836 if (!ToComplex)
1837 return false;
1838
1839 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001840 ToComplex->getElementType()) ||
1841 IsIntegralPromotion(0, FromComplex->getElementType(),
1842 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001843}
1844
Douglas Gregor237f96c2008-11-26 23:31:11 +00001845/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1846/// the pointer type FromPtr to a pointer to type ToPointee, with the
1847/// same type qualifiers as FromPtr has on its pointee type. ToType,
1848/// if non-empty, will be a pointer to ToType that may or may not have
1849/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001850///
Mike Stump11289f42009-09-09 15:08:12 +00001851static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001852BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001853 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001854 ASTContext &Context,
1855 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001856 assert((FromPtr->getTypeClass() == Type::Pointer ||
1857 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1858 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001859
John McCall31168b02011-06-15 23:02:42 +00001860 /// Conversions to 'id' subsume cv-qualifier conversions.
1861 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001862 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001863
1864 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001865 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001866 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001867 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001868
John McCall31168b02011-06-15 23:02:42 +00001869 if (StripObjCLifetime)
1870 Quals.removeObjCLifetime();
1871
Mike Stump11289f42009-09-09 15:08:12 +00001872 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001873 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001874 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001875 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001876 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001877
1878 // Build a pointer to ToPointee. It has the right qualifiers
1879 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001880 if (isa<ObjCObjectPointerType>(ToType))
1881 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001882 return Context.getPointerType(ToPointee);
1883 }
1884
1885 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001886 QualType QualifiedCanonToPointee
1887 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001888
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001889 if (isa<ObjCObjectPointerType>(ToType))
1890 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1891 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001892}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001893
Mike Stump11289f42009-09-09 15:08:12 +00001894static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001895 bool InOverloadResolution,
1896 ASTContext &Context) {
1897 // Handle value-dependent integral null pointer constants correctly.
1898 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1899 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001900 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001901 return !InOverloadResolution;
1902
Douglas Gregor56751b52009-09-25 04:25:58 +00001903 return Expr->isNullPointerConstant(Context,
1904 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1905 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001906}
Mike Stump11289f42009-09-09 15:08:12 +00001907
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001908/// IsPointerConversion - Determines whether the conversion of the
1909/// expression From, which has the (possibly adjusted) type FromType,
1910/// can be converted to the type ToType via a pointer conversion (C++
1911/// 4.10). If so, returns true and places the converted type (that
1912/// might differ from ToType in its cv-qualifiers at some level) into
1913/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001914///
Douglas Gregora29dc052008-11-27 01:19:21 +00001915/// This routine also supports conversions to and from block pointers
1916/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1917/// pointers to interfaces. FIXME: Once we've determined the
1918/// appropriate overloading rules for Objective-C, we may want to
1919/// split the Objective-C checks into a different routine; however,
1920/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001921/// conversions, so for now they live here. IncompatibleObjC will be
1922/// set if the conversion is an allowed Objective-C conversion that
1923/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001924bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001925 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001926 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001927 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001928 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001929 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1930 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001931 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001932
Mike Stump11289f42009-09-09 15:08:12 +00001933 // Conversion from a null pointer constant to any Objective-C pointer type.
1934 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001935 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001936 ConvertedType = ToType;
1937 return true;
1938 }
1939
Douglas Gregor231d1c62008-11-27 00:15:41 +00001940 // Blocks: Block pointers can be converted to void*.
1941 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001942 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001943 ConvertedType = ToType;
1944 return true;
1945 }
1946 // Blocks: A null pointer constant can be converted to a block
1947 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001948 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001949 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001950 ConvertedType = ToType;
1951 return true;
1952 }
1953
Sebastian Redl576fd422009-05-10 18:38:11 +00001954 // If the left-hand-side is nullptr_t, the right side can be a null
1955 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001956 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001957 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001958 ConvertedType = ToType;
1959 return true;
1960 }
1961
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001962 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001963 if (!ToTypePtr)
1964 return false;
1965
1966 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001967 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001968 ConvertedType = ToType;
1969 return true;
1970 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001971
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001972 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001973 // , including objective-c pointers.
1974 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001975 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001976 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001977 ConvertedType = BuildSimilarlyQualifiedPointerType(
1978 FromType->getAs<ObjCObjectPointerType>(),
1979 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001980 ToType, Context);
1981 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001982 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001983 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001984 if (!FromTypePtr)
1985 return false;
1986
1987 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001988
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001989 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001990 // pointer conversion, so don't do all of the work below.
1991 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1992 return false;
1993
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001994 // An rvalue of type "pointer to cv T," where T is an object type,
1995 // can be converted to an rvalue of type "pointer to cv void" (C++
1996 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001997 if (FromPointeeType->isIncompleteOrObjectType() &&
1998 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001999 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002000 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002001 ToType, Context,
2002 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002003 return true;
2004 }
2005
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002006 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002007 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002008 ToPointeeType->isVoidType()) {
2009 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2010 ToPointeeType,
2011 ToType, Context);
2012 return true;
2013 }
2014
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002015 // When we're overloading in C, we allow a special kind of pointer
2016 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002017 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002018 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002019 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002020 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002021 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002022 return true;
2023 }
2024
Douglas Gregor5c407d92008-10-23 00:40:37 +00002025 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002026 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002027 // An rvalue of type "pointer to cv D," where D is a class type,
2028 // can be converted to an rvalue of type "pointer to cv B," where
2029 // B is a base class (clause 10) of D. If B is an inaccessible
2030 // (clause 11) or ambiguous (10.2) base class of D, a program that
2031 // necessitates this conversion is ill-formed. The result of the
2032 // conversion is a pointer to the base class sub-object of the
2033 // derived class object. The null pointer value is converted to
2034 // the null pointer value of the destination type.
2035 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002036 // Note that we do not check for ambiguity or inaccessibility
2037 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002038 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002039 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002040 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002041 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002042 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002043 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002044 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002045 ToType, Context);
2046 return true;
2047 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002048
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002049 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2050 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2051 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2052 ToPointeeType,
2053 ToType, Context);
2054 return true;
2055 }
2056
Douglas Gregora119f102008-12-19 19:13:09 +00002057 return false;
2058}
Douglas Gregoraec25842011-04-26 23:16:46 +00002059
2060/// \brief Adopt the given qualifiers for the given type.
2061static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2062 Qualifiers TQs = T.getQualifiers();
2063
2064 // Check whether qualifiers already match.
2065 if (TQs == Qs)
2066 return T;
2067
2068 if (Qs.compatiblyIncludes(TQs))
2069 return Context.getQualifiedType(T, Qs);
2070
2071 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2072}
Douglas Gregora119f102008-12-19 19:13:09 +00002073
2074/// isObjCPointerConversion - Determines whether this is an
2075/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2076/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002077bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002078 QualType& ConvertedType,
2079 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002080 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002081 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002082
Douglas Gregoraec25842011-04-26 23:16:46 +00002083 // The set of qualifiers on the type we're converting from.
2084 Qualifiers FromQualifiers = FromType.getQualifiers();
2085
Steve Naroff7cae42b2009-07-10 23:34:53 +00002086 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002087 const ObjCObjectPointerType* ToObjCPtr =
2088 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002089 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002090 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002091
Steve Naroff7cae42b2009-07-10 23:34:53 +00002092 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002093 // If the pointee types are the same (ignoring qualifications),
2094 // then this is not a pointer conversion.
2095 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2096 FromObjCPtr->getPointeeType()))
2097 return false;
2098
Douglas Gregoraec25842011-04-26 23:16:46 +00002099 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002100 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002101 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002102 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002103 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002104 return true;
2105 }
2106 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002107 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002108 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002109 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002110 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002111 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002112 return true;
2113 }
2114 // Objective C++: We're able to convert from a pointer to an
2115 // interface to a pointer to a different interface.
2116 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002117 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2118 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002119 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002120 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2121 FromObjCPtr->getPointeeType()))
2122 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002123 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002124 ToObjCPtr->getPointeeType(),
2125 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002126 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002127 return true;
2128 }
2129
2130 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2131 // Okay: this is some kind of implicit downcast of Objective-C
2132 // interfaces, which is permitted. However, we're going to
2133 // complain about it.
2134 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002135 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002136 ToObjCPtr->getPointeeType(),
2137 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002138 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002139 return true;
2140 }
Mike Stump11289f42009-09-09 15:08:12 +00002141 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002142 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002143 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002144 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002145 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002146 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002147 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002148 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002149 // to a block pointer type.
2150 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002151 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002152 return true;
2153 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002154 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002155 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002156 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002157 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002158 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002159 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002160 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002161 return true;
2162 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002163 else
Douglas Gregora119f102008-12-19 19:13:09 +00002164 return false;
2165
Douglas Gregor033f56d2008-12-23 00:53:59 +00002166 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002167 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002168 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002169 else if (const BlockPointerType *FromBlockPtr =
2170 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002171 FromPointeeType = FromBlockPtr->getPointeeType();
2172 else
Douglas Gregora119f102008-12-19 19:13:09 +00002173 return false;
2174
Douglas Gregora119f102008-12-19 19:13:09 +00002175 // If we have pointers to pointers, recursively check whether this
2176 // is an Objective-C conversion.
2177 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2178 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2179 IncompatibleObjC)) {
2180 // We always complain about this conversion.
2181 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002182 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002183 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002184 return true;
2185 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002186 // Allow conversion of pointee being objective-c pointer to another one;
2187 // as in I* to id.
2188 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2189 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2190 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2191 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002192
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002193 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002194 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002195 return true;
2196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002197
Douglas Gregor033f56d2008-12-23 00:53:59 +00002198 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002199 // differences in the argument and result types are in Objective-C
2200 // pointer conversions. If so, we permit the conversion (but
2201 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002202 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002203 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002204 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002205 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002206 if (FromFunctionType && ToFunctionType) {
2207 // If the function types are exactly the same, this isn't an
2208 // Objective-C pointer conversion.
2209 if (Context.getCanonicalType(FromPointeeType)
2210 == Context.getCanonicalType(ToPointeeType))
2211 return false;
2212
2213 // Perform the quick checks that will tell us whether these
2214 // function types are obviously different.
2215 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2216 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2217 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2218 return false;
2219
2220 bool HasObjCConversion = false;
2221 if (Context.getCanonicalType(FromFunctionType->getResultType())
2222 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2223 // Okay, the types match exactly. Nothing to do.
2224 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2225 ToFunctionType->getResultType(),
2226 ConvertedType, IncompatibleObjC)) {
2227 // Okay, we have an Objective-C pointer conversion.
2228 HasObjCConversion = true;
2229 } else {
2230 // Function types are too different. Abort.
2231 return false;
2232 }
Mike Stump11289f42009-09-09 15:08:12 +00002233
Douglas Gregora119f102008-12-19 19:13:09 +00002234 // Check argument types.
2235 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2236 ArgIdx != NumArgs; ++ArgIdx) {
2237 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2238 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2239 if (Context.getCanonicalType(FromArgType)
2240 == Context.getCanonicalType(ToArgType)) {
2241 // Okay, the types match exactly. Nothing to do.
2242 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2243 ConvertedType, IncompatibleObjC)) {
2244 // Okay, we have an Objective-C pointer conversion.
2245 HasObjCConversion = true;
2246 } else {
2247 // Argument types are too different. Abort.
2248 return false;
2249 }
2250 }
2251
2252 if (HasObjCConversion) {
2253 // We had an Objective-C conversion. Allow this pointer
2254 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002255 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002256 IncompatibleObjC = true;
2257 return true;
2258 }
2259 }
2260
Sebastian Redl72b597d2009-01-25 19:43:20 +00002261 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002262}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002263
John McCall31168b02011-06-15 23:02:42 +00002264/// \brief Determine whether this is an Objective-C writeback conversion,
2265/// used for parameter passing when performing automatic reference counting.
2266///
2267/// \param FromType The type we're converting form.
2268///
2269/// \param ToType The type we're converting to.
2270///
2271/// \param ConvertedType The type that will be produced after applying
2272/// this conversion.
2273bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2274 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002275 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002276 Context.hasSameUnqualifiedType(FromType, ToType))
2277 return false;
2278
2279 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2280 QualType ToPointee;
2281 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2282 ToPointee = ToPointer->getPointeeType();
2283 else
2284 return false;
2285
2286 Qualifiers ToQuals = ToPointee.getQualifiers();
2287 if (!ToPointee->isObjCLifetimeType() ||
2288 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002289 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002290 return false;
2291
2292 // Argument must be a pointer to __strong to __weak.
2293 QualType FromPointee;
2294 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2295 FromPointee = FromPointer->getPointeeType();
2296 else
2297 return false;
2298
2299 Qualifiers FromQuals = FromPointee.getQualifiers();
2300 if (!FromPointee->isObjCLifetimeType() ||
2301 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2302 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2303 return false;
2304
2305 // Make sure that we have compatible qualifiers.
2306 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2307 if (!ToQuals.compatiblyIncludes(FromQuals))
2308 return false;
2309
2310 // Remove qualifiers from the pointee type we're converting from; they
2311 // aren't used in the compatibility check belong, and we'll be adding back
2312 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2313 FromPointee = FromPointee.getUnqualifiedType();
2314
2315 // The unqualified form of the pointee types must be compatible.
2316 ToPointee = ToPointee.getUnqualifiedType();
2317 bool IncompatibleObjC;
2318 if (Context.typesAreCompatible(FromPointee, ToPointee))
2319 FromPointee = ToPointee;
2320 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2321 IncompatibleObjC))
2322 return false;
2323
2324 /// \brief Construct the type we're converting to, which is a pointer to
2325 /// __autoreleasing pointee.
2326 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2327 ConvertedType = Context.getPointerType(FromPointee);
2328 return true;
2329}
2330
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002331bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2332 QualType& ConvertedType) {
2333 QualType ToPointeeType;
2334 if (const BlockPointerType *ToBlockPtr =
2335 ToType->getAs<BlockPointerType>())
2336 ToPointeeType = ToBlockPtr->getPointeeType();
2337 else
2338 return false;
2339
2340 QualType FromPointeeType;
2341 if (const BlockPointerType *FromBlockPtr =
2342 FromType->getAs<BlockPointerType>())
2343 FromPointeeType = FromBlockPtr->getPointeeType();
2344 else
2345 return false;
2346 // We have pointer to blocks, check whether the only
2347 // differences in the argument and result types are in Objective-C
2348 // pointer conversions. If so, we permit the conversion.
2349
2350 const FunctionProtoType *FromFunctionType
2351 = FromPointeeType->getAs<FunctionProtoType>();
2352 const FunctionProtoType *ToFunctionType
2353 = ToPointeeType->getAs<FunctionProtoType>();
2354
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002355 if (!FromFunctionType || !ToFunctionType)
2356 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002357
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002358 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002359 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002360
2361 // Perform the quick checks that will tell us whether these
2362 // function types are obviously different.
2363 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2364 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2365 return false;
2366
2367 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2368 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2369 if (FromEInfo != ToEInfo)
2370 return false;
2371
2372 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002373 if (Context.hasSameType(FromFunctionType->getResultType(),
2374 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002375 // Okay, the types match exactly. Nothing to do.
2376 } else {
2377 QualType RHS = FromFunctionType->getResultType();
2378 QualType LHS = ToFunctionType->getResultType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002379 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002380 !RHS.hasQualifiers() && LHS.hasQualifiers())
2381 LHS = LHS.getUnqualifiedType();
2382
2383 if (Context.hasSameType(RHS,LHS)) {
2384 // OK exact match.
2385 } else if (isObjCPointerConversion(RHS, LHS,
2386 ConvertedType, IncompatibleObjC)) {
2387 if (IncompatibleObjC)
2388 return false;
2389 // Okay, we have an Objective-C pointer conversion.
2390 }
2391 else
2392 return false;
2393 }
2394
2395 // Check argument types.
2396 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2397 ArgIdx != NumArgs; ++ArgIdx) {
2398 IncompatibleObjC = false;
2399 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2400 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2401 if (Context.hasSameType(FromArgType, ToArgType)) {
2402 // Okay, the types match exactly. Nothing to do.
2403 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2404 ConvertedType, IncompatibleObjC)) {
2405 if (IncompatibleObjC)
2406 return false;
2407 // Okay, we have an Objective-C pointer conversion.
2408 } else
2409 // Argument types are too different. Abort.
2410 return false;
2411 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002412 if (LangOpts.ObjCAutoRefCount &&
2413 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2414 ToFunctionType))
2415 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002416
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002417 ConvertedType = ToType;
2418 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002419}
2420
Richard Trieucaff2472011-11-23 22:32:32 +00002421enum {
2422 ft_default,
2423 ft_different_class,
2424 ft_parameter_arity,
2425 ft_parameter_mismatch,
2426 ft_return_type,
2427 ft_qualifer_mismatch
2428};
2429
2430/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2431/// function types. Catches different number of parameter, mismatch in
2432/// parameter types, and different return types.
2433void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2434 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002435 // If either type is not valid, include no extra info.
2436 if (FromType.isNull() || ToType.isNull()) {
2437 PDiag << ft_default;
2438 return;
2439 }
2440
Richard Trieucaff2472011-11-23 22:32:32 +00002441 // Get the function type from the pointers.
2442 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2443 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2444 *ToMember = ToType->getAs<MemberPointerType>();
2445 if (FromMember->getClass() != ToMember->getClass()) {
2446 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2447 << QualType(FromMember->getClass(), 0);
2448 return;
2449 }
2450 FromType = FromMember->getPointeeType();
2451 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002452 }
2453
Richard Trieu96ed5b62011-12-13 23:19:45 +00002454 if (FromType->isPointerType())
2455 FromType = FromType->getPointeeType();
2456 if (ToType->isPointerType())
2457 ToType = ToType->getPointeeType();
2458
2459 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002460 FromType = FromType.getNonReferenceType();
2461 ToType = ToType.getNonReferenceType();
2462
Richard Trieucaff2472011-11-23 22:32:32 +00002463 // Don't print extra info for non-specialized template functions.
2464 if (FromType->isInstantiationDependentType() &&
2465 !FromType->getAs<TemplateSpecializationType>()) {
2466 PDiag << ft_default;
2467 return;
2468 }
2469
Richard Trieu96ed5b62011-12-13 23:19:45 +00002470 // No extra info for same types.
2471 if (Context.hasSameType(FromType, ToType)) {
2472 PDiag << ft_default;
2473 return;
2474 }
2475
Richard Trieucaff2472011-11-23 22:32:32 +00002476 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2477 *ToFunction = ToType->getAs<FunctionProtoType>();
2478
2479 // Both types need to be function types.
2480 if (!FromFunction || !ToFunction) {
2481 PDiag << ft_default;
2482 return;
2483 }
2484
2485 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2486 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2487 << FromFunction->getNumArgs();
2488 return;
2489 }
2490
2491 // Handle different parameter types.
2492 unsigned ArgPos;
2493 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2494 PDiag << ft_parameter_mismatch << ArgPos + 1
2495 << ToFunction->getArgType(ArgPos)
2496 << FromFunction->getArgType(ArgPos);
2497 return;
2498 }
2499
2500 // Handle different return type.
2501 if (!Context.hasSameType(FromFunction->getResultType(),
2502 ToFunction->getResultType())) {
2503 PDiag << ft_return_type << ToFunction->getResultType()
2504 << FromFunction->getResultType();
2505 return;
2506 }
2507
2508 unsigned FromQuals = FromFunction->getTypeQuals(),
2509 ToQuals = ToFunction->getTypeQuals();
2510 if (FromQuals != ToQuals) {
2511 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2512 return;
2513 }
2514
2515 // Unable to find a difference, so add no extra info.
2516 PDiag << ft_default;
2517}
2518
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002519/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002520/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002521/// they have same number of arguments. This routine assumes that Objective-C
2522/// pointer types which only differ in their protocol qualifiers are equal.
Sylvestre Ledru830885c2012-07-23 08:59:39 +00002523/// If the parameters are different, ArgPos will have the parameter index
Richard Trieucaff2472011-11-23 22:32:32 +00002524/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002525bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002526 const FunctionProtoType *NewType,
2527 unsigned *ArgPos) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002528 if (!getLangOpts().ObjC1) {
Richard Trieucaff2472011-11-23 22:32:32 +00002529 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2530 N = NewType->arg_type_begin(),
2531 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2532 if (!Context.hasSameType(*O, *N)) {
2533 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2534 return false;
2535 }
2536 }
2537 return true;
2538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002539
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002540 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2541 N = NewType->arg_type_begin(),
2542 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2543 QualType ToType = (*O);
2544 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002545 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002546 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2547 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002548 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2549 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2550 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2551 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002552 continue;
2553 }
John McCall8b07ec22010-05-15 11:32:37 +00002554 else if (const ObjCObjectPointerType *PTTo =
2555 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002556 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002557 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002558 if (Context.hasSameUnqualifiedType(
2559 PTTo->getObjectType()->getBaseType(),
2560 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002561 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002562 }
Richard Trieucaff2472011-11-23 22:32:32 +00002563 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002564 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002565 }
2566 }
2567 return true;
2568}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002569
Douglas Gregor39c16d42008-10-24 04:54:22 +00002570/// CheckPointerConversion - Check the pointer conversion from the
2571/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002572/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002573/// conversions for which IsPointerConversion has already returned
2574/// true. It returns true and produces a diagnostic if there was an
2575/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002576bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002577 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002578 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002579 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002580 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002581 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002582
John McCall8cb679e2010-11-15 09:13:47 +00002583 Kind = CK_BitCast;
2584
David Blaikie1c7c8f72012-08-08 17:33:31 +00002585 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2586 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2587 Expr::NPCK_ZeroExpression) {
2588 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2589 DiagRuntimeBehavior(From->getExprLoc(), From,
2590 PDiag(diag::warn_impcast_bool_to_null_pointer)
2591 << ToType << From->getSourceRange());
2592 else if (!isUnevaluatedContext())
2593 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2594 << ToType << From->getSourceRange();
2595 }
John McCall9320b872011-09-09 05:25:32 +00002596 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2597 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002598 QualType FromPointeeType = FromPtrType->getPointeeType(),
2599 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002600
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002601 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2602 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002603 // We must have a derived-to-base conversion. Check an
2604 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002605 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2606 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002607 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002608 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002609 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002610
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002611 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002612 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002613 }
2614 }
John McCall9320b872011-09-09 05:25:32 +00002615 } else if (const ObjCObjectPointerType *ToPtrType =
2616 ToType->getAs<ObjCObjectPointerType>()) {
2617 if (const ObjCObjectPointerType *FromPtrType =
2618 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002619 // Objective-C++ conversions are always okay.
2620 // FIXME: We should have a different class of conversions for the
2621 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002622 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002623 return false;
John McCall9320b872011-09-09 05:25:32 +00002624 } else if (FromType->isBlockPointerType()) {
2625 Kind = CK_BlockPointerToObjCPointerCast;
2626 } else {
2627 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002628 }
John McCall9320b872011-09-09 05:25:32 +00002629 } else if (ToType->isBlockPointerType()) {
2630 if (!FromType->isBlockPointerType())
2631 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002632 }
John McCall8cb679e2010-11-15 09:13:47 +00002633
2634 // We shouldn't fall into this case unless it's valid for other
2635 // reasons.
2636 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2637 Kind = CK_NullToPointer;
2638
Douglas Gregor39c16d42008-10-24 04:54:22 +00002639 return false;
2640}
2641
Sebastian Redl72b597d2009-01-25 19:43:20 +00002642/// IsMemberPointerConversion - Determines whether the conversion of the
2643/// expression From, which has the (possibly adjusted) type FromType, can be
2644/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2645/// If so, returns true and places the converted type (that might differ from
2646/// ToType in its cv-qualifiers at some level) into ConvertedType.
2647bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002648 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002649 bool InOverloadResolution,
2650 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002651 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002652 if (!ToTypePtr)
2653 return false;
2654
2655 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002656 if (From->isNullPointerConstant(Context,
2657 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2658 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002659 ConvertedType = ToType;
2660 return true;
2661 }
2662
2663 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002664 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002665 if (!FromTypePtr)
2666 return false;
2667
2668 // A pointer to member of B can be converted to a pointer to member of D,
2669 // where D is derived from B (C++ 4.11p2).
2670 QualType FromClass(FromTypePtr->getClass(), 0);
2671 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002672
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002673 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002674 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002675 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002676 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2677 ToClass.getTypePtr());
2678 return true;
2679 }
2680
2681 return false;
2682}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002683
Sebastian Redl72b597d2009-01-25 19:43:20 +00002684/// CheckMemberPointerConversion - Check the member pointer conversion from the
2685/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002686/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002687/// for which IsMemberPointerConversion has already returned true. It returns
2688/// true and produces a diagnostic if there was an error, or returns false
2689/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002690bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002691 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002692 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002693 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002694 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002695 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002696 if (!FromPtrType) {
2697 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002698 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002699 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002700 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002701 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002702 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002703 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002704
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002705 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002706 assert(ToPtrType && "No member pointer cast has a target type "
2707 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002708
Sebastian Redled8f2002009-01-28 18:33:18 +00002709 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2710 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002711
Sebastian Redled8f2002009-01-28 18:33:18 +00002712 // FIXME: What about dependent types?
2713 assert(FromClass->isRecordType() && "Pointer into non-class.");
2714 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002715
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002716 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002717 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002718 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2719 assert(DerivationOkay &&
2720 "Should not have been called if derivation isn't OK.");
2721 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002722
Sebastian Redled8f2002009-01-28 18:33:18 +00002723 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2724 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002725 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2726 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2727 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2728 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002729 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002730
Douglas Gregor89ee6822009-02-28 01:32:25 +00002731 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002732 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2733 << FromClass << ToClass << QualType(VBase, 0)
2734 << From->getSourceRange();
2735 return true;
2736 }
2737
John McCall5b0829a2010-02-10 09:31:12 +00002738 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002739 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2740 Paths.front(),
2741 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002742
Anders Carlssond7923c62009-08-22 23:33:40 +00002743 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002744 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002745 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002746 return false;
2747}
2748
Douglas Gregor9a657932008-10-21 23:43:52 +00002749/// IsQualificationConversion - Determines whether the conversion from
2750/// an rvalue of type FromType to ToType is a qualification conversion
2751/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002752///
2753/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2754/// when the qualification conversion involves a change in the Objective-C
2755/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002756bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002757Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002758 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002759 FromType = Context.getCanonicalType(FromType);
2760 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002761 ObjCLifetimeConversion = false;
2762
Douglas Gregor9a657932008-10-21 23:43:52 +00002763 // If FromType and ToType are the same type, this is not a
2764 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002765 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002766 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002767
Douglas Gregor9a657932008-10-21 23:43:52 +00002768 // (C++ 4.4p4):
2769 // A conversion can add cv-qualifiers at levels other than the first
2770 // in multi-level pointers, subject to the following rules: [...]
2771 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002772 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002773 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002774 // Within each iteration of the loop, we check the qualifiers to
2775 // determine if this still looks like a qualification
2776 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002777 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002778 // until there are no more pointers or pointers-to-members left to
2779 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002780 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002781
Douglas Gregor90609aa2011-04-25 18:40:17 +00002782 Qualifiers FromQuals = FromType.getQualifiers();
2783 Qualifiers ToQuals = ToType.getQualifiers();
2784
John McCall31168b02011-06-15 23:02:42 +00002785 // Objective-C ARC:
2786 // Check Objective-C lifetime conversions.
2787 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2788 UnwrappedAnyPointer) {
2789 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2790 ObjCLifetimeConversion = true;
2791 FromQuals.removeObjCLifetime();
2792 ToQuals.removeObjCLifetime();
2793 } else {
2794 // Qualification conversions cannot cast between different
2795 // Objective-C lifetime qualifiers.
2796 return false;
2797 }
2798 }
2799
Douglas Gregorf30053d2011-05-08 06:09:53 +00002800 // Allow addition/removal of GC attributes but not changing GC attributes.
2801 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2802 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2803 FromQuals.removeObjCGCAttr();
2804 ToQuals.removeObjCGCAttr();
2805 }
2806
Douglas Gregor9a657932008-10-21 23:43:52 +00002807 // -- for every j > 0, if const is in cv 1,j then const is in cv
2808 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002809 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002810 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002811
Douglas Gregor9a657932008-10-21 23:43:52 +00002812 // -- if the cv 1,j and cv 2,j are different, then const is in
2813 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002814 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002815 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002816 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002817
Douglas Gregor9a657932008-10-21 23:43:52 +00002818 // Keep track of whether all prior cv-qualifiers in the "to" type
2819 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002820 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002821 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002822 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002823
2824 // We are left with FromType and ToType being the pointee types
2825 // after unwrapping the original FromType and ToType the same number
2826 // of types. If we unwrapped any pointers, and if FromType and
2827 // ToType have the same unqualified type (since we checked
2828 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002829 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002830}
2831
Douglas Gregorc79862f2012-04-12 17:51:55 +00002832/// \brief - Determine whether this is a conversion from a scalar type to an
2833/// atomic type.
2834///
2835/// If successful, updates \c SCS's second and third steps in the conversion
2836/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002837static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2838 bool InOverloadResolution,
2839 StandardConversionSequence &SCS,
2840 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002841 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2842 if (!ToAtomic)
2843 return false;
2844
2845 StandardConversionSequence InnerSCS;
2846 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2847 InOverloadResolution, InnerSCS,
2848 CStyle, /*AllowObjCWritebackConversion=*/false))
2849 return false;
2850
2851 SCS.Second = InnerSCS.Second;
2852 SCS.setToType(1, InnerSCS.getToType(1));
2853 SCS.Third = InnerSCS.Third;
2854 SCS.QualificationIncludesObjCLifetime
2855 = InnerSCS.QualificationIncludesObjCLifetime;
2856 SCS.setToType(2, InnerSCS.getToType(2));
2857 return true;
2858}
2859
Sebastian Redle5417162012-03-27 18:33:03 +00002860static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2861 CXXConstructorDecl *Constructor,
2862 QualType Type) {
2863 const FunctionProtoType *CtorType =
2864 Constructor->getType()->getAs<FunctionProtoType>();
2865 if (CtorType->getNumArgs() > 0) {
2866 QualType FirstArg = CtorType->getArgType(0);
2867 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2868 return true;
2869 }
2870 return false;
2871}
2872
Sebastian Redl82ace982012-02-11 23:51:08 +00002873static OverloadingResult
2874IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2875 CXXRecordDecl *To,
2876 UserDefinedConversionSequence &User,
2877 OverloadCandidateSet &CandidateSet,
2878 bool AllowExplicit) {
2879 DeclContext::lookup_iterator Con, ConEnd;
2880 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2881 Con != ConEnd; ++Con) {
2882 NamedDecl *D = *Con;
2883 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2884
2885 // Find the constructor (which may be a template).
2886 CXXConstructorDecl *Constructor = 0;
2887 FunctionTemplateDecl *ConstructorTmpl
2888 = dyn_cast<FunctionTemplateDecl>(D);
2889 if (ConstructorTmpl)
2890 Constructor
2891 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2892 else
2893 Constructor = cast<CXXConstructorDecl>(D);
2894
2895 bool Usable = !Constructor->isInvalidDecl() &&
2896 S.isInitListConstructor(Constructor) &&
2897 (AllowExplicit || !Constructor->isExplicit());
2898 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002899 // If the first argument is (a reference to) the target type,
2900 // suppress conversions.
2901 bool SuppressUserConversions =
2902 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002903 if (ConstructorTmpl)
2904 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2905 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002906 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002907 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002908 else
2909 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002910 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002911 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002912 }
2913 }
2914
2915 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2916
2917 OverloadCandidateSet::iterator Best;
2918 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2919 case OR_Success: {
2920 // Record the standard conversion we used and the conversion function.
2921 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2922 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2923
2924 QualType ThisType = Constructor->getThisType(S.Context);
2925 // Initializer lists don't have conversions as such.
2926 User.Before.setAsIdentityConversion();
2927 User.HadMultipleCandidates = HadMultipleCandidates;
2928 User.ConversionFunction = Constructor;
2929 User.FoundConversionFunction = Best->FoundDecl;
2930 User.After.setAsIdentityConversion();
2931 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2932 User.After.setAllToTypes(ToType);
2933 return OR_Success;
2934 }
2935
2936 case OR_No_Viable_Function:
2937 return OR_No_Viable_Function;
2938 case OR_Deleted:
2939 return OR_Deleted;
2940 case OR_Ambiguous:
2941 return OR_Ambiguous;
2942 }
2943
2944 llvm_unreachable("Invalid OverloadResult!");
2945}
2946
Douglas Gregor576e98c2009-01-30 23:27:23 +00002947/// Determines whether there is a user-defined conversion sequence
2948/// (C++ [over.ics.user]) that converts expression From to the type
2949/// ToType. If such a conversion exists, User will contain the
2950/// user-defined conversion sequence that performs such a conversion
2951/// and this routine will return true. Otherwise, this routine returns
2952/// false and User is unspecified.
2953///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002954/// \param AllowExplicit true if the conversion should consider C++0x
2955/// "explicit" conversion functions as well as non-explicit conversion
2956/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002957static OverloadingResult
2958IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002959 UserDefinedConversionSequence &User,
2960 OverloadCandidateSet &CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002961 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002962 // Whether we will only visit constructors.
2963 bool ConstructorsOnly = false;
2964
2965 // If the type we are conversion to is a class type, enumerate its
2966 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002967 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002968 // C++ [over.match.ctor]p1:
2969 // When objects of class type are direct-initialized (8.5), or
2970 // copy-initialized from an expression of the same or a
2971 // derived class type (8.5), overload resolution selects the
2972 // constructor. [...] For copy-initialization, the candidate
2973 // functions are all the converting constructors (12.3.1) of
2974 // that class. The argument list is the expression-list within
2975 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002976 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002977 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002978 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002979 ConstructorsOnly = true;
2980
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002981 S.RequireCompleteType(From->getLocStart(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002982 // RequireCompleteType may have returned true due to some invalid decl
2983 // during template instantiation, but ToType may be complete enough now
2984 // to try to recover.
2985 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002986 // We're not going to find any constructors.
2987 } else if (CXXRecordDecl *ToRecordDecl
2988 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002989
2990 Expr **Args = &From;
2991 unsigned NumArgs = 1;
2992 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002993 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl82ace982012-02-11 23:51:08 +00002994 // But first, see if there is an init-list-contructor that will work.
2995 OverloadingResult Result = IsInitializerListConstructorConversion(
2996 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2997 if (Result != OR_No_Viable_Function)
2998 return Result;
2999 // Never mind.
3000 CandidateSet.clear();
3001
3002 // If we're list-initializing, we pass the individual elements as
3003 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003004 Args = InitList->getInits();
3005 NumArgs = InitList->getNumInits();
3006 ListInitializing = true;
3007 }
3008
Douglas Gregor89ee6822009-02-28 01:32:25 +00003009 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00003010 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00003011 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003012 NamedDecl *D = *Con;
3013 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3014
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003015 // Find the constructor (which may be a template).
3016 CXXConstructorDecl *Constructor = 0;
3017 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003018 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003019 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003020 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003021 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3022 else
John McCalla0296f72010-03-19 07:35:19 +00003023 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003024
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003025 bool Usable = !Constructor->isInvalidDecl();
3026 if (ListInitializing)
3027 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3028 else
3029 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3030 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003031 bool SuppressUserConversions = !ConstructorsOnly;
3032 if (SuppressUserConversions && ListInitializing) {
3033 SuppressUserConversions = false;
3034 if (NumArgs == 1) {
3035 // If the first argument is (a reference to) the target type,
3036 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003037 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3038 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003039 }
3040 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003041 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003042 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3043 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003044 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003045 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003046 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003047 // Allow one user-defined conversion when user specifies a
3048 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003049 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003050 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003051 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003052 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003053 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003054 }
3055 }
3056
Douglas Gregor5ab11652010-04-17 22:01:05 +00003057 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003058 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003059 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003060 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003061 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003062 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003063 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003064 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3065 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00003066 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003067 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003068 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003069 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003070 DeclAccessPair FoundDecl = I.getPair();
3071 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003072 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3073 if (isa<UsingShadowDecl>(D))
3074 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3075
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003076 CXXConversionDecl *Conv;
3077 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003078 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3079 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003080 else
John McCallda4458e2010-03-31 01:36:47 +00003081 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003082
3083 if (AllowExplicit || !Conv->isExplicit()) {
3084 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003085 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3086 ActingContext, From, ToType,
3087 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003088 else
John McCall5c32be02010-08-24 20:38:10 +00003089 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3090 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003091 }
3092 }
3093 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003094 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003095
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003096 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3097
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003098 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003099 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003100 case OR_Success:
3101 // Record the standard conversion we used and the conversion function.
3102 if (CXXConstructorDecl *Constructor
3103 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003104 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth30141632011-02-25 19:41:05 +00003105
John McCall5c32be02010-08-24 20:38:10 +00003106 // C++ [over.ics.user]p1:
3107 // If the user-defined conversion is specified by a
3108 // constructor (12.3.1), the initial standard conversion
3109 // sequence converts the source type to the type required by
3110 // the argument of the constructor.
3111 //
3112 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003113 if (isa<InitListExpr>(From)) {
3114 // Initializer lists don't have conversions as such.
3115 User.Before.setAsIdentityConversion();
3116 } else {
3117 if (Best->Conversions[0].isEllipsis())
3118 User.EllipsisConversion = true;
3119 else {
3120 User.Before = Best->Conversions[0].Standard;
3121 User.EllipsisConversion = false;
3122 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003123 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003124 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003125 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003126 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003127 User.After.setAsIdentityConversion();
3128 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3129 User.After.setAllToTypes(ToType);
3130 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003131 }
3132 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003133 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003134 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth30141632011-02-25 19:41:05 +00003135
John McCall5c32be02010-08-24 20:38:10 +00003136 // 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);
3964 const UnresolvedSetImpl *Conversions
3965 = T2RecordDecl->getVisibleConversionFunctions();
3966 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3967 E = Conversions->end(); I != E; ++I) {
3968 NamedDecl *D = *I;
3969 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3970 if (isa<UsingShadowDecl>(D))
3971 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3972
3973 FunctionTemplateDecl *ConvTemplate
3974 = dyn_cast<FunctionTemplateDecl>(D);
3975 CXXConversionDecl *Conv;
3976 if (ConvTemplate)
3977 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3978 else
3979 Conv = cast<CXXConversionDecl>(D);
3980
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003981 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003982 // explicit conversions, skip it.
3983 if (!AllowExplicit && Conv->isExplicit())
3984 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003985
Douglas Gregor836a7e82010-08-11 02:15:33 +00003986 if (AllowRvalues) {
3987 bool DerivedToBase = false;
3988 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003989 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003990
3991 // If we are initializing an rvalue reference, don't permit conversion
3992 // functions that return lvalues.
3993 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3994 const ReferenceType *RefType
3995 = Conv->getConversionType()->getAs<LValueReferenceType>();
3996 if (RefType && !RefType->getPointeeType()->isFunctionType())
3997 continue;
3998 }
3999
Douglas Gregor836a7e82010-08-11 02:15:33 +00004000 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004001 S.CompareReferenceRelationship(
4002 DeclLoc,
4003 Conv->getConversionType().getNonReferenceType()
4004 .getUnqualifiedType(),
4005 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004006 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004007 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004008 continue;
4009 } else {
4010 // If the conversion function doesn't return a reference type,
4011 // it can't be considered for this conversion. An rvalue reference
4012 // is only acceptable if its referencee is a function type.
4013
4014 const ReferenceType *RefType =
4015 Conv->getConversionType()->getAs<ReferenceType>();
4016 if (!RefType ||
4017 (!RefType->isLValueReferenceType() &&
4018 !RefType->getPointeeType()->isFunctionType()))
4019 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004020 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004021
Douglas Gregor836a7e82010-08-11 02:15:33 +00004022 if (ConvTemplate)
4023 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00004024 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004025 else
4026 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00004027 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00004028 }
4029
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004030 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4031
Sebastian Redld92badf2010-06-30 18:13:39 +00004032 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004033 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004034 case OR_Success:
4035 // C++ [over.ics.ref]p1:
4036 //
4037 // [...] If the parameter binds directly to the result of
4038 // applying a conversion function to the argument
4039 // expression, the implicit conversion sequence is a
4040 // user-defined conversion sequence (13.3.3.1.2), with the
4041 // second standard conversion sequence either an identity
4042 // conversion or, if the conversion function returns an
4043 // entity of a type that is a derived class of the parameter
4044 // type, a derived-to-base Conversion.
4045 if (!Best->FinalConversion.DirectBinding)
4046 return false;
4047
Chandler Carruth30141632011-02-25 19:41:05 +00004048 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00004049 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004050 ICS.setUserDefined();
4051 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4052 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004053 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004054 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004055 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004056 ICS.UserDefined.EllipsisConversion = false;
4057 assert(ICS.UserDefined.After.ReferenceBinding &&
4058 ICS.UserDefined.After.DirectBinding &&
4059 "Expected a direct reference binding!");
4060 return true;
4061
4062 case OR_Ambiguous:
4063 ICS.setAmbiguous();
4064 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4065 Cand != CandidateSet.end(); ++Cand)
4066 if (Cand->Viable)
4067 ICS.Ambiguous.addConversion(Cand->Function);
4068 return true;
4069
4070 case OR_No_Viable_Function:
4071 case OR_Deleted:
4072 // There was no suitable conversion, or we found a deleted
4073 // conversion; continue with other checks.
4074 return false;
4075 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004076
David Blaikie8a40f702012-01-17 06:56:22 +00004077 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004078}
4079
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004080/// \brief Compute an implicit conversion sequence for reference
4081/// initialization.
4082static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004083TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004084 SourceLocation DeclLoc,
4085 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004086 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004087 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4088
4089 // Most paths end in a failed conversion.
4090 ImplicitConversionSequence ICS;
4091 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4092
4093 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4094 QualType T2 = Init->getType();
4095
4096 // If the initializer is the address of an overloaded function, try
4097 // to resolve the overloaded function. If all goes well, T2 is the
4098 // type of the resulting function.
4099 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4100 DeclAccessPair Found;
4101 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4102 false, Found))
4103 T2 = Fn->getType();
4104 }
4105
4106 // Compute some basic properties of the types and the initializer.
4107 bool isRValRef = DeclType->isRValueReferenceType();
4108 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004109 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004110 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004111 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004112 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004113 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004114 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004115
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004116
Sebastian Redld92badf2010-06-30 18:13:39 +00004117 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004118 // A reference to type "cv1 T1" is initialized by an expression
4119 // of type "cv2 T2" as follows:
4120
Sebastian Redld92badf2010-06-30 18:13:39 +00004121 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004122 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004123 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4124 // reference-compatible with "cv2 T2," or
4125 //
4126 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4127 if (InitCategory.isLValue() &&
4128 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004129 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004130 // When a parameter of reference type binds directly (8.5.3)
4131 // to an argument expression, the implicit conversion sequence
4132 // is the identity conversion, unless the argument expression
4133 // has a type that is a derived class of the parameter type,
4134 // in which case the implicit conversion sequence is a
4135 // derived-to-base Conversion (13.3.3.1).
4136 ICS.setStandard();
4137 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004138 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4139 : ObjCConversion? ICK_Compatible_Conversion
4140 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004141 ICS.Standard.Third = ICK_Identity;
4142 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4143 ICS.Standard.setToType(0, T2);
4144 ICS.Standard.setToType(1, T1);
4145 ICS.Standard.setToType(2, T1);
4146 ICS.Standard.ReferenceBinding = true;
4147 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004148 ICS.Standard.IsLvalueReference = !isRValRef;
4149 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4150 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004151 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004152 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004153 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004154
Sebastian Redld92badf2010-06-30 18:13:39 +00004155 // Nothing more to do: the inaccessibility/ambiguity check for
4156 // derived-to-base conversions is suppressed when we're
4157 // computing the implicit conversion sequence (C++
4158 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004159 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004160 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004161
Sebastian Redld92badf2010-06-30 18:13:39 +00004162 // -- has a class type (i.e., T2 is a class type), where T1 is
4163 // not reference-related to T2, and can be implicitly
4164 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4165 // is reference-compatible with "cv3 T3" 92) (this
4166 // conversion is selected by enumerating the applicable
4167 // conversion functions (13.3.1.6) and choosing the best
4168 // one through overload resolution (13.3)),
4169 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004170 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004171 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004172 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4173 Init, T2, /*AllowRvalues=*/false,
4174 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004175 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004176 }
4177 }
4178
Sebastian Redld92badf2010-06-30 18:13:39 +00004179 // -- Otherwise, the reference shall be an lvalue reference to a
4180 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004181 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004182 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004183 // We actually handle one oddity of C++ [over.ics.ref] at this
4184 // point, which is that, due to p2 (which short-circuits reference
4185 // binding by only attempting a simple conversion for non-direct
4186 // bindings) and p3's strange wording, we allow a const volatile
4187 // reference to bind to an rvalue. Hence the check for the presence
4188 // of "const" rather than checking for "const" being the only
4189 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004190 // This is also the point where rvalue references and lvalue inits no longer
4191 // go together.
Richard Smithce4f6082012-05-24 04:29:20 +00004192 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004193 return ICS;
4194
Douglas Gregorf143cd52011-01-24 16:14:37 +00004195 // -- If the initializer expression
4196 //
4197 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004198 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004199 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4200 (InitCategory.isXValue() ||
4201 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4202 (InitCategory.isLValue() && T2->isFunctionType()))) {
4203 ICS.setStandard();
4204 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004205 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004206 : ObjCConversion? ICK_Compatible_Conversion
4207 : ICK_Identity;
4208 ICS.Standard.Third = ICK_Identity;
4209 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4210 ICS.Standard.setToType(0, T2);
4211 ICS.Standard.setToType(1, T1);
4212 ICS.Standard.setToType(2, T1);
4213 ICS.Standard.ReferenceBinding = true;
4214 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4215 // binding unless we're binding to a class prvalue.
4216 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4217 // allow the use of rvalue references in C++98/03 for the benefit of
4218 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004219 ICS.Standard.DirectBinding =
David Blaikiebbafb8a2012-03-11 07:00:24 +00004220 S.getLangOpts().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004221 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004222 ICS.Standard.IsLvalueReference = !isRValRef;
4223 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004224 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004225 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004226 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004227 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004228 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004229 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004230
Douglas Gregorf143cd52011-01-24 16:14:37 +00004231 // -- has a class type (i.e., T2 is a class type), where T1 is not
4232 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004233 // an xvalue, class prvalue, or function lvalue of type
4234 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004235 // "cv3 T3",
4236 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004237 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004238 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004239 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004240 // class subobject).
4241 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004242 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004243 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4244 Init, T2, /*AllowRvalues=*/true,
4245 AllowExplicit)) {
4246 // In the second case, if the reference is an rvalue reference
4247 // and the second standard conversion sequence of the
4248 // user-defined conversion sequence includes an lvalue-to-rvalue
4249 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004250 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004251 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4252 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4253
Douglas Gregor95273c32011-01-21 16:36:05 +00004254 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004255 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004256
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004257 // -- Otherwise, a temporary of type "cv1 T1" is created and
4258 // initialized from the initializer expression using the
4259 // rules for a non-reference copy initialization (8.5). The
4260 // reference is then bound to the temporary. If T1 is
4261 // reference-related to T2, cv1 must be the same
4262 // cv-qualification as, or greater cv-qualification than,
4263 // cv2; otherwise, the program is ill-formed.
4264 if (RefRelationship == Sema::Ref_Related) {
4265 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4266 // we would be reference-compatible or reference-compatible with
4267 // added qualification. But that wasn't the case, so the reference
4268 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004269 //
4270 // Note that we only want to check address spaces and cvr-qualifiers here.
4271 // ObjC GC and lifetime qualifiers aren't important.
4272 Qualifiers T1Quals = T1.getQualifiers();
4273 Qualifiers T2Quals = T2.getQualifiers();
4274 T1Quals.removeObjCGCAttr();
4275 T1Quals.removeObjCLifetime();
4276 T2Quals.removeObjCGCAttr();
4277 T2Quals.removeObjCLifetime();
4278 if (!T1Quals.compatiblyIncludes(T2Quals))
4279 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004280 }
4281
4282 // If at least one of the types is a class type, the types are not
4283 // related, and we aren't allowed any user conversions, the
4284 // reference binding fails. This case is important for breaking
4285 // recursion, since TryImplicitConversion below will attempt to
4286 // create a temporary through the use of a copy constructor.
4287 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4288 (T1->isRecordType() || T2->isRecordType()))
4289 return ICS;
4290
Douglas Gregorcba72b12011-01-21 05:18:22 +00004291 // If T1 is reference-related to T2 and the reference is an rvalue
4292 // reference, the initializer expression shall not be an lvalue.
4293 if (RefRelationship >= Sema::Ref_Related &&
4294 isRValRef && Init->Classify(S.Context).isLValue())
4295 return ICS;
4296
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004297 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004298 // When a parameter of reference type is not bound directly to
4299 // an argument expression, the conversion sequence is the one
4300 // required to convert the argument expression to the
4301 // underlying type of the reference according to
4302 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4303 // to copy-initializing a temporary of the underlying type with
4304 // the argument expression. Any difference in top-level
4305 // cv-qualification is subsumed by the initialization itself
4306 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004307 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4308 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004309 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004310 /*CStyle=*/false,
4311 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004312
4313 // Of course, that's still a reference binding.
4314 if (ICS.isStandard()) {
4315 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004316 ICS.Standard.IsLvalueReference = !isRValRef;
4317 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4318 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004319 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004320 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004321 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004322 // Don't allow rvalue references to bind to lvalues.
4323 if (DeclType->isRValueReferenceType()) {
4324 if (const ReferenceType *RefType
4325 = ICS.UserDefined.ConversionFunction->getResultType()
4326 ->getAs<LValueReferenceType>()) {
4327 if (!RefType->getPointeeType()->isFunctionType()) {
4328 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4329 DeclType);
4330 return ICS;
4331 }
4332 }
4333 }
4334
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004335 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004336 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4337 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4338 ICS.UserDefined.After.BindsToRvalue = true;
4339 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4340 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004341 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004342
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004343 return ICS;
4344}
4345
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004346static ImplicitConversionSequence
4347TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4348 bool SuppressUserConversions,
4349 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004350 bool AllowObjCWritebackConversion,
4351 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004352
4353/// TryListConversion - Try to copy-initialize a value of type ToType from the
4354/// initializer list From.
4355static ImplicitConversionSequence
4356TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4357 bool SuppressUserConversions,
4358 bool InOverloadResolution,
4359 bool AllowObjCWritebackConversion) {
4360 // C++11 [over.ics.list]p1:
4361 // When an argument is an initializer list, it is not an expression and
4362 // special rules apply for converting it to a parameter type.
4363
4364 ImplicitConversionSequence Result;
4365 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004366 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004367
Sebastian Redl09edce02012-01-23 22:09:39 +00004368 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004369 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004370 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004371 return Result;
4372
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004373 // C++11 [over.ics.list]p2:
4374 // If the parameter type is std::initializer_list<X> or "array of X" and
4375 // all the elements can be implicitly converted to X, the implicit
4376 // conversion sequence is the worst conversion necessary to convert an
4377 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004378 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004379 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004380 if (ToType->isArrayType())
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004381 X = S.Context.getBaseElementType(ToType);
4382 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004383 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004384 if (!X.isNull()) {
4385 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4386 Expr *Init = From->getInit(i);
4387 ImplicitConversionSequence ICS =
4388 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4389 InOverloadResolution,
4390 AllowObjCWritebackConversion);
4391 // If a single element isn't convertible, fail.
4392 if (ICS.isBad()) {
4393 Result = ICS;
4394 break;
4395 }
4396 // Otherwise, look for the worst conversion.
4397 if (Result.isBad() ||
4398 CompareImplicitConversionSequences(S, ICS, Result) ==
4399 ImplicitConversionSequence::Worse)
4400 Result = ICS;
4401 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004402
4403 // For an empty list, we won't have computed any conversion sequence.
4404 // Introduce the identity conversion sequence.
4405 if (From->getNumInits() == 0) {
4406 Result.setStandard();
4407 Result.Standard.setAsIdentityConversion();
4408 Result.Standard.setFromType(ToType);
4409 Result.Standard.setAllToTypes(ToType);
4410 }
4411
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004412 Result.setListInitializationSequence();
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004413 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004414 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004415 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004416
4417 // C++11 [over.ics.list]p3:
4418 // Otherwise, if the parameter is a non-aggregate class X and overload
4419 // resolution chooses a single best constructor [...] the implicit
4420 // conversion sequence is a user-defined conversion sequence. If multiple
4421 // constructors are viable but none is better than the others, the
4422 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004423 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4424 // This function can deal with initializer lists.
4425 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4426 /*AllowExplicit=*/false,
4427 InOverloadResolution, /*CStyle=*/false,
4428 AllowObjCWritebackConversion);
4429 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004430 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004431 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004432
4433 // C++11 [over.ics.list]p4:
4434 // Otherwise, if the parameter has an aggregate type which can be
4435 // initialized from the initializer list [...] the implicit conversion
4436 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004437 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004438 // Type is an aggregate, argument is an init list. At this point it comes
4439 // down to checking whether the initialization works.
4440 // FIXME: Find out whether this parameter is consumed or not.
4441 InitializedEntity Entity =
4442 InitializedEntity::InitializeParameter(S.Context, ToType,
4443 /*Consumed=*/false);
4444 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4445 Result.setUserDefined();
4446 Result.UserDefined.Before.setAsIdentityConversion();
4447 // Initializer lists don't have a type.
4448 Result.UserDefined.Before.setFromType(QualType());
4449 Result.UserDefined.Before.setAllToTypes(QualType());
4450
4451 Result.UserDefined.After.setAsIdentityConversion();
4452 Result.UserDefined.After.setFromType(ToType);
4453 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004454 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004455 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004456 return Result;
4457 }
4458
4459 // C++11 [over.ics.list]p5:
4460 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004461 if (ToType->isReferenceType()) {
4462 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4463 // mention initializer lists in any way. So we go by what list-
4464 // initialization would do and try to extrapolate from that.
4465
4466 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4467
4468 // If the initializer list has a single element that is reference-related
4469 // to the parameter type, we initialize the reference from that.
4470 if (From->getNumInits() == 1) {
4471 Expr *Init = From->getInit(0);
4472
4473 QualType T2 = Init->getType();
4474
4475 // If the initializer is the address of an overloaded function, try
4476 // to resolve the overloaded function. If all goes well, T2 is the
4477 // type of the resulting function.
4478 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4479 DeclAccessPair Found;
4480 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4481 Init, ToType, false, Found))
4482 T2 = Fn->getType();
4483 }
4484
4485 // Compute some basic properties of the types and the initializer.
4486 bool dummy1 = false;
4487 bool dummy2 = false;
4488 bool dummy3 = false;
4489 Sema::ReferenceCompareResult RefRelationship
4490 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4491 dummy2, dummy3);
4492
4493 if (RefRelationship >= Sema::Ref_Related)
4494 return TryReferenceInit(S, Init, ToType,
4495 /*FIXME:*/From->getLocStart(),
4496 SuppressUserConversions,
4497 /*AllowExplicit=*/false);
4498 }
4499
4500 // Otherwise, we bind the reference to a temporary created from the
4501 // initializer list.
4502 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4503 InOverloadResolution,
4504 AllowObjCWritebackConversion);
4505 if (Result.isFailure())
4506 return Result;
4507 assert(!Result.isEllipsis() &&
4508 "Sub-initialization cannot result in ellipsis conversion.");
4509
4510 // Can we even bind to a temporary?
4511 if (ToType->isRValueReferenceType() ||
4512 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4513 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4514 Result.UserDefined.After;
4515 SCS.ReferenceBinding = true;
4516 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4517 SCS.BindsToRvalue = true;
4518 SCS.BindsToFunctionLvalue = false;
4519 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4520 SCS.ObjCLifetimeConversionBinding = false;
4521 } else
4522 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4523 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004524 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004525 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004526
4527 // C++11 [over.ics.list]p6:
4528 // Otherwise, if the parameter type is not a class:
4529 if (!ToType->isRecordType()) {
4530 // - if the initializer list has one element, the implicit conversion
4531 // sequence is the one required to convert the element to the
4532 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004533 unsigned NumInits = From->getNumInits();
4534 if (NumInits == 1)
4535 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4536 SuppressUserConversions,
4537 InOverloadResolution,
4538 AllowObjCWritebackConversion);
4539 // - if the initializer list has no elements, the implicit conversion
4540 // sequence is the identity conversion.
4541 else if (NumInits == 0) {
4542 Result.setStandard();
4543 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004544 Result.Standard.setFromType(ToType);
4545 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004546 }
Sebastian Redl12edeb02012-02-28 23:36:38 +00004547 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004548 return Result;
4549 }
4550
4551 // C++11 [over.ics.list]p7:
4552 // In all cases other than those enumerated above, no conversion is possible
4553 return Result;
4554}
4555
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004556/// TryCopyInitialization - Try to copy-initialize a value of type
4557/// ToType from the expression From. Return the implicit conversion
4558/// sequence required to pass this argument, which may be a bad
4559/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004560/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004561/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004562static ImplicitConversionSequence
4563TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004564 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004565 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004566 bool AllowObjCWritebackConversion,
4567 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004568 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4569 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4570 InOverloadResolution,AllowObjCWritebackConversion);
4571
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004572 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004573 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004574 /*FIXME:*/From->getLocStart(),
4575 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004576 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004577
John McCall5c32be02010-08-24 20:38:10 +00004578 return TryImplicitConversion(S, From, ToType,
4579 SuppressUserConversions,
4580 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004581 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004582 /*CStyle=*/false,
4583 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004584}
4585
Anna Zaks1b068122011-07-28 19:46:48 +00004586static bool TryCopyInitialization(const CanQualType FromQTy,
4587 const CanQualType ToQTy,
4588 Sema &S,
4589 SourceLocation Loc,
4590 ExprValueKind FromVK) {
4591 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4592 ImplicitConversionSequence ICS =
4593 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4594
4595 return !ICS.isBad();
4596}
4597
Douglas Gregor436424c2008-11-18 23:14:02 +00004598/// TryObjectArgumentInitialization - Try to initialize the object
4599/// parameter of the given member function (@c Method) from the
4600/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004601static ImplicitConversionSequence
4602TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004603 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004604 CXXMethodDecl *Method,
4605 CXXRecordDecl *ActingContext) {
4606 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004607 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4608 // const volatile object.
4609 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4610 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004611 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004612
4613 // Set up the conversion sequence as a "bad" conversion, to allow us
4614 // to exit early.
4615 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004616
4617 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004618 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004619 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004620 FromType = PT->getPointeeType();
4621
Douglas Gregor02824322011-01-26 19:30:28 +00004622 // When we had a pointer, it's implicitly dereferenced, so we
4623 // better have an lvalue.
4624 assert(FromClassification.isLValue());
4625 }
4626
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004627 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004628
Douglas Gregor02824322011-01-26 19:30:28 +00004629 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004630 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004631 // parameter is
4632 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004633 // - "lvalue reference to cv X" for functions declared without a
4634 // ref-qualifier or with the & ref-qualifier
4635 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004636 // ref-qualifier
4637 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004638 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004639 // cv-qualification on the member function declaration.
4640 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004641 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004642 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004643 // (C++ [over.match.funcs]p5). We perform a simplified version of
4644 // reference binding here, that allows class rvalues to bind to
4645 // non-constant references.
4646
Douglas Gregor02824322011-01-26 19:30:28 +00004647 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004648 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004649 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004650 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004651 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004652 ICS.setBad(BadConversionSequence::bad_qualifiers,
4653 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004654 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004655 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004656
4657 // Check that we have either the same type or a derived type. It
4658 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004659 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004660 ImplicitConversionKind SecondKind;
4661 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4662 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004663 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004664 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004665 else {
John McCall65eb8792010-02-25 01:37:24 +00004666 ICS.setBad(BadConversionSequence::unrelated_class,
4667 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004668 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004669 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004670
Douglas Gregor02824322011-01-26 19:30:28 +00004671 // Check the ref-qualifier.
4672 switch (Method->getRefQualifier()) {
4673 case RQ_None:
4674 // Do nothing; we don't care about lvalueness or rvalueness.
4675 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004676
Douglas Gregor02824322011-01-26 19:30:28 +00004677 case RQ_LValue:
4678 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4679 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004680 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004681 ImplicitParamType);
4682 return ICS;
4683 }
4684 break;
4685
4686 case RQ_RValue:
4687 if (!FromClassification.isRValue()) {
4688 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004689 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004690 ImplicitParamType);
4691 return ICS;
4692 }
4693 break;
4694 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004695
Douglas Gregor436424c2008-11-18 23:14:02 +00004696 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004697 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004698 ICS.Standard.setAsIdentityConversion();
4699 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004700 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004701 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004702 ICS.Standard.ReferenceBinding = true;
4703 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004704 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004705 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004706 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4707 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4708 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004709 return ICS;
4710}
4711
4712/// PerformObjectArgumentInitialization - Perform initialization of
4713/// the implicit object parameter for the given Method with the given
4714/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004715ExprResult
4716Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004717 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004718 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004719 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004720 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004721 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004722 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004723
Douglas Gregor02824322011-01-26 19:30:28 +00004724 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004725 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004726 FromRecordType = PT->getPointeeType();
4727 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004728 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004729 } else {
4730 FromRecordType = From->getType();
4731 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004732 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004733 }
4734
John McCall6e9f8f62009-12-03 04:06:58 +00004735 // Note that we always use the true parent context when performing
4736 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004737 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004738 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4739 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004740 if (ICS.isBad()) {
4741 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4742 Qualifiers FromQs = FromRecordType.getQualifiers();
4743 Qualifiers ToQs = DestType.getQualifiers();
4744 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4745 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004746 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004747 diag::err_member_function_call_bad_cvr)
4748 << Method->getDeclName() << FromRecordType << (CVR - 1)
4749 << From->getSourceRange();
4750 Diag(Method->getLocation(), diag::note_previous_decl)
4751 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004752 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004753 }
4754 }
4755
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004756 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004757 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004758 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004759 }
Mike Stump11289f42009-09-09 15:08:12 +00004760
John Wiegley01296292011-04-08 18:41:53 +00004761 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4762 ExprResult FromRes =
4763 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4764 if (FromRes.isInvalid())
4765 return ExprError();
4766 From = FromRes.take();
4767 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004768
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004769 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004770 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004771 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004772 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004773}
4774
Douglas Gregor5fb53972009-01-14 15:45:31 +00004775/// TryContextuallyConvertToBool - Attempt to contextually convert the
4776/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004777static ImplicitConversionSequence
4778TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004779 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004780 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004781 // FIXME: Are these flags correct?
4782 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004783 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004784 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004785 /*CStyle=*/false,
4786 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004787}
4788
4789/// PerformContextuallyConvertToBool - Perform a contextual conversion
4790/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004791ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004792 if (checkPlaceholderForOverload(*this, From))
4793 return ExprError();
4794
John McCall5c32be02010-08-24 20:38:10 +00004795 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004796 if (!ICS.isBad())
4797 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004798
Fariborz Jahanian76197412009-11-18 18:26:29 +00004799 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004800 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004801 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004802 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004803 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004804}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004805
Richard Smithf8379a02012-01-18 23:55:52 +00004806/// Check that the specified conversion is permitted in a converted constant
4807/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4808/// is acceptable.
4809static bool CheckConvertedConstantConversions(Sema &S,
4810 StandardConversionSequence &SCS) {
4811 // Since we know that the target type is an integral or unscoped enumeration
4812 // type, most conversion kinds are impossible. All possible First and Third
4813 // conversions are fine.
4814 switch (SCS.Second) {
4815 case ICK_Identity:
4816 case ICK_Integral_Promotion:
4817 case ICK_Integral_Conversion:
4818 return true;
4819
4820 case ICK_Boolean_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004821 case ICK_Floating_Integral:
4822 case ICK_Complex_Real:
4823 return false;
4824
4825 case ICK_Lvalue_To_Rvalue:
4826 case ICK_Array_To_Pointer:
4827 case ICK_Function_To_Pointer:
4828 case ICK_NoReturn_Adjustment:
4829 case ICK_Qualification:
4830 case ICK_Compatible_Conversion:
4831 case ICK_Vector_Conversion:
4832 case ICK_Vector_Splat:
4833 case ICK_Derived_To_Base:
4834 case ICK_Pointer_Conversion:
4835 case ICK_Pointer_Member:
4836 case ICK_Block_Pointer_Conversion:
4837 case ICK_Writeback_Conversion:
4838 case ICK_Floating_Promotion:
4839 case ICK_Complex_Promotion:
4840 case ICK_Complex_Conversion:
4841 case ICK_Floating_Conversion:
4842 case ICK_TransparentUnionConversion:
4843 llvm_unreachable("unexpected second conversion kind");
4844
4845 case ICK_Num_Conversion_Kinds:
4846 break;
4847 }
4848
4849 llvm_unreachable("unknown conversion kind");
4850}
4851
4852/// CheckConvertedConstantExpression - Check that the expression From is a
4853/// converted constant expression of type T, perform the conversion and produce
4854/// the converted expression, per C++11 [expr.const]p3.
4855ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4856 llvm::APSInt &Value,
4857 CCEKind CCE) {
4858 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4859 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4860
4861 if (checkPlaceholderForOverload(*this, From))
4862 return ExprError();
4863
4864 // C++11 [expr.const]p3 with proposed wording fixes:
4865 // A converted constant expression of type T is a core constant expression,
4866 // implicitly converted to a prvalue of type T, where the converted
4867 // expression is a literal constant expression and the implicit conversion
4868 // sequence contains only user-defined conversions, lvalue-to-rvalue
4869 // conversions, integral promotions, and integral conversions other than
4870 // narrowing conversions.
4871 ImplicitConversionSequence ICS =
4872 TryImplicitConversion(From, T,
4873 /*SuppressUserConversions=*/false,
4874 /*AllowExplicit=*/false,
4875 /*InOverloadResolution=*/false,
4876 /*CStyle=*/false,
4877 /*AllowObjcWritebackConversion=*/false);
4878 StandardConversionSequence *SCS = 0;
4879 switch (ICS.getKind()) {
4880 case ImplicitConversionSequence::StandardConversion:
4881 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004882 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004883 diag::err_typecheck_converted_constant_expression_disallowed)
4884 << From->getType() << From->getSourceRange() << T;
4885 SCS = &ICS.Standard;
4886 break;
4887 case ImplicitConversionSequence::UserDefinedConversion:
4888 // We are converting from class type to an integral or enumeration type, so
4889 // the Before sequence must be trivial.
4890 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004891 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004892 diag::err_typecheck_converted_constant_expression_disallowed)
4893 << From->getType() << From->getSourceRange() << T;
4894 SCS = &ICS.UserDefined.After;
4895 break;
4896 case ImplicitConversionSequence::AmbiguousConversion:
4897 case ImplicitConversionSequence::BadConversion:
4898 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004899 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004900 diag::err_typecheck_converted_constant_expression)
4901 << From->getType() << From->getSourceRange() << T;
4902 return ExprError();
4903
4904 case ImplicitConversionSequence::EllipsisConversion:
4905 llvm_unreachable("ellipsis conversion in converted constant expression");
4906 }
4907
4908 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4909 if (Result.isInvalid())
4910 return Result;
4911
4912 // Check for a narrowing implicit conversion.
4913 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00004914 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00004915 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4916 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00004917 case NK_Variable_Narrowing:
4918 // Implicit conversion to a narrower type, and the value is not a constant
4919 // expression. We'll diagnose this in a moment.
4920 case NK_Not_Narrowing:
4921 break;
4922
4923 case NK_Constant_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004924 Diag(From->getLocStart(),
4925 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4926 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004927 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00004928 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00004929 break;
4930
4931 case NK_Type_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004932 Diag(From->getLocStart(),
4933 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4934 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004935 << CCE << /*Constant*/0 << From->getType() << T;
4936 break;
4937 }
4938
4939 // Check the expression is a constant expression.
4940 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4941 Expr::EvalResult Eval;
4942 Eval.Diag = &Notes;
4943
4944 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4945 // The expression can't be folded, so we can't keep it at this position in
4946 // the AST.
4947 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00004948 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00004949 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00004950
4951 if (Notes.empty()) {
4952 // It's a constant expression.
4953 return Result;
4954 }
Richard Smithf8379a02012-01-18 23:55:52 +00004955 }
4956
4957 // It's not a constant expression. Produce an appropriate diagnostic.
4958 if (Notes.size() == 1 &&
4959 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4960 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4961 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004962 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00004963 << CCE << From->getSourceRange();
4964 for (unsigned I = 0; I < Notes.size(); ++I)
4965 Diag(Notes[I].first, Notes[I].second);
4966 }
Richard Smith911e1422012-01-30 22:27:01 +00004967 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00004968}
4969
John McCallfec112d2011-09-09 06:11:02 +00004970/// dropPointerConversions - If the given standard conversion sequence
4971/// involves any pointer conversions, remove them. This may change
4972/// the result type of the conversion sequence.
4973static void dropPointerConversion(StandardConversionSequence &SCS) {
4974 if (SCS.Second == ICK_Pointer_Conversion) {
4975 SCS.Second = ICK_Identity;
4976 SCS.Third = ICK_Identity;
4977 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4978 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004979}
John McCall5c32be02010-08-24 20:38:10 +00004980
John McCallfec112d2011-09-09 06:11:02 +00004981/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4982/// convert the expression From to an Objective-C pointer type.
4983static ImplicitConversionSequence
4984TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4985 // Do an implicit conversion to 'id'.
4986 QualType Ty = S.Context.getObjCIdType();
4987 ImplicitConversionSequence ICS
4988 = TryImplicitConversion(S, From, Ty,
4989 // FIXME: Are these flags correct?
4990 /*SuppressUserConversions=*/false,
4991 /*AllowExplicit=*/true,
4992 /*InOverloadResolution=*/false,
4993 /*CStyle=*/false,
4994 /*AllowObjCWritebackConversion=*/false);
4995
4996 // Strip off any final conversions to 'id'.
4997 switch (ICS.getKind()) {
4998 case ImplicitConversionSequence::BadConversion:
4999 case ImplicitConversionSequence::AmbiguousConversion:
5000 case ImplicitConversionSequence::EllipsisConversion:
5001 break;
5002
5003 case ImplicitConversionSequence::UserDefinedConversion:
5004 dropPointerConversion(ICS.UserDefined.After);
5005 break;
5006
5007 case ImplicitConversionSequence::StandardConversion:
5008 dropPointerConversion(ICS.Standard);
5009 break;
5010 }
5011
5012 return ICS;
5013}
5014
5015/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5016/// conversion of the expression From to an Objective-C pointer type.
5017ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005018 if (checkPlaceholderForOverload(*this, From))
5019 return ExprError();
5020
John McCall8b07ec22010-05-15 11:32:37 +00005021 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005022 ImplicitConversionSequence ICS =
5023 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005024 if (!ICS.isBad())
5025 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005026 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005027}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005028
Richard Smith8dd34252012-02-04 07:07:42 +00005029/// Determine whether the provided type is an integral type, or an enumeration
5030/// type of a permitted flavor.
5031static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5032 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5033 : T->isIntegralOrUnscopedEnumerationType();
5034}
5035
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005036/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005037/// enumeration type.
5038///
5039/// This routine will attempt to convert an expression of class type to an
5040/// integral or enumeration type, if that class type only has a single
5041/// conversion to an integral or enumeration type.
5042///
Douglas Gregor4799d032010-06-30 00:20:43 +00005043/// \param Loc The source location of the construct that requires the
5044/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005045///
James Dennett18348b62012-06-22 08:52:37 +00005046/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005047///
James Dennett18348b62012-06-22 08:52:37 +00005048/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor4799d032010-06-30 00:20:43 +00005049///
Richard Smith8dd34252012-02-04 07:07:42 +00005050/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5051/// enumerations should be considered.
5052///
Douglas Gregor4799d032010-06-30 00:20:43 +00005053/// \returns The expression, converted to an integral or enumeration type if
5054/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005055ExprResult
John McCallb268a282010-08-23 23:25:46 +00005056Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregore2b37442012-05-04 22:38:52 +00005057 ICEConvertDiagnoser &Diagnoser,
Richard Smith8dd34252012-02-04 07:07:42 +00005058 bool AllowScopedEnumerations) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005059 // We can't perform any more checking for type-dependent expressions.
5060 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00005061 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005062
Eli Friedman1da70392012-01-26 00:26:18 +00005063 // Process placeholders immediately.
5064 if (From->hasPlaceholderType()) {
5065 ExprResult result = CheckPlaceholderExpr(From);
5066 if (result.isInvalid()) return result;
5067 From = result.take();
5068 }
5069
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005070 // If the expression already has integral or enumeration type, we're golden.
5071 QualType T = From->getType();
Richard Smith8dd34252012-02-04 07:07:42 +00005072 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedman1da70392012-01-26 00:26:18 +00005073 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005074
5075 // FIXME: Check for missing '()' if T is a function type?
5076
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005077 // 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 +00005078 // expression of integral or enumeration type.
5079 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005080 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005081 if (!Diagnoser.Suppress)
5082 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00005083 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005084 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005085
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005086 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005087 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregore2b37442012-05-04 22:38:52 +00005088 ICEConvertDiagnoser &Diagnoser;
5089 Expr *From;
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005090
Douglas Gregore2b37442012-05-04 22:38:52 +00005091 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5092 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005093
5094 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005095 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005096 }
Douglas Gregore2b37442012-05-04 22:38:52 +00005097 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005098
5099 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCallb268a282010-08-23 23:25:46 +00005100 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005101
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005102 // Look for a conversion to an integral or enumeration type.
5103 UnresolvedSet<4> ViableConversions;
5104 UnresolvedSet<4> ExplicitConversions;
5105 const UnresolvedSetImpl *Conversions
5106 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005107
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005108 bool HadMultipleCandidates = (Conversions->size() > 1);
5109
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005110 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005111 E = Conversions->end();
5112 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005113 ++I) {
5114 if (CXXConversionDecl *Conversion
Richard Smith8dd34252012-02-04 07:07:42 +00005115 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5116 if (isIntegralOrEnumerationType(
5117 Conversion->getConversionType().getNonReferenceType(),
5118 AllowScopedEnumerations)) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005119 if (Conversion->isExplicit())
5120 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5121 else
5122 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5123 }
Richard Smith8dd34252012-02-04 07:07:42 +00005124 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005125 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005126
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005127 switch (ViableConversions.size()) {
5128 case 0:
Douglas Gregore2b37442012-05-04 22:38:52 +00005129 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005130 DeclAccessPair Found = ExplicitConversions[0];
5131 CXXConversionDecl *Conversion
5132 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005133
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005134 // The user probably meant to invoke the given explicit
5135 // conversion; use it.
5136 QualType ConvTy
5137 = Conversion->getConversionType().getNonReferenceType();
5138 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00005139 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005140
Douglas Gregore2b37442012-05-04 22:38:52 +00005141 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005142 << FixItHint::CreateInsertion(From->getLocStart(),
5143 "static_cast<" + TypeStr + ">(")
5144 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5145 ")");
Douglas Gregore2b37442012-05-04 22:38:52 +00005146 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005147
5148 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005149 // explicit conversion function.
5150 if (isSFINAEContext())
5151 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005152
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005153 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005154 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5155 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005156 if (Result.isInvalid())
5157 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005158 // Record usage of conversion in an implicit cast.
5159 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5160 CK_UserDefinedConversion,
5161 Result.get(), 0,
5162 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005163 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005164
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005165 // We'll complain below about a non-integral condition type.
5166 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005167
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005168 case 1: {
5169 // Apply this conversion.
5170 DeclAccessPair Found = ViableConversions[0];
5171 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005172
Douglas Gregor4799d032010-06-30 00:20:43 +00005173 CXXConversionDecl *Conversion
5174 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5175 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005176 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregore2b37442012-05-04 22:38:52 +00005177 if (!Diagnoser.SuppressConversion) {
Douglas Gregor4799d032010-06-30 00:20:43 +00005178 if (isSFINAEContext())
5179 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005180
Douglas Gregore2b37442012-05-04 22:38:52 +00005181 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5182 << From->getSourceRange();
Douglas Gregor4799d032010-06-30 00:20:43 +00005183 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005184
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005185 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5186 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005187 if (Result.isInvalid())
5188 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005189 // Record usage of conversion in an implicit cast.
5190 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5191 CK_UserDefinedConversion,
5192 Result.get(), 0,
5193 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005194 break;
5195 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005196
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005197 default:
Douglas Gregore2b37442012-05-04 22:38:52 +00005198 if (Diagnoser.Suppress)
5199 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005200
Douglas Gregore2b37442012-05-04 22:38:52 +00005201 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005202 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5203 CXXConversionDecl *Conv
5204 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5205 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregore2b37442012-05-04 22:38:52 +00005206 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005207 }
John McCallb268a282010-08-23 23:25:46 +00005208 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005209 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005210
Richard Smithf4c51d92012-02-04 09:53:13 +00005211 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregore2b37442012-05-04 22:38:52 +00005212 !Diagnoser.Suppress) {
5213 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5214 << From->getSourceRange();
5215 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005216
Eli Friedman1da70392012-01-26 00:26:18 +00005217 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005218}
5219
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005220/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005221/// candidate functions, using the given function call arguments. If
5222/// @p SuppressUserConversions, then don't allow user-defined
5223/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005224///
James Dennett2a4d13c2012-06-15 07:13:21 +00005225/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005226/// based on an incomplete set of function arguments. This feature is used by
5227/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005228void
5229Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005230 DeclAccessPair FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005231 llvm::ArrayRef<Expr *> Args,
Douglas Gregor2fe98832008-11-03 19:09:14 +00005232 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005233 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005234 bool PartialOverloading,
5235 bool AllowExplicit) {
Mike Stump11289f42009-09-09 15:08:12 +00005236 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005237 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005238 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005239 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005240 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005241
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005242 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005243 if (!isa<CXXConstructorDecl>(Method)) {
5244 // If we get here, it's because we're calling a member function
5245 // that is named without a member access expression (e.g.,
5246 // "this->f") that was either written explicitly or created
5247 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005248 // function, e.g., X::f(). We use an empty type for the implied
5249 // object argument (C++ [over.call.func]p3), and the acting context
5250 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005251 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005252 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005253 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005254 return;
5255 }
5256 // We treat a constructor like a non-member function, since its object
5257 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005258 }
5259
Douglas Gregorff7028a2009-11-13 23:59:09 +00005260 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005261 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005262
Douglas Gregor27381f32009-11-23 12:27:39 +00005263 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005264 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005265
Douglas Gregorffe14e32009-11-14 01:20:54 +00005266 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5267 // C++ [class.copy]p3:
5268 // A member function template is never instantiated to perform the copy
5269 // of a class object to an object of its class type.
5270 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005271 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005272 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005273 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5274 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005275 return;
5276 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005277
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005278 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005279 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005280 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005281 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005282 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005283 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005284 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005285 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005286
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005287 unsigned NumArgsInProto = Proto->getNumArgs();
5288
5289 // (C++ 13.3.2p2): A candidate function having fewer than m
5290 // parameters is viable only if it has an ellipsis in its parameter
5291 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005292 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005293 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005294 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005295 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005296 return;
5297 }
5298
5299 // (C++ 13.3.2p2): A candidate function having more than m parameters
5300 // is viable only if the (m+1)st parameter has a default argument
5301 // (8.3.6). For the purposes of overload resolution, the
5302 // parameter list is truncated on the right, so that there are
5303 // exactly m parameters.
5304 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005305 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005306 // Not enough arguments.
5307 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005308 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005309 return;
5310 }
5311
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005312 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005313 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005314 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5315 if (CheckCUDATarget(Caller, Function)) {
5316 Candidate.Viable = false;
5317 Candidate.FailureKind = ovl_fail_bad_target;
5318 return;
5319 }
5320
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005321 // Determine the implicit conversion sequences for each of the
5322 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005323 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005324 if (ArgIdx < NumArgsInProto) {
5325 // (C++ 13.3.2p3): for F to be a viable function, there shall
5326 // exist for each argument an implicit conversion sequence
5327 // (13.3.3.1) that converts that argument to the corresponding
5328 // parameter of F.
5329 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005330 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005331 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005332 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005333 /*InOverloadResolution=*/true,
5334 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005335 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005336 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005337 if (Candidate.Conversions[ArgIdx].isBad()) {
5338 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005339 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00005340 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00005341 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005342 } else {
5343 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5344 // argument for which there is no corresponding parameter is
5345 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005346 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005347 }
5348 }
5349}
5350
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005351/// \brief Add all of the function declarations in the given function set to
5352/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005353void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005354 llvm::ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005355 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005356 bool SuppressUserConversions,
5357 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005358 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005359 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5360 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005361 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005362 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005363 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005364 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005365 Args.slice(1), CandidateSet,
5366 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005367 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005368 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005369 SuppressUserConversions);
5370 } else {
John McCalla0296f72010-03-19 07:35:19 +00005371 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005372 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5373 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005374 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005375 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005376 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005377 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005378 Args[0]->Classify(Context), Args.slice(1),
5379 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005380 else
John McCalla0296f72010-03-19 07:35:19 +00005381 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005382 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005383 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005384 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005385 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005386}
5387
John McCallf0f1cf02009-11-17 07:50:12 +00005388/// AddMethodCandidate - Adds a named decl (which is some kind of
5389/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005390void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005391 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005392 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00005393 Expr **Args, unsigned NumArgs,
5394 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005395 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005396 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005397 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005398
5399 if (isa<UsingShadowDecl>(Decl))
5400 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005401
John McCallf0f1cf02009-11-17 07:50:12 +00005402 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5403 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5404 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005405 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5406 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005407 ObjectType, ObjectClassification,
5408 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005409 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005410 } else {
John McCalla0296f72010-03-19 07:35:19 +00005411 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005412 ObjectType, ObjectClassification,
5413 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorf1e46692010-04-16 17:33:27 +00005414 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005415 }
5416}
5417
Douglas Gregor436424c2008-11-18 23:14:02 +00005418/// AddMethodCandidate - Adds the given C++ member function to the set
5419/// of candidate functions, using the given function call arguments
5420/// and the object argument (@c Object). For example, in a call
5421/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5422/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5423/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005424/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005425void
John McCalla0296f72010-03-19 07:35:19 +00005426Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005427 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005428 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005429 llvm::ArrayRef<Expr *> Args,
Douglas Gregor436424c2008-11-18 23:14:02 +00005430 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005431 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00005432 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005433 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005434 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005435 assert(!isa<CXXConstructorDecl>(Method) &&
5436 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005437
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005438 if (!CandidateSet.isNewCandidate(Method))
5439 return;
5440
Douglas Gregor27381f32009-11-23 12:27:39 +00005441 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005442 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005443
Douglas Gregor436424c2008-11-18 23:14:02 +00005444 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005445 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005446 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005447 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005448 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005449 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005450 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005451
5452 unsigned NumArgsInProto = Proto->getNumArgs();
5453
5454 // (C++ 13.3.2p2): A candidate function having fewer than m
5455 // parameters is viable only if it has an ellipsis in its parameter
5456 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005457 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005458 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005459 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005460 return;
5461 }
5462
5463 // (C++ 13.3.2p2): A candidate function having more than m parameters
5464 // is viable only if the (m+1)st parameter has a default argument
5465 // (8.3.6). For the purposes of overload resolution, the
5466 // parameter list is truncated on the right, so that there are
5467 // exactly m parameters.
5468 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005469 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005470 // Not enough arguments.
5471 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005472 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005473 return;
5474 }
5475
5476 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005477
John McCall6e9f8f62009-12-03 04:06:58 +00005478 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005479 // The implicit object argument is ignored.
5480 Candidate.IgnoreObjectArgument = true;
5481 else {
5482 // Determine the implicit conversion sequence for the object
5483 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005484 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005485 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5486 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005487 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005488 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005489 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005490 return;
5491 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005492 }
5493
5494 // Determine the implicit conversion sequences for each of the
5495 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005496 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005497 if (ArgIdx < NumArgsInProto) {
5498 // (C++ 13.3.2p3): for F to be a viable function, there shall
5499 // exist for each argument an implicit conversion sequence
5500 // (13.3.3.1) that converts that argument to the corresponding
5501 // parameter of F.
5502 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005503 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005504 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005505 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005506 /*InOverloadResolution=*/true,
5507 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005508 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005509 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005510 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005511 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005512 break;
5513 }
5514 } else {
5515 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5516 // argument for which there is no corresponding parameter is
5517 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005518 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005519 }
5520 }
5521}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005522
Douglas Gregor97628d62009-08-21 00:16:32 +00005523/// \brief Add a C++ member function template as a candidate to the candidate
5524/// set, using template argument deduction to produce an appropriate member
5525/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005526void
Douglas Gregor97628d62009-08-21 00:16:32 +00005527Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005528 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005529 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005530 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005531 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005532 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005533 llvm::ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005534 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005535 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005536 if (!CandidateSet.isNewCandidate(MethodTmpl))
5537 return;
5538
Douglas Gregor97628d62009-08-21 00:16:32 +00005539 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005540 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005541 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005542 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005543 // candidate functions in the usual way.113) A given name can refer to one
5544 // or more function templates and also to a set of overloaded non-template
5545 // functions. In such a case, the candidate functions generated from each
5546 // function template are combined with the set of non-template candidate
5547 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005548 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005549 FunctionDecl *Specialization = 0;
5550 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005551 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5552 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005553 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005554 Candidate.FoundDecl = FoundDecl;
5555 Candidate.Function = MethodTmpl->getTemplatedDecl();
5556 Candidate.Viable = false;
5557 Candidate.FailureKind = ovl_fail_bad_deduction;
5558 Candidate.IsSurrogate = false;
5559 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005560 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005561 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005562 Info);
5563 return;
5564 }
Mike Stump11289f42009-09-09 15:08:12 +00005565
Douglas Gregor97628d62009-08-21 00:16:32 +00005566 // Add the function template specialization produced by template argument
5567 // deduction as a candidate.
5568 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005569 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005570 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005571 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005572 ActingContext, ObjectType, ObjectClassification, Args,
5573 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005574}
5575
Douglas Gregor05155d82009-08-21 23:19:43 +00005576/// \brief Add a C++ function template specialization as a candidate
5577/// in the candidate set, using template argument deduction to produce
5578/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005579void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005580Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005581 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005582 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005583 llvm::ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005584 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005585 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005586 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5587 return;
5588
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005589 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005590 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005591 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005592 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005593 // candidate functions in the usual way.113) A given name can refer to one
5594 // or more function templates and also to a set of overloaded non-template
5595 // functions. In such a case, the candidate functions generated from each
5596 // function template are combined with the set of non-template candidate
5597 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00005598 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005599 FunctionDecl *Specialization = 0;
5600 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005601 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5602 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005603 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005604 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005605 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5606 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005607 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005608 Candidate.IsSurrogate = false;
5609 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005610 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005611 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005612 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005613 return;
5614 }
Mike Stump11289f42009-09-09 15:08:12 +00005615
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005616 // Add the function template specialization produced by template argument
5617 // deduction as a candidate.
5618 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005619 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005620 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005621}
Mike Stump11289f42009-09-09 15:08:12 +00005622
Douglas Gregora1f013e2008-11-07 22:36:19 +00005623/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005624/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005625/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005626/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005627/// (which may or may not be the same type as the type that the
5628/// conversion function produces).
5629void
5630Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005631 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005632 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005633 Expr *From, QualType ToType,
5634 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005635 assert(!Conversion->getDescribedFunctionTemplate() &&
5636 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005637 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005638 if (!CandidateSet.isNewCandidate(Conversion))
5639 return;
5640
Douglas Gregor27381f32009-11-23 12:27:39 +00005641 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005642 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005643
Douglas Gregora1f013e2008-11-07 22:36:19 +00005644 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005645 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005646 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005647 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005648 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005649 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005650 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005651 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005652 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005653 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005654 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005655
Douglas Gregor6affc782010-08-19 15:37:02 +00005656 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005657 // For conversion functions, the function is considered to be a member of
5658 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005659 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005660 //
5661 // Determine the implicit conversion sequence for the implicit
5662 // object parameter.
5663 QualType ImplicitParamType = From->getType();
5664 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5665 ImplicitParamType = FromPtrType->getPointeeType();
5666 CXXRecordDecl *ConversionContext
5667 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005668
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005669 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005670 = TryObjectArgumentInitialization(*this, From->getType(),
5671 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005672 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005673
John McCall0d1da222010-01-12 00:44:57 +00005674 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005675 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005676 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005677 return;
5678 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005679
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005680 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005681 // derived to base as such conversions are given Conversion Rank. They only
5682 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5683 QualType FromCanon
5684 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5685 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5686 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5687 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005688 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005689 return;
5690 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005691
Douglas Gregora1f013e2008-11-07 22:36:19 +00005692 // To determine what the conversion from the result of calling the
5693 // conversion function to the type we're eventually trying to
5694 // convert to (ToType), we need to synthesize a call to the
5695 // conversion function and attempt copy initialization from it. This
5696 // makes sure that we get the right semantics with respect to
5697 // lvalues/rvalues and the type. Fortunately, we can allocate this
5698 // call on the stack and we don't need its arguments to be
5699 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00005700 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005701 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005702 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5703 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005704 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005705 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005706
Richard Smith48d24642011-07-13 22:53:21 +00005707 QualType ConversionType = Conversion->getConversionType();
5708 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005709 Candidate.Viable = false;
5710 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5711 return;
5712 }
5713
Richard Smith48d24642011-07-13 22:53:21 +00005714 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005715
Mike Stump11289f42009-09-09 15:08:12 +00005716 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005717 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5718 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005719 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Benjamin Kramerc215e762012-08-24 11:54:20 +00005720 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005721 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005722 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005723 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005724 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005725 /*InOverloadResolution=*/false,
5726 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005727
John McCall0d1da222010-01-12 00:44:57 +00005728 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005729 case ImplicitConversionSequence::StandardConversion:
5730 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005731
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005732 // C++ [over.ics.user]p3:
5733 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005734 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005735 // shall have exact match rank.
5736 if (Conversion->getPrimaryTemplate() &&
5737 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5738 Candidate.Viable = false;
5739 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5740 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005741
Douglas Gregorcba72b12011-01-21 05:18:22 +00005742 // C++0x [dcl.init.ref]p5:
5743 // In the second case, if the reference is an rvalue reference and
5744 // the second standard conversion sequence of the user-defined
5745 // conversion sequence includes an lvalue-to-rvalue conversion, the
5746 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005747 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005748 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5749 Candidate.Viable = false;
5750 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5751 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005752 break;
5753
5754 case ImplicitConversionSequence::BadConversion:
5755 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005756 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005757 break;
5758
5759 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005760 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005761 "Can only end up with a standard conversion sequence or failure");
5762 }
5763}
5764
Douglas Gregor05155d82009-08-21 23:19:43 +00005765/// \brief Adds a conversion function template specialization
5766/// candidate to the overload set, using template argument deduction
5767/// to deduce the template arguments of the conversion function
5768/// template from the type that we are converting to (C++
5769/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005770void
Douglas Gregor05155d82009-08-21 23:19:43 +00005771Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005772 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005773 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005774 Expr *From, QualType ToType,
5775 OverloadCandidateSet &CandidateSet) {
5776 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5777 "Only conversion function templates permitted here");
5778
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005779 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5780 return;
5781
John McCallbc077cf2010-02-08 23:07:23 +00005782 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005783 CXXConversionDecl *Specialization = 0;
5784 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005785 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005786 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005787 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005788 Candidate.FoundDecl = FoundDecl;
5789 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5790 Candidate.Viable = false;
5791 Candidate.FailureKind = ovl_fail_bad_deduction;
5792 Candidate.IsSurrogate = false;
5793 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005794 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005795 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005796 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005797 return;
5798 }
Mike Stump11289f42009-09-09 15:08:12 +00005799
Douglas Gregor05155d82009-08-21 23:19:43 +00005800 // Add the conversion function template specialization produced by
5801 // template argument deduction as a candidate.
5802 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005803 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005804 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005805}
5806
Douglas Gregorab7897a2008-11-19 22:57:39 +00005807/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5808/// converts the given @c Object to a function pointer via the
5809/// conversion function @c Conversion, and then attempts to call it
5810/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5811/// the type of function that we'll eventually be calling.
5812void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005813 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005814 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005815 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005816 Expr *Object,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005817 llvm::ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005818 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005819 if (!CandidateSet.isNewCandidate(Conversion))
5820 return;
5821
Douglas Gregor27381f32009-11-23 12:27:39 +00005822 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005823 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005824
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005825 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005826 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005827 Candidate.Function = 0;
5828 Candidate.Surrogate = Conversion;
5829 Candidate.Viable = true;
5830 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005831 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005832 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005833
5834 // Determine the implicit conversion sequence for the implicit
5835 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005836 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005837 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005838 Object->Classify(Context),
5839 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005840 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005841 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005842 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005843 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005844 return;
5845 }
5846
5847 // The first conversion is actually a user-defined conversion whose
5848 // first conversion is ObjectInit's standard conversion (which is
5849 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005850 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005851 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005852 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005853 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005854 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005855 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005856 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005857 = Candidate.Conversions[0].UserDefined.Before;
5858 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5859
Mike Stump11289f42009-09-09 15:08:12 +00005860 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005861 unsigned NumArgsInProto = Proto->getNumArgs();
5862
5863 // (C++ 13.3.2p2): A candidate function having fewer than m
5864 // parameters is viable only if it has an ellipsis in its parameter
5865 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005866 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005867 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005868 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005869 return;
5870 }
5871
5872 // Function types don't have any default arguments, so just check if
5873 // we have enough arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005874 if (Args.size() < NumArgsInProto) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005875 // Not enough arguments.
5876 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005877 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005878 return;
5879 }
5880
5881 // Determine the implicit conversion sequences for each of the
5882 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005883 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005884 if (ArgIdx < NumArgsInProto) {
5885 // (C++ 13.3.2p3): for F to be a viable function, there shall
5886 // exist for each argument an implicit conversion sequence
5887 // (13.3.3.1) that converts that argument to the corresponding
5888 // parameter of F.
5889 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005890 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005891 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005892 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005893 /*InOverloadResolution=*/false,
5894 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005895 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005896 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005897 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005898 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005899 break;
5900 }
5901 } else {
5902 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5903 // argument for which there is no corresponding parameter is
5904 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005905 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005906 }
5907 }
5908}
5909
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005910/// \brief Add overload candidates for overloaded operators that are
5911/// member functions.
5912///
5913/// Add the overloaded operator candidates that are member functions
5914/// for the operator Op that was used in an operator expression such
5915/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5916/// CandidateSet will store the added overload candidates. (C++
5917/// [over.match.oper]).
5918void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5919 SourceLocation OpLoc,
5920 Expr **Args, unsigned NumArgs,
5921 OverloadCandidateSet& CandidateSet,
5922 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005923 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5924
5925 // C++ [over.match.oper]p3:
5926 // For a unary operator @ with an operand of a type whose
5927 // cv-unqualified version is T1, and for a binary operator @ with
5928 // a left operand of a type whose cv-unqualified version is T1 and
5929 // a right operand of a type whose cv-unqualified version is T2,
5930 // three sets of candidate functions, designated member
5931 // candidates, non-member candidates and built-in candidates, are
5932 // constructed as follows:
5933 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005934
5935 // -- If T1 is a class type, the set of member candidates is the
5936 // result of the qualified lookup of T1::operator@
5937 // (13.3.1.1.1); otherwise, the set of member candidates is
5938 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005939 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005940 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005941 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005942 return;
Mike Stump11289f42009-09-09 15:08:12 +00005943
John McCall27b18f82009-11-17 02:14:36 +00005944 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5945 LookupQualifiedName(Operators, T1Rec->getDecl());
5946 Operators.suppressDiagnostics();
5947
Mike Stump11289f42009-09-09 15:08:12 +00005948 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005949 OperEnd = Operators.end();
5950 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005951 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005952 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005953 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005954 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005955 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005956 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005957}
5958
Douglas Gregora11693b2008-11-12 17:17:38 +00005959/// AddBuiltinCandidate - Add a candidate for a built-in
5960/// operator. ResultTy and ParamTys are the result and parameter types
5961/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005962/// arguments being passed to the candidate. IsAssignmentOperator
5963/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005964/// operator. NumContextualBoolArguments is the number of arguments
5965/// (at the beginning of the argument list) that will be contextually
5966/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005967void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005968 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005969 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005970 bool IsAssignmentOperator,
5971 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005972 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005973 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005974
Douglas Gregora11693b2008-11-12 17:17:38 +00005975 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005976 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005977 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005978 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005979 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005980 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005981 Candidate.BuiltinTypes.ResultTy = ResultTy;
5982 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5983 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5984
5985 // Determine the implicit conversion sequences for each of the
5986 // arguments.
5987 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005988 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005989 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005990 // C++ [over.match.oper]p4:
5991 // For the built-in assignment operators, conversions of the
5992 // left operand are restricted as follows:
5993 // -- no temporaries are introduced to hold the left operand, and
5994 // -- no user-defined conversions are applied to the left
5995 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005996 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005997 //
5998 // We block these conversions by turning off user-defined
5999 // conversions, since that is the only way that initialization of
6000 // a reference to a non-class type can occur from something that
6001 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006002 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006003 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006004 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006005 Candidate.Conversions[ArgIdx]
6006 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006007 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006008 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006009 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006010 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006011 /*InOverloadResolution=*/false,
6012 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006013 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006014 }
John McCall0d1da222010-01-12 00:44:57 +00006015 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006016 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006017 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006018 break;
6019 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006020 }
6021}
6022
6023/// BuiltinCandidateTypeSet - A set of types that will be used for the
6024/// candidate operator functions for built-in operators (C++
6025/// [over.built]). The types are separated into pointer types and
6026/// enumeration types.
6027class BuiltinCandidateTypeSet {
6028 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006029 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006030
6031 /// PointerTypes - The set of pointer types that will be used in the
6032 /// built-in candidates.
6033 TypeSet PointerTypes;
6034
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006035 /// MemberPointerTypes - The set of member pointer types that will be
6036 /// used in the built-in candidates.
6037 TypeSet MemberPointerTypes;
6038
Douglas Gregora11693b2008-11-12 17:17:38 +00006039 /// EnumerationTypes - The set of enumeration types that will be
6040 /// used in the built-in candidates.
6041 TypeSet EnumerationTypes;
6042
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006043 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006044 /// candidates.
6045 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006046
6047 /// \brief A flag indicating non-record types are viable candidates
6048 bool HasNonRecordTypes;
6049
6050 /// \brief A flag indicating whether either arithmetic or enumeration types
6051 /// were present in the candidate set.
6052 bool HasArithmeticOrEnumeralTypes;
6053
Douglas Gregor80af3132011-05-21 23:15:46 +00006054 /// \brief A flag indicating whether the nullptr type was present in the
6055 /// candidate set.
6056 bool HasNullPtrType;
6057
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006058 /// Sema - The semantic analysis instance where we are building the
6059 /// candidate type set.
6060 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006061
Douglas Gregora11693b2008-11-12 17:17:38 +00006062 /// Context - The AST context in which we will build the type sets.
6063 ASTContext &Context;
6064
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006065 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6066 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006067 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006068
6069public:
6070 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006071 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006072
Mike Stump11289f42009-09-09 15:08:12 +00006073 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006074 : HasNonRecordTypes(false),
6075 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006076 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006077 SemaRef(SemaRef),
6078 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006079
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006080 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006081 SourceLocation Loc,
6082 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006083 bool AllowExplicitConversions,
6084 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006085
6086 /// pointer_begin - First pointer type found;
6087 iterator pointer_begin() { return PointerTypes.begin(); }
6088
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006089 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006090 iterator pointer_end() { return PointerTypes.end(); }
6091
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006092 /// member_pointer_begin - First member pointer type found;
6093 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6094
6095 /// member_pointer_end - Past the last member pointer type found;
6096 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6097
Douglas Gregora11693b2008-11-12 17:17:38 +00006098 /// enumeration_begin - First enumeration type found;
6099 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6100
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006101 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006102 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006103
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006104 iterator vector_begin() { return VectorTypes.begin(); }
6105 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006106
6107 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6108 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006109 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006110};
6111
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006112/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006113/// the set of pointer types along with any more-qualified variants of
6114/// that type. For example, if @p Ty is "int const *", this routine
6115/// will add "int const *", "int const volatile *", "int const
6116/// restrict *", and "int const volatile restrict *" to the set of
6117/// pointer types. Returns true if the add of @p Ty itself succeeded,
6118/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006119///
6120/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006121bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006122BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6123 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006124
Douglas Gregora11693b2008-11-12 17:17:38 +00006125 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006126 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006127 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006128
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006129 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006130 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006131 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006132 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006133 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6134 PointeeTy = PTy->getPointeeType();
6135 buildObjCPtr = true;
6136 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006137 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006138 }
6139
Sebastian Redl4990a632009-11-18 20:39:26 +00006140 // Don't add qualified variants of arrays. For one, they're not allowed
6141 // (the qualifier would sink to the element type), and for another, the
6142 // only overload situation where it matters is subscript or pointer +- int,
6143 // and those shouldn't have qualifier variants anyway.
6144 if (PointeeTy->isArrayType())
6145 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006146
John McCall8ccfcb52009-09-24 19:53:00 +00006147 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006148 bool hasVolatile = VisibleQuals.hasVolatile();
6149 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006150
John McCall8ccfcb52009-09-24 19:53:00 +00006151 // Iterate through all strict supersets of BaseCVR.
6152 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6153 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006154 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006155 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006156
6157 // Skip over restrict if no restrict found anywhere in the types, or if
6158 // the type cannot be restrict-qualified.
6159 if ((CVR & Qualifiers::Restrict) &&
6160 (!hasRestrict ||
6161 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6162 continue;
6163
6164 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006165 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006166
6167 // Build qualified pointer type.
6168 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006169 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006170 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006171 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006172 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6173
6174 // Insert qualified pointer type.
6175 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006176 }
6177
6178 return true;
6179}
6180
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006181/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6182/// to the set of pointer types along with any more-qualified variants of
6183/// that type. For example, if @p Ty is "int const *", this routine
6184/// will add "int const *", "int const volatile *", "int const
6185/// restrict *", and "int const volatile restrict *" to the set of
6186/// pointer types. Returns true if the add of @p Ty itself succeeded,
6187/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006188///
6189/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006190bool
6191BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6192 QualType Ty) {
6193 // Insert this type.
6194 if (!MemberPointerTypes.insert(Ty))
6195 return false;
6196
John McCall8ccfcb52009-09-24 19:53:00 +00006197 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6198 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006199
John McCall8ccfcb52009-09-24 19:53:00 +00006200 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006201 // Don't add qualified variants of arrays. For one, they're not allowed
6202 // (the qualifier would sink to the element type), and for another, the
6203 // only overload situation where it matters is subscript or pointer +- int,
6204 // and those shouldn't have qualifier variants anyway.
6205 if (PointeeTy->isArrayType())
6206 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006207 const Type *ClassTy = PointerTy->getClass();
6208
6209 // Iterate through all strict supersets of the pointee type's CVR
6210 // qualifiers.
6211 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6212 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6213 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006214
John McCall8ccfcb52009-09-24 19:53:00 +00006215 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006216 MemberPointerTypes.insert(
6217 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006218 }
6219
6220 return true;
6221}
6222
Douglas Gregora11693b2008-11-12 17:17:38 +00006223/// AddTypesConvertedFrom - Add each of the types to which the type @p
6224/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006225/// primarily interested in pointer types and enumeration types. We also
6226/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006227/// AllowUserConversions is true if we should look at the conversion
6228/// functions of a class type, and AllowExplicitConversions if we
6229/// should also include the explicit conversion functions of a class
6230/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006231void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006232BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006233 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006234 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006235 bool AllowExplicitConversions,
6236 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006237 // Only deal with canonical types.
6238 Ty = Context.getCanonicalType(Ty);
6239
6240 // Look through reference types; they aren't part of the type of an
6241 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006242 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006243 Ty = RefTy->getPointeeType();
6244
John McCall33ddac02011-01-19 10:06:00 +00006245 // If we're dealing with an array type, decay to the pointer.
6246 if (Ty->isArrayType())
6247 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6248
6249 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006250 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006251
Chandler Carruth00a38332010-12-13 01:44:01 +00006252 // Flag if we ever add a non-record type.
6253 const RecordType *TyRec = Ty->getAs<RecordType>();
6254 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6255
Chandler Carruth00a38332010-12-13 01:44:01 +00006256 // Flag if we encounter an arithmetic type.
6257 HasArithmeticOrEnumeralTypes =
6258 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6259
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006260 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6261 PointerTypes.insert(Ty);
6262 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006263 // Insert our type, and its more-qualified variants, into the set
6264 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006265 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006266 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006267 } else if (Ty->isMemberPointerType()) {
6268 // Member pointers are far easier, since the pointee can't be converted.
6269 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6270 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006271 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006272 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006273 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006274 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006275 // We treat vector types as arithmetic types in many contexts as an
6276 // extension.
6277 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006278 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006279 } else if (Ty->isNullPtrType()) {
6280 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006281 } else if (AllowUserConversions && TyRec) {
6282 // No conversion functions in incomplete types.
6283 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6284 return;
Mike Stump11289f42009-09-09 15:08:12 +00006285
Chandler Carruth00a38332010-12-13 01:44:01 +00006286 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6287 const UnresolvedSetImpl *Conversions
6288 = ClassDecl->getVisibleConversionFunctions();
6289 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6290 E = Conversions->end(); I != E; ++I) {
6291 NamedDecl *D = I.getDecl();
6292 if (isa<UsingShadowDecl>(D))
6293 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006294
Chandler Carruth00a38332010-12-13 01:44:01 +00006295 // Skip conversion function templates; they don't tell us anything
6296 // about which builtin types we can convert to.
6297 if (isa<FunctionTemplateDecl>(D))
6298 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006299
Chandler Carruth00a38332010-12-13 01:44:01 +00006300 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6301 if (AllowExplicitConversions || !Conv->isExplicit()) {
6302 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6303 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006304 }
6305 }
6306 }
6307}
6308
Douglas Gregor84605ae2009-08-24 13:43:27 +00006309/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6310/// the volatile- and non-volatile-qualified assignment operators for the
6311/// given type to the candidate set.
6312static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6313 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00006314 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006315 unsigned NumArgs,
6316 OverloadCandidateSet &CandidateSet) {
6317 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006318
Douglas Gregor84605ae2009-08-24 13:43:27 +00006319 // T& operator=(T&, T)
6320 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6321 ParamTypes[1] = T;
6322 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6323 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006324
Douglas Gregor84605ae2009-08-24 13:43:27 +00006325 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6326 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006327 ParamTypes[0]
6328 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006329 ParamTypes[1] = T;
6330 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006331 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006332 }
6333}
Mike Stump11289f42009-09-09 15:08:12 +00006334
Sebastian Redl1054fae2009-10-25 17:03:50 +00006335/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6336/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006337static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6338 Qualifiers VRQuals;
6339 const RecordType *TyRec;
6340 if (const MemberPointerType *RHSMPType =
6341 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006342 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006343 else
6344 TyRec = ArgExpr->getType()->getAs<RecordType>();
6345 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006346 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006347 VRQuals.addVolatile();
6348 VRQuals.addRestrict();
6349 return VRQuals;
6350 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006351
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006352 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006353 if (!ClassDecl->hasDefinition())
6354 return VRQuals;
6355
John McCallad371252010-01-20 00:46:10 +00006356 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00006357 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006358
John McCallad371252010-01-20 00:46:10 +00006359 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006360 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006361 NamedDecl *D = I.getDecl();
6362 if (isa<UsingShadowDecl>(D))
6363 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6364 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006365 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6366 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6367 CanTy = ResTypeRef->getPointeeType();
6368 // Need to go down the pointer/mempointer chain and add qualifiers
6369 // as see them.
6370 bool done = false;
6371 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006372 if (CanTy.isRestrictQualified())
6373 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006374 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6375 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006376 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006377 CanTy->getAs<MemberPointerType>())
6378 CanTy = ResTypeMPtr->getPointeeType();
6379 else
6380 done = true;
6381 if (CanTy.isVolatileQualified())
6382 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006383 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6384 return VRQuals;
6385 }
6386 }
6387 }
6388 return VRQuals;
6389}
John McCall52872982010-11-13 05:51:15 +00006390
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006391namespace {
John McCall52872982010-11-13 05:51:15 +00006392
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006393/// \brief Helper class to manage the addition of builtin operator overload
6394/// candidates. It provides shared state and utility methods used throughout
6395/// the process, as well as a helper method to add each group of builtin
6396/// operator overloads from the standard to a candidate set.
6397class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006398 // Common instance state available to all overload candidate addition methods.
6399 Sema &S;
6400 Expr **Args;
6401 unsigned NumArgs;
6402 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006403 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006404 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006405 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006406
Chandler Carruthc6586e52010-12-12 10:35:00 +00006407 // Define some constants used to index and iterate over the arithemetic types
6408 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006409 // The "promoted arithmetic types" are the arithmetic
6410 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006411 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00006412 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00006413 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00006414 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00006415 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00006416 LastPromotedArithmeticType = 11;
6417 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00006418
Chandler Carruthc6586e52010-12-12 10:35:00 +00006419 /// \brief Get the canonical type for a given arithmetic type index.
6420 CanQualType getArithmeticType(unsigned index) {
6421 assert(index < NumArithmeticTypes);
6422 static CanQualType ASTContext::* const
6423 ArithmeticTypes[NumArithmeticTypes] = {
6424 // Start of promoted types.
6425 &ASTContext::FloatTy,
6426 &ASTContext::DoubleTy,
6427 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006428
Chandler Carruthc6586e52010-12-12 10:35:00 +00006429 // Start of integral types.
6430 &ASTContext::IntTy,
6431 &ASTContext::LongTy,
6432 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006433 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006434 &ASTContext::UnsignedIntTy,
6435 &ASTContext::UnsignedLongTy,
6436 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006437 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006438 // End of promoted types.
6439
6440 &ASTContext::BoolTy,
6441 &ASTContext::CharTy,
6442 &ASTContext::WCharTy,
6443 &ASTContext::Char16Ty,
6444 &ASTContext::Char32Ty,
6445 &ASTContext::SignedCharTy,
6446 &ASTContext::ShortTy,
6447 &ASTContext::UnsignedCharTy,
6448 &ASTContext::UnsignedShortTy,
6449 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00006450 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00006451 };
6452 return S.Context.*ArithmeticTypes[index];
6453 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006454
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006455 /// \brief Gets the canonical type resulting from the usual arithemetic
6456 /// converions for the given arithmetic types.
6457 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6458 // Accelerator table for performing the usual arithmetic conversions.
6459 // The rules are basically:
6460 // - if either is floating-point, use the wider floating-point
6461 // - if same signedness, use the higher rank
6462 // - if same size, use unsigned of the higher rank
6463 // - use the larger type
6464 // These rules, together with the axiom that higher ranks are
6465 // never smaller, are sufficient to precompute all of these results
6466 // *except* when dealing with signed types of higher rank.
6467 // (we could precompute SLL x UI for all known platforms, but it's
6468 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00006469 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006470 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00006471 Dep=-1,
6472 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006473 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00006474 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006475 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00006476/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6477/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6478/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6479/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6480/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6481/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6482/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6483/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6484/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6485/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6486/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006487 };
6488
6489 assert(L < LastPromotedArithmeticType);
6490 assert(R < LastPromotedArithmeticType);
6491 int Idx = ConversionsTable[L][R];
6492
6493 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006494 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006495
6496 // Slow path: we need to compare widths.
6497 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006498 CanQualType LT = getArithmeticType(L),
6499 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006500 unsigned LW = S.Context.getIntWidth(LT),
6501 RW = S.Context.getIntWidth(RT);
6502
6503 // If they're different widths, use the signed type.
6504 if (LW > RW) return LT;
6505 else if (LW < RW) return RT;
6506
6507 // Otherwise, use the unsigned type of the signed type's rank.
6508 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6509 assert(L == SLL || R == SLL);
6510 return S.Context.UnsignedLongLongTy;
6511 }
6512
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006513 /// \brief Helper method to factor out the common pattern of adding overloads
6514 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006515 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006516 bool HasVolatile,
6517 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006518 QualType ParamTypes[2] = {
6519 S.Context.getLValueReferenceType(CandidateTy),
6520 S.Context.IntTy
6521 };
6522
6523 // Non-volatile version.
6524 if (NumArgs == 1)
6525 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6526 else
6527 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6528
6529 // Use a heuristic to reduce number of builtin candidates in the set:
6530 // add volatile version only if there are conversions to a volatile type.
6531 if (HasVolatile) {
6532 ParamTypes[0] =
6533 S.Context.getLValueReferenceType(
6534 S.Context.getVolatileType(CandidateTy));
6535 if (NumArgs == 1)
6536 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6537 else
6538 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6539 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00006540
6541 // Add restrict version only if there are conversions to a restrict type
6542 // and our candidate type is a non-restrict-qualified pointer.
6543 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6544 !CandidateTy.isRestrictQualified()) {
6545 ParamTypes[0]
6546 = S.Context.getLValueReferenceType(
6547 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6548 if (NumArgs == 1)
6549 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6550 else
6551 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6552
6553 if (HasVolatile) {
6554 ParamTypes[0]
6555 = S.Context.getLValueReferenceType(
6556 S.Context.getCVRQualifiedType(CandidateTy,
6557 (Qualifiers::Volatile |
6558 Qualifiers::Restrict)));
6559 if (NumArgs == 1)
6560 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6561 CandidateSet);
6562 else
6563 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6564 }
6565 }
6566
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006567 }
6568
6569public:
6570 BuiltinOperatorOverloadBuilder(
6571 Sema &S, Expr **Args, unsigned NumArgs,
6572 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006573 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006574 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006575 OverloadCandidateSet &CandidateSet)
6576 : S(S), Args(Args), NumArgs(NumArgs),
6577 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006578 HasArithmeticOrEnumeralCandidateType(
6579 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006580 CandidateTypes(CandidateTypes),
6581 CandidateSet(CandidateSet) {
6582 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006583 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006584 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006585 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00006586 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006587 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006588 assert(getArithmeticType(FirstPromotedArithmeticType)
6589 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006590 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006591 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00006592 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006593 "Invalid last promoted arithmetic type");
6594 }
6595
6596 // C++ [over.built]p3:
6597 //
6598 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6599 // is either volatile or empty, there exist candidate operator
6600 // functions of the form
6601 //
6602 // VQ T& operator++(VQ T&);
6603 // T operator++(VQ T&, int);
6604 //
6605 // C++ [over.built]p4:
6606 //
6607 // For every pair (T, VQ), where T is an arithmetic type other
6608 // than bool, and VQ is either volatile or empty, there exist
6609 // candidate operator functions of the form
6610 //
6611 // VQ T& operator--(VQ T&);
6612 // T operator--(VQ T&, int);
6613 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006614 if (!HasArithmeticOrEnumeralCandidateType)
6615 return;
6616
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006617 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6618 Arith < NumArithmeticTypes; ++Arith) {
6619 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00006620 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00006621 VisibleTypeConversionsQuals.hasVolatile(),
6622 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006623 }
6624 }
6625
6626 // C++ [over.built]p5:
6627 //
6628 // For every pair (T, VQ), where T is a cv-qualified or
6629 // cv-unqualified object type, and VQ is either volatile or
6630 // empty, there exist candidate operator functions of the form
6631 //
6632 // T*VQ& operator++(T*VQ&);
6633 // T*VQ& operator--(T*VQ&);
6634 // T* operator++(T*VQ&, int);
6635 // T* operator--(T*VQ&, int);
6636 void addPlusPlusMinusMinusPointerOverloads() {
6637 for (BuiltinCandidateTypeSet::iterator
6638 Ptr = CandidateTypes[0].pointer_begin(),
6639 PtrEnd = CandidateTypes[0].pointer_end();
6640 Ptr != PtrEnd; ++Ptr) {
6641 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00006642 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006643 continue;
6644
6645 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006646 (!(*Ptr).isVolatileQualified() &&
6647 VisibleTypeConversionsQuals.hasVolatile()),
6648 (!(*Ptr).isRestrictQualified() &&
6649 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006650 }
6651 }
6652
6653 // C++ [over.built]p6:
6654 // For every cv-qualified or cv-unqualified object type T, there
6655 // exist candidate operator functions of the form
6656 //
6657 // T& operator*(T*);
6658 //
6659 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006660 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00006661 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006662 // T& operator*(T*);
6663 void addUnaryStarPointerOverloads() {
6664 for (BuiltinCandidateTypeSet::iterator
6665 Ptr = CandidateTypes[0].pointer_begin(),
6666 PtrEnd = CandidateTypes[0].pointer_end();
6667 Ptr != PtrEnd; ++Ptr) {
6668 QualType ParamTy = *Ptr;
6669 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006670 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6671 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006672
Douglas Gregor02824322011-01-26 19:30:28 +00006673 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6674 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6675 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006676
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006677 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6678 &ParamTy, Args, 1, CandidateSet);
6679 }
6680 }
6681
6682 // C++ [over.built]p9:
6683 // For every promoted arithmetic type T, there exist candidate
6684 // operator functions of the form
6685 //
6686 // T operator+(T);
6687 // T operator-(T);
6688 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006689 if (!HasArithmeticOrEnumeralCandidateType)
6690 return;
6691
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006692 for (unsigned Arith = FirstPromotedArithmeticType;
6693 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006694 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006695 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6696 }
6697
6698 // Extension: We also add these operators for vector types.
6699 for (BuiltinCandidateTypeSet::iterator
6700 Vec = CandidateTypes[0].vector_begin(),
6701 VecEnd = CandidateTypes[0].vector_end();
6702 Vec != VecEnd; ++Vec) {
6703 QualType VecTy = *Vec;
6704 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6705 }
6706 }
6707
6708 // C++ [over.built]p8:
6709 // For every type T, there exist candidate operator functions of
6710 // the form
6711 //
6712 // T* operator+(T*);
6713 void addUnaryPlusPointerOverloads() {
6714 for (BuiltinCandidateTypeSet::iterator
6715 Ptr = CandidateTypes[0].pointer_begin(),
6716 PtrEnd = CandidateTypes[0].pointer_end();
6717 Ptr != PtrEnd; ++Ptr) {
6718 QualType ParamTy = *Ptr;
6719 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6720 }
6721 }
6722
6723 // C++ [over.built]p10:
6724 // For every promoted integral type T, there exist candidate
6725 // operator functions of the form
6726 //
6727 // T operator~(T);
6728 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006729 if (!HasArithmeticOrEnumeralCandidateType)
6730 return;
6731
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006732 for (unsigned Int = FirstPromotedIntegralType;
6733 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006734 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006735 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6736 }
6737
6738 // Extension: We also add this operator for vector types.
6739 for (BuiltinCandidateTypeSet::iterator
6740 Vec = CandidateTypes[0].vector_begin(),
6741 VecEnd = CandidateTypes[0].vector_end();
6742 Vec != VecEnd; ++Vec) {
6743 QualType VecTy = *Vec;
6744 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6745 }
6746 }
6747
6748 // C++ [over.match.oper]p16:
6749 // For every pointer to member type T, there exist candidate operator
6750 // functions of the form
6751 //
6752 // bool operator==(T,T);
6753 // bool operator!=(T,T);
6754 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6755 /// Set of (canonical) types that we've already handled.
6756 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6757
6758 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6759 for (BuiltinCandidateTypeSet::iterator
6760 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6761 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6762 MemPtr != MemPtrEnd;
6763 ++MemPtr) {
6764 // Don't add the same builtin candidate twice.
6765 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6766 continue;
6767
6768 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6769 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6770 CandidateSet);
6771 }
6772 }
6773 }
6774
6775 // C++ [over.built]p15:
6776 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006777 // For every T, where T is an enumeration type, a pointer type, or
6778 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006779 //
6780 // bool operator<(T, T);
6781 // bool operator>(T, T);
6782 // bool operator<=(T, T);
6783 // bool operator>=(T, T);
6784 // bool operator==(T, T);
6785 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006786 void addRelationalPointerOrEnumeralOverloads() {
6787 // C++ [over.built]p1:
6788 // If there is a user-written candidate with the same name and parameter
6789 // types as a built-in candidate operator function, the built-in operator
6790 // function is hidden and is not included in the set of candidate
6791 // functions.
6792 //
6793 // The text is actually in a note, but if we don't implement it then we end
6794 // up with ambiguities when the user provides an overloaded operator for
6795 // an enumeration type. Note that only enumeration types have this problem,
6796 // so we track which enumeration types we've seen operators for. Also, the
6797 // only other overloaded operator with enumeration argumenst, operator=,
6798 // cannot be overloaded for enumeration types, so this is the only place
6799 // where we must suppress candidates like this.
6800 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6801 UserDefinedBinaryOperators;
6802
6803 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6804 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6805 CandidateTypes[ArgIdx].enumeration_end()) {
6806 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6807 CEnd = CandidateSet.end();
6808 C != CEnd; ++C) {
6809 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6810 continue;
6811
6812 QualType FirstParamType =
6813 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6814 QualType SecondParamType =
6815 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6816
6817 // Skip if either parameter isn't of enumeral type.
6818 if (!FirstParamType->isEnumeralType() ||
6819 !SecondParamType->isEnumeralType())
6820 continue;
6821
6822 // Add this operator to the set of known user-defined operators.
6823 UserDefinedBinaryOperators.insert(
6824 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6825 S.Context.getCanonicalType(SecondParamType)));
6826 }
6827 }
6828 }
6829
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006830 /// Set of (canonical) types that we've already handled.
6831 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6832
6833 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6834 for (BuiltinCandidateTypeSet::iterator
6835 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6836 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6837 Ptr != PtrEnd; ++Ptr) {
6838 // Don't add the same builtin candidate twice.
6839 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6840 continue;
6841
6842 QualType ParamTypes[2] = { *Ptr, *Ptr };
6843 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6844 CandidateSet);
6845 }
6846 for (BuiltinCandidateTypeSet::iterator
6847 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6848 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6849 Enum != EnumEnd; ++Enum) {
6850 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6851
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006852 // Don't add the same builtin candidate twice, or if a user defined
6853 // candidate exists.
6854 if (!AddedTypes.insert(CanonType) ||
6855 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6856 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006857 continue;
6858
6859 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006860 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6861 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006862 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006863
6864 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6865 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6866 if (AddedTypes.insert(NullPtrTy) &&
6867 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6868 NullPtrTy))) {
6869 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6870 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6871 CandidateSet);
6872 }
6873 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006874 }
6875 }
6876
6877 // C++ [over.built]p13:
6878 //
6879 // For every cv-qualified or cv-unqualified object type T
6880 // there exist candidate operator functions of the form
6881 //
6882 // T* operator+(T*, ptrdiff_t);
6883 // T& operator[](T*, ptrdiff_t); [BELOW]
6884 // T* operator-(T*, ptrdiff_t);
6885 // T* operator+(ptrdiff_t, T*);
6886 // T& operator[](ptrdiff_t, T*); [BELOW]
6887 //
6888 // C++ [over.built]p14:
6889 //
6890 // For every T, where T is a pointer to object type, there
6891 // exist candidate operator functions of the form
6892 //
6893 // ptrdiff_t operator-(T, T);
6894 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6895 /// Set of (canonical) types that we've already handled.
6896 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6897
6898 for (int Arg = 0; Arg < 2; ++Arg) {
6899 QualType AsymetricParamTypes[2] = {
6900 S.Context.getPointerDiffType(),
6901 S.Context.getPointerDiffType(),
6902 };
6903 for (BuiltinCandidateTypeSet::iterator
6904 Ptr = CandidateTypes[Arg].pointer_begin(),
6905 PtrEnd = CandidateTypes[Arg].pointer_end();
6906 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006907 QualType PointeeTy = (*Ptr)->getPointeeType();
6908 if (!PointeeTy->isObjectType())
6909 continue;
6910
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006911 AsymetricParamTypes[Arg] = *Ptr;
6912 if (Arg == 0 || Op == OO_Plus) {
6913 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6914 // T* operator+(ptrdiff_t, T*);
6915 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6916 CandidateSet);
6917 }
6918 if (Op == OO_Minus) {
6919 // ptrdiff_t operator-(T, T);
6920 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6921 continue;
6922
6923 QualType ParamTypes[2] = { *Ptr, *Ptr };
6924 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6925 Args, 2, CandidateSet);
6926 }
6927 }
6928 }
6929 }
6930
6931 // C++ [over.built]p12:
6932 //
6933 // For every pair of promoted arithmetic types L and R, there
6934 // exist candidate operator functions of the form
6935 //
6936 // LR operator*(L, R);
6937 // LR operator/(L, R);
6938 // LR operator+(L, R);
6939 // LR operator-(L, R);
6940 // bool operator<(L, R);
6941 // bool operator>(L, R);
6942 // bool operator<=(L, R);
6943 // bool operator>=(L, R);
6944 // bool operator==(L, R);
6945 // bool operator!=(L, R);
6946 //
6947 // where LR is the result of the usual arithmetic conversions
6948 // between types L and R.
6949 //
6950 // C++ [over.built]p24:
6951 //
6952 // For every pair of promoted arithmetic types L and R, there exist
6953 // candidate operator functions of the form
6954 //
6955 // LR operator?(bool, L, R);
6956 //
6957 // where LR is the result of the usual arithmetic conversions
6958 // between types L and R.
6959 // Our candidates ignore the first parameter.
6960 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006961 if (!HasArithmeticOrEnumeralCandidateType)
6962 return;
6963
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006964 for (unsigned Left = FirstPromotedArithmeticType;
6965 Left < LastPromotedArithmeticType; ++Left) {
6966 for (unsigned Right = FirstPromotedArithmeticType;
6967 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006968 QualType LandR[2] = { getArithmeticType(Left),
6969 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006970 QualType Result =
6971 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006972 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006973 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6974 }
6975 }
6976
6977 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6978 // conditional operator for vector types.
6979 for (BuiltinCandidateTypeSet::iterator
6980 Vec1 = CandidateTypes[0].vector_begin(),
6981 Vec1End = CandidateTypes[0].vector_end();
6982 Vec1 != Vec1End; ++Vec1) {
6983 for (BuiltinCandidateTypeSet::iterator
6984 Vec2 = CandidateTypes[1].vector_begin(),
6985 Vec2End = CandidateTypes[1].vector_end();
6986 Vec2 != Vec2End; ++Vec2) {
6987 QualType LandR[2] = { *Vec1, *Vec2 };
6988 QualType Result = S.Context.BoolTy;
6989 if (!isComparison) {
6990 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6991 Result = *Vec1;
6992 else
6993 Result = *Vec2;
6994 }
6995
6996 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6997 }
6998 }
6999 }
7000
7001 // C++ [over.built]p17:
7002 //
7003 // For every pair of promoted integral types L and R, there
7004 // exist candidate operator functions of the form
7005 //
7006 // LR operator%(L, R);
7007 // LR operator&(L, R);
7008 // LR operator^(L, R);
7009 // LR operator|(L, R);
7010 // L operator<<(L, R);
7011 // L operator>>(L, R);
7012 //
7013 // where LR is the result of the usual arithmetic conversions
7014 // between types L and R.
7015 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007016 if (!HasArithmeticOrEnumeralCandidateType)
7017 return;
7018
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007019 for (unsigned Left = FirstPromotedIntegralType;
7020 Left < LastPromotedIntegralType; ++Left) {
7021 for (unsigned Right = FirstPromotedIntegralType;
7022 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007023 QualType LandR[2] = { getArithmeticType(Left),
7024 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007025 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7026 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007027 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007028 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7029 }
7030 }
7031 }
7032
7033 // C++ [over.built]p20:
7034 //
7035 // For every pair (T, VQ), where T is an enumeration or
7036 // pointer to member type and VQ is either volatile or
7037 // empty, there exist candidate operator functions of the form
7038 //
7039 // VQ T& operator=(VQ T&, T);
7040 void addAssignmentMemberPointerOrEnumeralOverloads() {
7041 /// Set of (canonical) types that we've already handled.
7042 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7043
7044 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7045 for (BuiltinCandidateTypeSet::iterator
7046 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7047 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7048 Enum != EnumEnd; ++Enum) {
7049 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7050 continue;
7051
7052 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7053 CandidateSet);
7054 }
7055
7056 for (BuiltinCandidateTypeSet::iterator
7057 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7058 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7059 MemPtr != MemPtrEnd; ++MemPtr) {
7060 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7061 continue;
7062
7063 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7064 CandidateSet);
7065 }
7066 }
7067 }
7068
7069 // C++ [over.built]p19:
7070 //
7071 // For every pair (T, VQ), where T is any type and VQ is either
7072 // volatile or empty, there exist candidate operator functions
7073 // of the form
7074 //
7075 // T*VQ& operator=(T*VQ&, T*);
7076 //
7077 // C++ [over.built]p21:
7078 //
7079 // For every pair (T, VQ), where T is a cv-qualified or
7080 // cv-unqualified object type and VQ is either volatile or
7081 // empty, there exist candidate operator functions of the form
7082 //
7083 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7084 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7085 void addAssignmentPointerOverloads(bool isEqualOp) {
7086 /// Set of (canonical) types that we've already handled.
7087 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7088
7089 for (BuiltinCandidateTypeSet::iterator
7090 Ptr = CandidateTypes[0].pointer_begin(),
7091 PtrEnd = CandidateTypes[0].pointer_end();
7092 Ptr != PtrEnd; ++Ptr) {
7093 // If this is operator=, keep track of the builtin candidates we added.
7094 if (isEqualOp)
7095 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007096 else if (!(*Ptr)->getPointeeType()->isObjectType())
7097 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007098
7099 // non-volatile version
7100 QualType ParamTypes[2] = {
7101 S.Context.getLValueReferenceType(*Ptr),
7102 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7103 };
7104 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7105 /*IsAssigmentOperator=*/ isEqualOp);
7106
Douglas Gregor5bee2582012-06-04 00:15:09 +00007107 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7108 VisibleTypeConversionsQuals.hasVolatile();
7109 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007110 // volatile version
7111 ParamTypes[0] =
7112 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7113 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7114 /*IsAssigmentOperator=*/isEqualOp);
7115 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007116
7117 if (!(*Ptr).isRestrictQualified() &&
7118 VisibleTypeConversionsQuals.hasRestrict()) {
7119 // restrict version
7120 ParamTypes[0]
7121 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7122 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7123 /*IsAssigmentOperator=*/isEqualOp);
7124
7125 if (NeedVolatile) {
7126 // volatile restrict version
7127 ParamTypes[0]
7128 = S.Context.getLValueReferenceType(
7129 S.Context.getCVRQualifiedType(*Ptr,
7130 (Qualifiers::Volatile |
7131 Qualifiers::Restrict)));
7132 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7133 CandidateSet,
7134 /*IsAssigmentOperator=*/isEqualOp);
7135 }
7136 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007137 }
7138
7139 if (isEqualOp) {
7140 for (BuiltinCandidateTypeSet::iterator
7141 Ptr = CandidateTypes[1].pointer_begin(),
7142 PtrEnd = CandidateTypes[1].pointer_end();
7143 Ptr != PtrEnd; ++Ptr) {
7144 // Make sure we don't add the same candidate twice.
7145 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7146 continue;
7147
Chandler Carruth8e543b32010-12-12 08:17:55 +00007148 QualType ParamTypes[2] = {
7149 S.Context.getLValueReferenceType(*Ptr),
7150 *Ptr,
7151 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007152
7153 // non-volatile version
7154 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7155 /*IsAssigmentOperator=*/true);
7156
Douglas Gregor5bee2582012-06-04 00:15:09 +00007157 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7158 VisibleTypeConversionsQuals.hasVolatile();
7159 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007160 // volatile version
7161 ParamTypes[0] =
7162 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00007163 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7164 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007165 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007166
7167 if (!(*Ptr).isRestrictQualified() &&
7168 VisibleTypeConversionsQuals.hasRestrict()) {
7169 // restrict version
7170 ParamTypes[0]
7171 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7172 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7173 CandidateSet, /*IsAssigmentOperator=*/true);
7174
7175 if (NeedVolatile) {
7176 // volatile restrict version
7177 ParamTypes[0]
7178 = S.Context.getLValueReferenceType(
7179 S.Context.getCVRQualifiedType(*Ptr,
7180 (Qualifiers::Volatile |
7181 Qualifiers::Restrict)));
7182 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7183 CandidateSet, /*IsAssigmentOperator=*/true);
7184
7185 }
7186 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007187 }
7188 }
7189 }
7190
7191 // C++ [over.built]p18:
7192 //
7193 // For every triple (L, VQ, R), where L is an arithmetic type,
7194 // VQ is either volatile or empty, and R is a promoted
7195 // arithmetic type, there exist candidate operator functions of
7196 // the form
7197 //
7198 // VQ L& operator=(VQ L&, R);
7199 // VQ L& operator*=(VQ L&, R);
7200 // VQ L& operator/=(VQ L&, R);
7201 // VQ L& operator+=(VQ L&, R);
7202 // VQ L& operator-=(VQ L&, R);
7203 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007204 if (!HasArithmeticOrEnumeralCandidateType)
7205 return;
7206
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007207 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7208 for (unsigned Right = FirstPromotedArithmeticType;
7209 Right < LastPromotedArithmeticType; ++Right) {
7210 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007211 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007212
7213 // Add this built-in operator as a candidate (VQ is empty).
7214 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007215 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007216 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7217 /*IsAssigmentOperator=*/isEqualOp);
7218
7219 // Add this built-in operator as a candidate (VQ is 'volatile').
7220 if (VisibleTypeConversionsQuals.hasVolatile()) {
7221 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007222 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007223 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007224 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7225 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007226 /*IsAssigmentOperator=*/isEqualOp);
7227 }
7228 }
7229 }
7230
7231 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7232 for (BuiltinCandidateTypeSet::iterator
7233 Vec1 = CandidateTypes[0].vector_begin(),
7234 Vec1End = CandidateTypes[0].vector_end();
7235 Vec1 != Vec1End; ++Vec1) {
7236 for (BuiltinCandidateTypeSet::iterator
7237 Vec2 = CandidateTypes[1].vector_begin(),
7238 Vec2End = CandidateTypes[1].vector_end();
7239 Vec2 != Vec2End; ++Vec2) {
7240 QualType ParamTypes[2];
7241 ParamTypes[1] = *Vec2;
7242 // Add this built-in operator as a candidate (VQ is empty).
7243 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7244 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7245 /*IsAssigmentOperator=*/isEqualOp);
7246
7247 // Add this built-in operator as a candidate (VQ is 'volatile').
7248 if (VisibleTypeConversionsQuals.hasVolatile()) {
7249 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7250 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007251 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7252 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007253 /*IsAssigmentOperator=*/isEqualOp);
7254 }
7255 }
7256 }
7257 }
7258
7259 // C++ [over.built]p22:
7260 //
7261 // For every triple (L, VQ, R), where L is an integral type, VQ
7262 // is either volatile or empty, and R is a promoted integral
7263 // type, there exist candidate operator functions of the form
7264 //
7265 // VQ L& operator%=(VQ L&, R);
7266 // VQ L& operator<<=(VQ L&, R);
7267 // VQ L& operator>>=(VQ L&, R);
7268 // VQ L& operator&=(VQ L&, R);
7269 // VQ L& operator^=(VQ L&, R);
7270 // VQ L& operator|=(VQ L&, R);
7271 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007272 if (!HasArithmeticOrEnumeralCandidateType)
7273 return;
7274
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007275 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7276 for (unsigned Right = FirstPromotedIntegralType;
7277 Right < LastPromotedIntegralType; ++Right) {
7278 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007279 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007280
7281 // Add this built-in operator as a candidate (VQ is empty).
7282 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007283 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007284 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7285 if (VisibleTypeConversionsQuals.hasVolatile()) {
7286 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007287 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007288 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7289 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7290 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7291 CandidateSet);
7292 }
7293 }
7294 }
7295 }
7296
7297 // C++ [over.operator]p23:
7298 //
7299 // There also exist candidate operator functions of the form
7300 //
7301 // bool operator!(bool);
7302 // bool operator&&(bool, bool);
7303 // bool operator||(bool, bool);
7304 void addExclaimOverload() {
7305 QualType ParamTy = S.Context.BoolTy;
7306 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7307 /*IsAssignmentOperator=*/false,
7308 /*NumContextualBoolArguments=*/1);
7309 }
7310 void addAmpAmpOrPipePipeOverload() {
7311 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7312 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7313 /*IsAssignmentOperator=*/false,
7314 /*NumContextualBoolArguments=*/2);
7315 }
7316
7317 // C++ [over.built]p13:
7318 //
7319 // For every cv-qualified or cv-unqualified object type T there
7320 // exist candidate operator functions of the form
7321 //
7322 // T* operator+(T*, ptrdiff_t); [ABOVE]
7323 // T& operator[](T*, ptrdiff_t);
7324 // T* operator-(T*, ptrdiff_t); [ABOVE]
7325 // T* operator+(ptrdiff_t, T*); [ABOVE]
7326 // T& operator[](ptrdiff_t, T*);
7327 void addSubscriptOverloads() {
7328 for (BuiltinCandidateTypeSet::iterator
7329 Ptr = CandidateTypes[0].pointer_begin(),
7330 PtrEnd = CandidateTypes[0].pointer_end();
7331 Ptr != PtrEnd; ++Ptr) {
7332 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7333 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007334 if (!PointeeType->isObjectType())
7335 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007336
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007337 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7338
7339 // T& operator[](T*, ptrdiff_t)
7340 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7341 }
7342
7343 for (BuiltinCandidateTypeSet::iterator
7344 Ptr = CandidateTypes[1].pointer_begin(),
7345 PtrEnd = CandidateTypes[1].pointer_end();
7346 Ptr != PtrEnd; ++Ptr) {
7347 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7348 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007349 if (!PointeeType->isObjectType())
7350 continue;
7351
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007352 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7353
7354 // T& operator[](ptrdiff_t, T*)
7355 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7356 }
7357 }
7358
7359 // C++ [over.built]p11:
7360 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7361 // C1 is the same type as C2 or is a derived class of C2, T is an object
7362 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7363 // there exist candidate operator functions of the form
7364 //
7365 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7366 //
7367 // where CV12 is the union of CV1 and CV2.
7368 void addArrowStarOverloads() {
7369 for (BuiltinCandidateTypeSet::iterator
7370 Ptr = CandidateTypes[0].pointer_begin(),
7371 PtrEnd = CandidateTypes[0].pointer_end();
7372 Ptr != PtrEnd; ++Ptr) {
7373 QualType C1Ty = (*Ptr);
7374 QualType C1;
7375 QualifierCollector Q1;
7376 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7377 if (!isa<RecordType>(C1))
7378 continue;
7379 // heuristic to reduce number of builtin candidates in the set.
7380 // Add volatile/restrict version only if there are conversions to a
7381 // volatile/restrict type.
7382 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7383 continue;
7384 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7385 continue;
7386 for (BuiltinCandidateTypeSet::iterator
7387 MemPtr = CandidateTypes[1].member_pointer_begin(),
7388 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7389 MemPtr != MemPtrEnd; ++MemPtr) {
7390 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7391 QualType C2 = QualType(mptr->getClass(), 0);
7392 C2 = C2.getUnqualifiedType();
7393 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7394 break;
7395 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7396 // build CV12 T&
7397 QualType T = mptr->getPointeeType();
7398 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7399 T.isVolatileQualified())
7400 continue;
7401 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7402 T.isRestrictQualified())
7403 continue;
7404 T = Q1.apply(S.Context, T);
7405 QualType ResultTy = S.Context.getLValueReferenceType(T);
7406 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7407 }
7408 }
7409 }
7410
7411 // Note that we don't consider the first argument, since it has been
7412 // contextually converted to bool long ago. The candidates below are
7413 // therefore added as binary.
7414 //
7415 // C++ [over.built]p25:
7416 // For every type T, where T is a pointer, pointer-to-member, or scoped
7417 // enumeration type, there exist candidate operator functions of the form
7418 //
7419 // T operator?(bool, T, T);
7420 //
7421 void addConditionalOperatorOverloads() {
7422 /// Set of (canonical) types that we've already handled.
7423 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7424
7425 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7426 for (BuiltinCandidateTypeSet::iterator
7427 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7428 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7429 Ptr != PtrEnd; ++Ptr) {
7430 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7431 continue;
7432
7433 QualType ParamTypes[2] = { *Ptr, *Ptr };
7434 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7435 }
7436
7437 for (BuiltinCandidateTypeSet::iterator
7438 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7439 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7440 MemPtr != MemPtrEnd; ++MemPtr) {
7441 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7442 continue;
7443
7444 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7445 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7446 }
7447
David Blaikiebbafb8a2012-03-11 07:00:24 +00007448 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007449 for (BuiltinCandidateTypeSet::iterator
7450 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7451 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7452 Enum != EnumEnd; ++Enum) {
7453 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7454 continue;
7455
7456 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7457 continue;
7458
7459 QualType ParamTypes[2] = { *Enum, *Enum };
7460 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7461 }
7462 }
7463 }
7464 }
7465};
7466
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007467} // end anonymous namespace
7468
7469/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7470/// operator overloads to the candidate set (C++ [over.built]), based
7471/// on the operator @p Op and the arguments given. For example, if the
7472/// operator is a binary '+', this routine might add "int
7473/// operator+(int, int)" to cover integer addition.
7474void
7475Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7476 SourceLocation OpLoc,
7477 Expr **Args, unsigned NumArgs,
7478 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007479 // Find all of the types that the arguments can convert to, but only
7480 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007481 // that make use of these types. Also record whether we encounter non-record
7482 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007483 Qualifiers VisibleTypeConversionsQuals;
7484 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007485 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7486 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007487
7488 bool HasNonRecordCandidateType = false;
7489 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007490 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007491 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7492 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7493 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7494 OpLoc,
7495 true,
7496 (Op == OO_Exclaim ||
7497 Op == OO_AmpAmp ||
7498 Op == OO_PipePipe),
7499 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007500 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7501 CandidateTypes[ArgIdx].hasNonRecordTypes();
7502 HasArithmeticOrEnumeralCandidateType =
7503 HasArithmeticOrEnumeralCandidateType ||
7504 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007505 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007506
Chandler Carruth00a38332010-12-13 01:44:01 +00007507 // Exit early when no non-record types have been added to the candidate set
7508 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007509 //
7510 // We can't exit early for !, ||, or &&, since there we have always have
7511 // 'bool' overloads.
7512 if (!HasNonRecordCandidateType &&
7513 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007514 return;
7515
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007516 // Setup an object to manage the common state for building overloads.
7517 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7518 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007519 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007520 CandidateTypes, CandidateSet);
7521
7522 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007523 switch (Op) {
7524 case OO_None:
7525 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007526 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007527
Chandler Carruth5184de02010-12-12 08:51:33 +00007528 case OO_New:
7529 case OO_Delete:
7530 case OO_Array_New:
7531 case OO_Array_Delete:
7532 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007533 llvm_unreachable(
7534 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007535
7536 case OO_Comma:
7537 case OO_Arrow:
7538 // C++ [over.match.oper]p3:
7539 // -- For the operator ',', the unary operator '&', or the
7540 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007541 break;
7542
7543 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007544 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007545 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007546 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007547
7548 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00007549 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007550 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007551 } else {
7552 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7553 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7554 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007555 break;
7556
Chandler Carruth5184de02010-12-12 08:51:33 +00007557 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00007558 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007559 OpBuilder.addUnaryStarPointerOverloads();
7560 else
7561 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7562 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007563
Chandler Carruth5184de02010-12-12 08:51:33 +00007564 case OO_Slash:
7565 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007566 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007567
7568 case OO_PlusPlus:
7569 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007570 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7571 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007572 break;
7573
Douglas Gregor84605ae2009-08-24 13:43:27 +00007574 case OO_EqualEqual:
7575 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007576 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007577 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007578
Douglas Gregora11693b2008-11-12 17:17:38 +00007579 case OO_Less:
7580 case OO_Greater:
7581 case OO_LessEqual:
7582 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007583 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007584 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7585 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007586
Douglas Gregora11693b2008-11-12 17:17:38 +00007587 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007588 case OO_Caret:
7589 case OO_Pipe:
7590 case OO_LessLess:
7591 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007592 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007593 break;
7594
Chandler Carruth5184de02010-12-12 08:51:33 +00007595 case OO_Amp: // '&' is either unary or binary
7596 if (NumArgs == 1)
7597 // C++ [over.match.oper]p3:
7598 // -- For the operator ',', the unary operator '&', or the
7599 // operator '->', the built-in candidates set is empty.
7600 break;
7601
7602 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7603 break;
7604
7605 case OO_Tilde:
7606 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7607 break;
7608
Douglas Gregora11693b2008-11-12 17:17:38 +00007609 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007610 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007611 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00007612
7613 case OO_PlusEqual:
7614 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007615 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007616 // Fall through.
7617
7618 case OO_StarEqual:
7619 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007620 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007621 break;
7622
7623 case OO_PercentEqual:
7624 case OO_LessLessEqual:
7625 case OO_GreaterGreaterEqual:
7626 case OO_AmpEqual:
7627 case OO_CaretEqual:
7628 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007629 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007630 break;
7631
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007632 case OO_Exclaim:
7633 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00007634 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007635
Douglas Gregora11693b2008-11-12 17:17:38 +00007636 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007637 case OO_PipePipe:
7638 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00007639 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007640
7641 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007642 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007643 break;
7644
7645 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007646 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007647 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00007648
7649 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007650 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007651 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7652 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007653 }
7654}
7655
Douglas Gregore254f902009-02-04 00:32:51 +00007656/// \brief Add function candidates found via argument-dependent lookup
7657/// to the set of overloading candidates.
7658///
7659/// This routine performs argument-dependent name lookup based on the
7660/// given function name (which may also be an operator name) and adds
7661/// all of the overload candidates found by ADL to the overload
7662/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00007663void
Douglas Gregore254f902009-02-04 00:32:51 +00007664Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00007665 bool Operator, SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007666 llvm::ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007667 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007668 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00007669 bool PartialOverloading,
7670 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00007671 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00007672
John McCall91f61fc2010-01-26 06:04:06 +00007673 // FIXME: This approach for uniquing ADL results (and removing
7674 // redundant candidates from the set) relies on pointer-equality,
7675 // which means we need to key off the canonical decl. However,
7676 // always going back to the canonical decl might not get us the
7677 // right set of default arguments. What default arguments are
7678 // we supposed to consider on ADL candidates, anyway?
7679
Douglas Gregorcabea402009-09-22 15:41:20 +00007680 // FIXME: Pass in the explicit template arguments?
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007681 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smith02e85f32011-04-14 22:09:26 +00007682 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00007683
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007684 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007685 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7686 CandEnd = CandidateSet.end();
7687 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00007688 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00007689 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00007690 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00007691 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00007692 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007693
7694 // For each of the ADL candidates we found, add it to the overload
7695 // set.
John McCall8fe68082010-01-26 07:16:45 +00007696 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00007697 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00007698 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00007699 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00007700 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007701
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007702 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7703 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007704 } else
John McCall4c4c1df2010-01-26 03:27:55 +00007705 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00007706 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007707 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00007708 }
Douglas Gregore254f902009-02-04 00:32:51 +00007709}
7710
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007711/// isBetterOverloadCandidate - Determines whether the first overload
7712/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00007713bool
John McCall5c32be02010-08-24 20:38:10 +00007714isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007715 const OverloadCandidate &Cand1,
7716 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007717 SourceLocation Loc,
7718 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007719 // Define viable functions to be better candidates than non-viable
7720 // functions.
7721 if (!Cand2.Viable)
7722 return Cand1.Viable;
7723 else if (!Cand1.Viable)
7724 return false;
7725
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007726 // C++ [over.match.best]p1:
7727 //
7728 // -- if F is a static member function, ICS1(F) is defined such
7729 // that ICS1(F) is neither better nor worse than ICS1(G) for
7730 // any function G, and, symmetrically, ICS1(G) is neither
7731 // better nor worse than ICS1(F).
7732 unsigned StartArg = 0;
7733 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7734 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007735
Douglas Gregord3cb3562009-07-07 23:38:56 +00007736 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007737 // A viable function F1 is defined to be a better function than another
7738 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007739 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007740 unsigned NumArgs = Cand1.NumConversions;
7741 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007742 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007743 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007744 switch (CompareImplicitConversionSequences(S,
7745 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007746 Cand2.Conversions[ArgIdx])) {
7747 case ImplicitConversionSequence::Better:
7748 // Cand1 has a better conversion sequence.
7749 HasBetterConversion = true;
7750 break;
7751
7752 case ImplicitConversionSequence::Worse:
7753 // Cand1 can't be better than Cand2.
7754 return false;
7755
7756 case ImplicitConversionSequence::Indistinguishable:
7757 // Do nothing.
7758 break;
7759 }
7760 }
7761
Mike Stump11289f42009-09-09 15:08:12 +00007762 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007763 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007764 if (HasBetterConversion)
7765 return true;
7766
Mike Stump11289f42009-09-09 15:08:12 +00007767 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007768 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007769 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007770 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7771 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007772
7773 // -- F1 and F2 are function template specializations, and the function
7774 // template for F1 is more specialized than the template for F2
7775 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007776 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007777 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007778 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007779 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007780 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7781 Cand2.Function->getPrimaryTemplate(),
7782 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007783 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007784 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007785 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007786 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007787 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007788
Douglas Gregora1f013e2008-11-07 22:36:19 +00007789 // -- the context is an initialization by user-defined conversion
7790 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7791 // from the return type of F1 to the destination type (i.e.,
7792 // the type of the entity being initialized) is a better
7793 // conversion sequence than the standard conversion sequence
7794 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007795 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007796 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007797 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00007798 // First check whether we prefer one of the conversion functions over the
7799 // other. This only distinguishes the results in non-standard, extension
7800 // cases such as the conversion from a lambda closure type to a function
7801 // pointer or block.
7802 ImplicitConversionSequence::CompareKind FuncResult
7803 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7804 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7805 return FuncResult;
7806
John McCall5c32be02010-08-24 20:38:10 +00007807 switch (CompareStandardConversionSequences(S,
7808 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007809 Cand2.FinalConversion)) {
7810 case ImplicitConversionSequence::Better:
7811 // Cand1 has a better conversion sequence.
7812 return true;
7813
7814 case ImplicitConversionSequence::Worse:
7815 // Cand1 can't be better than Cand2.
7816 return false;
7817
7818 case ImplicitConversionSequence::Indistinguishable:
7819 // Do nothing
7820 break;
7821 }
7822 }
7823
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007824 return false;
7825}
7826
Mike Stump11289f42009-09-09 15:08:12 +00007827/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007828/// within an overload candidate set.
7829///
James Dennettffad8b72012-06-22 08:10:18 +00007830/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007831/// which overload resolution occurs.
7832///
James Dennettffad8b72012-06-22 08:10:18 +00007833/// \param Best If overload resolution was successful or found a deleted
7834/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007835///
7836/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007837OverloadingResult
7838OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007839 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007840 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007841 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007842 Best = end();
7843 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7844 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007845 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007846 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007847 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007848 }
7849
7850 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007851 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007852 return OR_No_Viable_Function;
7853
7854 // Make sure that this function is better than every other viable
7855 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007856 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007857 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007858 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007859 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007860 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007861 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007862 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007863 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007864 }
Mike Stump11289f42009-09-09 15:08:12 +00007865
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007866 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007867 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007868 (Best->Function->isDeleted() ||
7869 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007870 return OR_Deleted;
7871
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007872 return OR_Success;
7873}
7874
John McCall53262c92010-01-12 02:15:36 +00007875namespace {
7876
7877enum OverloadCandidateKind {
7878 oc_function,
7879 oc_method,
7880 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007881 oc_function_template,
7882 oc_method_template,
7883 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007884 oc_implicit_default_constructor,
7885 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007886 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007887 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007888 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007889 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007890};
7891
John McCalle1ac8d12010-01-13 00:25:19 +00007892OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7893 FunctionDecl *Fn,
7894 std::string &Description) {
7895 bool isTemplate = false;
7896
7897 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7898 isTemplate = true;
7899 Description = S.getTemplateArgumentBindingsText(
7900 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7901 }
John McCallfd0b2f82010-01-06 09:43:14 +00007902
7903 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007904 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007905 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007906
Sebastian Redl08905022011-02-05 19:23:19 +00007907 if (Ctor->getInheritedConstructor())
7908 return oc_implicit_inherited_constructor;
7909
Alexis Hunt119c10e2011-05-25 23:16:36 +00007910 if (Ctor->isDefaultConstructor())
7911 return oc_implicit_default_constructor;
7912
7913 if (Ctor->isMoveConstructor())
7914 return oc_implicit_move_constructor;
7915
7916 assert(Ctor->isCopyConstructor() &&
7917 "unexpected sort of implicit constructor");
7918 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007919 }
7920
7921 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7922 // This actually gets spelled 'candidate function' for now, but
7923 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007924 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007925 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007926
Alexis Hunt119c10e2011-05-25 23:16:36 +00007927 if (Meth->isMoveAssignmentOperator())
7928 return oc_implicit_move_assignment;
7929
Douglas Gregor12695102012-02-10 08:36:38 +00007930 if (Meth->isCopyAssignmentOperator())
7931 return oc_implicit_copy_assignment;
7932
7933 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7934 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00007935 }
7936
John McCalle1ac8d12010-01-13 00:25:19 +00007937 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007938}
7939
Sebastian Redl08905022011-02-05 19:23:19 +00007940void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7941 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7942 if (!Ctor) return;
7943
7944 Ctor = Ctor->getInheritedConstructor();
7945 if (!Ctor) return;
7946
7947 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7948}
7949
John McCall53262c92010-01-12 02:15:36 +00007950} // end anonymous namespace
7951
7952// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007953void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007954 std::string FnDesc;
7955 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007956 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7957 << (unsigned) K << FnDesc;
7958 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7959 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007960 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007961}
7962
Douglas Gregorb491ed32011-02-19 21:32:49 +00007963//Notes the location of all overload candidates designated through
7964// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007965void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007966 assert(OverloadedExpr->getType() == Context.OverloadTy);
7967
7968 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7969 OverloadExpr *OvlExpr = Ovl.Expression;
7970
7971 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7972 IEnd = OvlExpr->decls_end();
7973 I != IEnd; ++I) {
7974 if (FunctionTemplateDecl *FunTmpl =
7975 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007976 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007977 } else if (FunctionDecl *Fun
7978 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007979 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007980 }
7981 }
7982}
7983
John McCall0d1da222010-01-12 00:44:57 +00007984/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7985/// "lead" diagnostic; it will be given two arguments, the source and
7986/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007987void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7988 Sema &S,
7989 SourceLocation CaretLoc,
7990 const PartialDiagnostic &PDiag) const {
7991 S.Diag(CaretLoc, PDiag)
7992 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007993 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007994 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7995 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007996 }
John McCall12f97bc2010-01-08 04:41:39 +00007997}
7998
John McCall0d1da222010-01-12 00:44:57 +00007999namespace {
8000
John McCall6a61b522010-01-13 09:16:55 +00008001void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8002 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8003 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008004 assert(Cand->Function && "for now, candidate must be a function");
8005 FunctionDecl *Fn = Cand->Function;
8006
8007 // There's a conversion slot for the object argument if this is a
8008 // non-constructor method. Note that 'I' corresponds the
8009 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008010 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008011 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008012 if (I == 0)
8013 isObjectArgument = true;
8014 else
8015 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008016 }
8017
John McCalle1ac8d12010-01-13 00:25:19 +00008018 std::string FnDesc;
8019 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8020
John McCall6a61b522010-01-13 09:16:55 +00008021 Expr *FromExpr = Conv.Bad.FromExpr;
8022 QualType FromTy = Conv.Bad.getFromType();
8023 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008024
John McCallfb7ad0f2010-02-02 02:42:52 +00008025 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008026 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008027 Expr *E = FromExpr->IgnoreParens();
8028 if (isa<UnaryOperator>(E))
8029 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008030 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008031
8032 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8033 << (unsigned) FnKind << FnDesc
8034 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8035 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008036 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008037 return;
8038 }
8039
John McCall6d174642010-01-23 08:10:49 +00008040 // Do some hand-waving analysis to see if the non-viability is due
8041 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008042 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8043 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8044 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8045 CToTy = RT->getPointeeType();
8046 else {
8047 // TODO: detect and diagnose the full richness of const mismatches.
8048 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8049 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8050 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8051 }
8052
8053 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8054 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008055 Qualifiers FromQs = CFromTy.getQualifiers();
8056 Qualifiers ToQs = CToTy.getQualifiers();
8057
8058 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8059 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8060 << (unsigned) FnKind << FnDesc
8061 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8062 << FromTy
8063 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8064 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008065 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008066 return;
8067 }
8068
John McCall31168b02011-06-15 23:02:42 +00008069 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008070 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008071 << (unsigned) FnKind << FnDesc
8072 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8073 << FromTy
8074 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8075 << (unsigned) isObjectArgument << I+1;
8076 MaybeEmitInheritedConstructorNote(S, Fn);
8077 return;
8078 }
8079
Douglas Gregoraec25842011-04-26 23:16:46 +00008080 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8081 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8082 << (unsigned) FnKind << FnDesc
8083 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8084 << FromTy
8085 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8086 << (unsigned) isObjectArgument << I+1;
8087 MaybeEmitInheritedConstructorNote(S, Fn);
8088 return;
8089 }
8090
John McCall47000992010-01-14 03:28:57 +00008091 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8092 assert(CVR && "unexpected qualifiers mismatch");
8093
8094 if (isObjectArgument) {
8095 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8096 << (unsigned) FnKind << FnDesc
8097 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8098 << FromTy << (CVR - 1);
8099 } else {
8100 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8101 << (unsigned) FnKind << FnDesc
8102 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8103 << FromTy << (CVR - 1) << I+1;
8104 }
Sebastian Redl08905022011-02-05 19:23:19 +00008105 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008106 return;
8107 }
8108
Sebastian Redla72462c2011-09-24 17:48:32 +00008109 // Special diagnostic for failure to convert an initializer list, since
8110 // telling the user that it has type void is not useful.
8111 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8112 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8113 << (unsigned) FnKind << FnDesc
8114 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8115 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8116 MaybeEmitInheritedConstructorNote(S, Fn);
8117 return;
8118 }
8119
John McCall6d174642010-01-23 08:10:49 +00008120 // Diagnose references or pointers to incomplete types differently,
8121 // since it's far from impossible that the incompleteness triggered
8122 // the failure.
8123 QualType TempFromTy = FromTy.getNonReferenceType();
8124 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8125 TempFromTy = PTy->getPointeeType();
8126 if (TempFromTy->isIncompleteType()) {
8127 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8128 << (unsigned) FnKind << FnDesc
8129 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8130 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008131 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008132 return;
8133 }
8134
Douglas Gregor56f2e342010-06-30 23:01:39 +00008135 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008136 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008137 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8138 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8139 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8140 FromPtrTy->getPointeeType()) &&
8141 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8142 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008143 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008144 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008145 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008146 }
8147 } else if (const ObjCObjectPointerType *FromPtrTy
8148 = FromTy->getAs<ObjCObjectPointerType>()) {
8149 if (const ObjCObjectPointerType *ToPtrTy
8150 = ToTy->getAs<ObjCObjectPointerType>())
8151 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8152 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8153 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8154 FromPtrTy->getPointeeType()) &&
8155 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008156 BaseToDerivedConversion = 2;
8157 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008158 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8159 !FromTy->isIncompleteType() &&
8160 !ToRefTy->getPointeeType()->isIncompleteType() &&
8161 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8162 BaseToDerivedConversion = 3;
8163 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8164 ToTy.getNonReferenceType().getCanonicalType() ==
8165 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008166 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8167 << (unsigned) FnKind << FnDesc
8168 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8169 << (unsigned) isObjectArgument << I + 1;
8170 MaybeEmitInheritedConstructorNote(S, Fn);
8171 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008172 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008173 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008174
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008175 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008176 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008177 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008178 << (unsigned) FnKind << FnDesc
8179 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008180 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008181 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008182 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008183 return;
8184 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008185
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008186 if (isa<ObjCObjectPointerType>(CFromTy) &&
8187 isa<PointerType>(CToTy)) {
8188 Qualifiers FromQs = CFromTy.getQualifiers();
8189 Qualifiers ToQs = CToTy.getQualifiers();
8190 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8191 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8192 << (unsigned) FnKind << FnDesc
8193 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8194 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8195 MaybeEmitInheritedConstructorNote(S, Fn);
8196 return;
8197 }
8198 }
8199
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008200 // Emit the generic diagnostic and, optionally, add the hints to it.
8201 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8202 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008203 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008204 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8205 << (unsigned) (Cand->Fix.Kind);
8206
8207 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008208 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8209 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008210 FDiag << *HI;
8211 S.Diag(Fn->getLocation(), FDiag);
8212
Sebastian Redl08905022011-02-05 19:23:19 +00008213 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008214}
8215
8216void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8217 unsigned NumFormalArgs) {
8218 // TODO: treat calls to a missing default constructor as a special case
8219
8220 FunctionDecl *Fn = Cand->Function;
8221 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8222
8223 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008224
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008225 // With invalid overloaded operators, it's possible that we think we
8226 // have an arity mismatch when it fact it looks like we have the
8227 // right number of arguments, because only overloaded operators have
8228 // the weird behavior of overloading member and non-member functions.
8229 // Just don't report anything.
8230 if (Fn->isInvalidDecl() &&
8231 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8232 return;
8233
John McCall6a61b522010-01-13 09:16:55 +00008234 // at least / at most / exactly
8235 unsigned mode, modeCount;
8236 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008237 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8238 (Cand->FailureKind == ovl_fail_bad_deduction &&
8239 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008240 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00008241 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008242 mode = 0; // "at least"
8243 else
8244 mode = 2; // "exactly"
8245 modeCount = MinParams;
8246 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008247 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8248 (Cand->FailureKind == ovl_fail_bad_deduction &&
8249 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00008250 if (MinParams != FnTy->getNumArgs())
8251 mode = 1; // "at most"
8252 else
8253 mode = 2; // "exactly"
8254 modeCount = FnTy->getNumArgs();
8255 }
8256
8257 std::string Description;
8258 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8259
Richard Smith10ff50d2012-05-11 05:16:41 +00008260 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8261 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8262 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8263 << Fn->getParamDecl(0) << NumFormalArgs;
8264 else
8265 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8266 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8267 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008268 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008269}
8270
John McCall8b9ed552010-02-01 18:53:26 +00008271/// Diagnose a failed template-argument deduction.
8272void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008273 unsigned NumArgs) {
John McCall8b9ed552010-02-01 18:53:26 +00008274 FunctionDecl *Fn = Cand->Function; // pattern
8275
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008276 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008277 NamedDecl *ParamD;
8278 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8279 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8280 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00008281 switch (Cand->DeductionFailure.Result) {
8282 case Sema::TDK_Success:
8283 llvm_unreachable("TDK_success while diagnosing bad deduction");
8284
8285 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008286 assert(ParamD && "no parameter found for incomplete deduction result");
8287 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8288 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00008289 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008290 return;
8291 }
8292
John McCall42d7d192010-08-05 09:05:08 +00008293 case Sema::TDK_Underqualified: {
8294 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8295 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8296
8297 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8298
8299 // Param will have been canonicalized, but it should just be a
8300 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008301 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008302 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008303 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008304 assert(S.Context.hasSameType(Param, NonCanonParam));
8305
8306 // Arg has also been canonicalized, but there's nothing we can do
8307 // about that. It also doesn't matter as much, because it won't
8308 // have any template parameters in it (because deduction isn't
8309 // done on dependent types).
8310 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8311
8312 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8313 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00008314 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00008315 return;
8316 }
8317
8318 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008319 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008320 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008321 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008322 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008323 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008324 which = 1;
8325 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008326 which = 2;
8327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008328
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008329 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008330 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008331 << *Cand->DeductionFailure.getFirstArg()
8332 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00008333 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008334 return;
8335 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008336
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008337 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008338 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008339 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008340 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008341 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8342 << ParamD->getDeclName();
8343 else {
8344 int index = 0;
8345 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8346 index = TTP->getIndex();
8347 else if (NonTypeTemplateParmDecl *NTTP
8348 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8349 index = NTTP->getIndex();
8350 else
8351 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008352 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008353 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8354 << (index + 1);
8355 }
Sebastian Redl08905022011-02-05 19:23:19 +00008356 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008357 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008358
Douglas Gregor02eb4832010-05-08 18:13:28 +00008359 case Sema::TDK_TooManyArguments:
8360 case Sema::TDK_TooFewArguments:
8361 DiagnoseArityMismatch(S, Cand, NumArgs);
8362 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008363
8364 case Sema::TDK_InstantiationDepth:
8365 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00008366 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008367 return;
8368
8369 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00008370 // Format the template argument list into the argument string.
8371 llvm::SmallString<128> TemplateArgString;
8372 if (TemplateArgumentList *Args =
8373 Cand->DeductionFailure.getTemplateArgumentList()) {
8374 TemplateArgString = " ";
8375 TemplateArgString += S.getTemplateArgumentBindingsText(
8376 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8377 }
8378
Richard Smith6f8d2c62012-05-09 05:17:00 +00008379 // If this candidate was disabled by enable_if, say so.
8380 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8381 if (PDiag && PDiag->second.getDiagID() ==
8382 diag::err_typename_nested_not_found_enable_if) {
8383 // FIXME: Use the source range of the condition, and the fully-qualified
8384 // name of the enable_if template. These are both present in PDiag.
8385 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8386 << "'enable_if'" << TemplateArgString;
8387 return;
8388 }
8389
Richard Smith9ca64612012-05-07 09:03:25 +00008390 // Format the SFINAE diagnostic into the argument string.
8391 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8392 // formatted message in another diagnostic.
8393 llvm::SmallString<128> SFINAEArgString;
8394 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008395 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00008396 SFINAEArgString = ": ";
8397 R = SourceRange(PDiag->first, PDiag->first);
8398 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8399 }
8400
Douglas Gregord09efd42010-05-08 20:07:26 +00008401 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smith9ca64612012-05-07 09:03:25 +00008402 << TemplateArgString << SFINAEArgString << R;
Sebastian Redl08905022011-02-05 19:23:19 +00008403 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008404 return;
8405 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008406
John McCall8b9ed552010-02-01 18:53:26 +00008407 // TODO: diagnose these individually, then kill off
8408 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00008409 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00008410 case Sema::TDK_FailedOverloadResolution:
8411 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00008412 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008413 return;
8414 }
8415}
8416
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008417/// CUDA: diagnose an invalid call across targets.
8418void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8419 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8420 FunctionDecl *Callee = Cand->Function;
8421
8422 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8423 CalleeTarget = S.IdentifyCUDATarget(Callee);
8424
8425 std::string FnDesc;
8426 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8427
8428 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8429 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8430}
8431
John McCall8b9ed552010-02-01 18:53:26 +00008432/// Generates a 'note' diagnostic for an overload candidate. We've
8433/// already generated a primary error at the call site.
8434///
8435/// It really does need to be a single diagnostic with its caret
8436/// pointed at the candidate declaration. Yes, this creates some
8437/// major challenges of technical writing. Yes, this makes pointing
8438/// out problems with specific arguments quite awkward. It's still
8439/// better than generating twenty screens of text for every failed
8440/// overload.
8441///
8442/// It would be great to be able to express per-candidate problems
8443/// more richly for those diagnostic clients that cared, but we'd
8444/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00008445void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008446 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00008447 FunctionDecl *Fn = Cand->Function;
8448
John McCall12f97bc2010-01-08 04:41:39 +00008449 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008450 if (Cand->Viable && (Fn->isDeleted() ||
8451 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00008452 std::string FnDesc;
8453 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00008454
8455 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00008456 << FnKind << FnDesc
8457 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00008458 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00008459 return;
John McCall12f97bc2010-01-08 04:41:39 +00008460 }
8461
John McCalle1ac8d12010-01-13 00:25:19 +00008462 // We don't really have anything else to say about viable candidates.
8463 if (Cand->Viable) {
8464 S.NoteOverloadCandidate(Fn);
8465 return;
8466 }
John McCall0d1da222010-01-12 00:44:57 +00008467
John McCall6a61b522010-01-13 09:16:55 +00008468 switch (Cand->FailureKind) {
8469 case ovl_fail_too_many_arguments:
8470 case ovl_fail_too_few_arguments:
8471 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00008472
John McCall6a61b522010-01-13 09:16:55 +00008473 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008474 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00008475
John McCallfe796dd2010-01-23 05:17:32 +00008476 case ovl_fail_trivial_conversion:
8477 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00008478 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00008479 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008480
John McCall65eb8792010-02-25 01:37:24 +00008481 case ovl_fail_bad_conversion: {
8482 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008483 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00008484 if (Cand->Conversions[I].isBad())
8485 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008486
John McCall6a61b522010-01-13 09:16:55 +00008487 // FIXME: this currently happens when we're called from SemaInit
8488 // when user-conversion overload fails. Figure out how to handle
8489 // those conditions and diagnose them well.
8490 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008491 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008492
8493 case ovl_fail_bad_target:
8494 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00008495 }
John McCalld3224162010-01-08 00:58:21 +00008496}
8497
8498void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8499 // Desugar the type of the surrogate down to a function type,
8500 // retaining as many typedefs as possible while still showing
8501 // the function type (and, therefore, its parameter types).
8502 QualType FnType = Cand->Surrogate->getConversionType();
8503 bool isLValueReference = false;
8504 bool isRValueReference = false;
8505 bool isPointer = false;
8506 if (const LValueReferenceType *FnTypeRef =
8507 FnType->getAs<LValueReferenceType>()) {
8508 FnType = FnTypeRef->getPointeeType();
8509 isLValueReference = true;
8510 } else if (const RValueReferenceType *FnTypeRef =
8511 FnType->getAs<RValueReferenceType>()) {
8512 FnType = FnTypeRef->getPointeeType();
8513 isRValueReference = true;
8514 }
8515 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8516 FnType = FnTypePtr->getPointeeType();
8517 isPointer = true;
8518 }
8519 // Desugar down to a function type.
8520 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8521 // Reconstruct the pointer/reference as appropriate.
8522 if (isPointer) FnType = S.Context.getPointerType(FnType);
8523 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8524 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8525
8526 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8527 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00008528 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00008529}
8530
8531void NoteBuiltinOperatorCandidate(Sema &S,
8532 const char *Opc,
8533 SourceLocation OpLoc,
8534 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008535 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00008536 std::string TypeStr("operator");
8537 TypeStr += Opc;
8538 TypeStr += "(";
8539 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00008540 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00008541 TypeStr += ")";
8542 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8543 } else {
8544 TypeStr += ", ";
8545 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8546 TypeStr += ")";
8547 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8548 }
8549}
8550
8551void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8552 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008553 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00008554 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8555 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00008556 if (ICS.isBad()) break; // all meaningless after first invalid
8557 if (!ICS.isAmbiguous()) continue;
8558
John McCall5c32be02010-08-24 20:38:10 +00008559 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008560 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00008561 }
8562}
8563
John McCall3712d9e2010-01-15 23:32:50 +00008564SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8565 if (Cand->Function)
8566 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00008567 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00008568 return Cand->Surrogate->getLocation();
8569 return SourceLocation();
8570}
8571
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008572static unsigned
8573RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00008574 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008575 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00008576 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008577
Douglas Gregorc5c01a62012-09-13 21:01:57 +00008578 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008579 case Sema::TDK_Incomplete:
8580 return 1;
8581
8582 case Sema::TDK_Underqualified:
8583 case Sema::TDK_Inconsistent:
8584 return 2;
8585
8586 case Sema::TDK_SubstitutionFailure:
8587 case Sema::TDK_NonDeducedMismatch:
8588 return 3;
8589
8590 case Sema::TDK_InstantiationDepth:
8591 case Sema::TDK_FailedOverloadResolution:
8592 return 4;
8593
8594 case Sema::TDK_InvalidExplicitArguments:
8595 return 5;
8596
8597 case Sema::TDK_TooManyArguments:
8598 case Sema::TDK_TooFewArguments:
8599 return 6;
8600 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008601 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008602}
8603
John McCallad2587a2010-01-12 00:48:53 +00008604struct CompareOverloadCandidatesForDisplay {
8605 Sema &S;
8606 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00008607
8608 bool operator()(const OverloadCandidate *L,
8609 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00008610 // Fast-path this check.
8611 if (L == R) return false;
8612
John McCall12f97bc2010-01-08 04:41:39 +00008613 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00008614 if (L->Viable) {
8615 if (!R->Viable) return true;
8616
8617 // TODO: introduce a tri-valued comparison for overload
8618 // candidates. Would be more worthwhile if we had a sort
8619 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00008620 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8621 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00008622 } else if (R->Viable)
8623 return false;
John McCall12f97bc2010-01-08 04:41:39 +00008624
John McCall3712d9e2010-01-15 23:32:50 +00008625 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00008626
John McCall3712d9e2010-01-15 23:32:50 +00008627 // Criteria by which we can sort non-viable candidates:
8628 if (!L->Viable) {
8629 // 1. Arity mismatches come after other candidates.
8630 if (L->FailureKind == ovl_fail_too_many_arguments ||
8631 L->FailureKind == ovl_fail_too_few_arguments)
8632 return false;
8633 if (R->FailureKind == ovl_fail_too_many_arguments ||
8634 R->FailureKind == ovl_fail_too_few_arguments)
8635 return true;
John McCall12f97bc2010-01-08 04:41:39 +00008636
John McCallfe796dd2010-01-23 05:17:32 +00008637 // 2. Bad conversions come first and are ordered by the number
8638 // of bad conversions and quality of good conversions.
8639 if (L->FailureKind == ovl_fail_bad_conversion) {
8640 if (R->FailureKind != ovl_fail_bad_conversion)
8641 return true;
8642
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008643 // The conversion that can be fixed with a smaller number of changes,
8644 // comes first.
8645 unsigned numLFixes = L->Fix.NumConversionsFixed;
8646 unsigned numRFixes = R->Fix.NumConversionsFixed;
8647 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8648 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008649 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008650 if (numLFixes < numRFixes)
8651 return true;
8652 else
8653 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008654 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008655
John McCallfe796dd2010-01-23 05:17:32 +00008656 // If there's any ordering between the defined conversions...
8657 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00008658 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00008659
8660 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00008661 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008662 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00008663 switch (CompareImplicitConversionSequences(S,
8664 L->Conversions[I],
8665 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00008666 case ImplicitConversionSequence::Better:
8667 leftBetter++;
8668 break;
8669
8670 case ImplicitConversionSequence::Worse:
8671 leftBetter--;
8672 break;
8673
8674 case ImplicitConversionSequence::Indistinguishable:
8675 break;
8676 }
8677 }
8678 if (leftBetter > 0) return true;
8679 if (leftBetter < 0) return false;
8680
8681 } else if (R->FailureKind == ovl_fail_bad_conversion)
8682 return false;
8683
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008684 if (L->FailureKind == ovl_fail_bad_deduction) {
8685 if (R->FailureKind != ovl_fail_bad_deduction)
8686 return true;
8687
8688 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8689 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00008690 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00008691 } else if (R->FailureKind == ovl_fail_bad_deduction)
8692 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008693
John McCall3712d9e2010-01-15 23:32:50 +00008694 // TODO: others?
8695 }
8696
8697 // Sort everything else by location.
8698 SourceLocation LLoc = GetLocationForCandidate(L);
8699 SourceLocation RLoc = GetLocationForCandidate(R);
8700
8701 // Put candidates without locations (e.g. builtins) at the end.
8702 if (LLoc.isInvalid()) return false;
8703 if (RLoc.isInvalid()) return true;
8704
8705 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00008706 }
8707};
8708
John McCallfe796dd2010-01-23 05:17:32 +00008709/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008710/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00008711void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008712 llvm::ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00008713 assert(!Cand->Viable);
8714
8715 // Don't do anything on failures other than bad conversion.
8716 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8717
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008718 // We only want the FixIts if all the arguments can be corrected.
8719 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00008720 // Use a implicit copy initialization to check conversion fixes.
8721 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008722
John McCallfe796dd2010-01-23 05:17:32 +00008723 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00008724 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008725 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00008726 while (true) {
8727 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8728 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008729 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00008730 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00008731 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008732 }
John McCallfe796dd2010-01-23 05:17:32 +00008733 }
8734
8735 if (ConvIdx == ConvCount)
8736 return;
8737
John McCall65eb8792010-02-25 01:37:24 +00008738 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8739 "remaining conversion is initialized?");
8740
Douglas Gregoradc7a702010-04-16 17:45:54 +00008741 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00008742 // operation somehow.
8743 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00008744
8745 const FunctionProtoType* Proto;
8746 unsigned ArgIdx = ConvIdx;
8747
8748 if (Cand->IsSurrogate) {
8749 QualType ConvType
8750 = Cand->Surrogate->getConversionType().getNonReferenceType();
8751 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8752 ConvType = ConvPtrType->getPointeeType();
8753 Proto = ConvType->getAs<FunctionProtoType>();
8754 ArgIdx--;
8755 } else if (Cand->Function) {
8756 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8757 if (isa<CXXMethodDecl>(Cand->Function) &&
8758 !isa<CXXConstructorDecl>(Cand->Function))
8759 ArgIdx--;
8760 } else {
8761 // Builtin binary operator with a bad first conversion.
8762 assert(ConvCount <= 3);
8763 for (; ConvIdx != ConvCount; ++ConvIdx)
8764 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008765 = TryCopyInitialization(S, Args[ConvIdx],
8766 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008767 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008768 /*InOverloadResolution*/ true,
8769 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008770 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008771 return;
8772 }
8773
8774 // Fill in the rest of the conversions.
8775 unsigned NumArgsInProto = Proto->getNumArgs();
8776 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008777 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008778 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008779 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008780 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008781 /*InOverloadResolution=*/true,
8782 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008783 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008784 // Store the FixIt in the candidate if it exists.
8785 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008786 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008787 }
John McCallfe796dd2010-01-23 05:17:32 +00008788 else
8789 Cand->Conversions[ConvIdx].setEllipsis();
8790 }
8791}
8792
John McCalld3224162010-01-08 00:58:21 +00008793} // end anonymous namespace
8794
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008795/// PrintOverloadCandidates - When overload resolution fails, prints
8796/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008797/// set.
John McCall5c32be02010-08-24 20:38:10 +00008798void OverloadCandidateSet::NoteCandidates(Sema &S,
8799 OverloadCandidateDisplayKind OCD,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008800 llvm::ArrayRef<Expr *> Args,
John McCall5c32be02010-08-24 20:38:10 +00008801 const char *Opc,
8802 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008803 // Sort the candidates by viability and position. Sorting directly would
8804 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008805 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008806 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8807 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008808 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008809 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008810 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008811 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008812 if (Cand->Function || Cand->IsSurrogate)
8813 Cands.push_back(Cand);
8814 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8815 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008816 }
8817 }
8818
John McCallad2587a2010-01-12 00:48:53 +00008819 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008820 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008821
John McCall0d1da222010-01-12 00:44:57 +00008822 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008823
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008824 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008825 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8826 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008827 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008828 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8829 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008830
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008831 // Set an arbitrary limit on the number of candidate functions we'll spam
8832 // the user with. FIXME: This limit should depend on details of the
8833 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008834 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008835 break;
8836 }
8837 ++CandsShown;
8838
John McCalld3224162010-01-08 00:58:21 +00008839 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008840 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00008841 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008842 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008843 else {
8844 assert(Cand->Viable &&
8845 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008846 // Generally we only see ambiguities including viable builtin
8847 // operators if overload resolution got screwed up by an
8848 // ambiguous user-defined conversion.
8849 //
8850 // FIXME: It's quite possible for different conversions to see
8851 // different ambiguities, though.
8852 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008853 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008854 ReportedAmbiguousConversions = true;
8855 }
John McCalld3224162010-01-08 00:58:21 +00008856
John McCall0d1da222010-01-12 00:44:57 +00008857 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008858 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008859 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008860 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008861
8862 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008863 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008864}
8865
Douglas Gregorb491ed32011-02-19 21:32:49 +00008866// [PossiblyAFunctionType] --> [Return]
8867// NonFunctionType --> NonFunctionType
8868// R (A) --> R(A)
8869// R (*)(A) --> R (A)
8870// R (&)(A) --> R (A)
8871// R (S::*)(A) --> R (A)
8872QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8873 QualType Ret = PossiblyAFunctionType;
8874 if (const PointerType *ToTypePtr =
8875 PossiblyAFunctionType->getAs<PointerType>())
8876 Ret = ToTypePtr->getPointeeType();
8877 else if (const ReferenceType *ToTypeRef =
8878 PossiblyAFunctionType->getAs<ReferenceType>())
8879 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008880 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008881 PossiblyAFunctionType->getAs<MemberPointerType>())
8882 Ret = MemTypePtr->getPointeeType();
8883 Ret =
8884 Context.getCanonicalType(Ret).getUnqualifiedType();
8885 return Ret;
8886}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008887
Douglas Gregorb491ed32011-02-19 21:32:49 +00008888// A helper class to help with address of function resolution
8889// - allows us to avoid passing around all those ugly parameters
8890class AddressOfFunctionResolver
8891{
8892 Sema& S;
8893 Expr* SourceExpr;
8894 const QualType& TargetType;
8895 QualType TargetFunctionType; // Extracted function type from target type
8896
8897 bool Complain;
8898 //DeclAccessPair& ResultFunctionAccessPair;
8899 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008900
Douglas Gregorb491ed32011-02-19 21:32:49 +00008901 bool TargetTypeIsNonStaticMemberFunction;
8902 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008903
Douglas Gregorb491ed32011-02-19 21:32:49 +00008904 OverloadExpr::FindResult OvlExprInfo;
8905 OverloadExpr *OvlExpr;
8906 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008907 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008908
Douglas Gregorb491ed32011-02-19 21:32:49 +00008909public:
8910 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8911 const QualType& TargetType, bool Complain)
8912 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8913 Complain(Complain), Context(S.getASTContext()),
8914 TargetTypeIsNonStaticMemberFunction(
8915 !!TargetType->getAs<MemberPointerType>()),
8916 FoundNonTemplateFunction(false),
8917 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8918 OvlExpr(OvlExprInfo.Expression)
8919 {
8920 ExtractUnqualifiedFunctionTypeFromTargetType();
8921
8922 if (!TargetFunctionType->isFunctionType()) {
8923 if (OvlExpr->hasExplicitTemplateArgs()) {
8924 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008925 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008926 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008927
8928 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8929 if (!Method->isStatic()) {
8930 // If the target type is a non-function type and the function
8931 // found is a non-static member function, pretend as if that was
8932 // the target, it's the only possible type to end up with.
8933 TargetTypeIsNonStaticMemberFunction = true;
8934
8935 // And skip adding the function if its not in the proper form.
8936 // We'll diagnose this due to an empty set of functions.
8937 if (!OvlExprInfo.HasFormOfMemberPointer)
8938 return;
8939 }
8940 }
8941
Douglas Gregorb491ed32011-02-19 21:32:49 +00008942 Matches.push_back(std::make_pair(dap,Fn));
8943 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008944 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008945 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008946 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008947
8948 if (OvlExpr->hasExplicitTemplateArgs())
8949 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008950
Douglas Gregorb491ed32011-02-19 21:32:49 +00008951 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8952 // C++ [over.over]p4:
8953 // If more than one function is selected, [...]
8954 if (Matches.size() > 1) {
8955 if (FoundNonTemplateFunction)
8956 EliminateAllTemplateMatches();
8957 else
8958 EliminateAllExceptMostSpecializedTemplate();
8959 }
8960 }
8961 }
8962
8963private:
8964 bool isTargetTypeAFunction() const {
8965 return TargetFunctionType->isFunctionType();
8966 }
8967
8968 // [ToType] [Return]
8969
8970 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8971 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8972 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8973 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8974 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8975 }
8976
8977 // return true if any matching specializations were found
8978 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8979 const DeclAccessPair& CurAccessFunPair) {
8980 if (CXXMethodDecl *Method
8981 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8982 // Skip non-static function templates when converting to pointer, and
8983 // static when converting to member pointer.
8984 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8985 return false;
8986 }
8987 else if (TargetTypeIsNonStaticMemberFunction)
8988 return false;
8989
8990 // C++ [over.over]p2:
8991 // If the name is a function template, template argument deduction is
8992 // done (14.8.2.2), and if the argument deduction succeeds, the
8993 // resulting template argument list is used to generate a single
8994 // function template specialization, which is added to the set of
8995 // overloaded functions considered.
8996 FunctionDecl *Specialization = 0;
8997 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8998 if (Sema::TemplateDeductionResult Result
8999 = S.DeduceTemplateArguments(FunctionTemplate,
9000 &OvlExplicitTemplateArgs,
9001 TargetFunctionType, Specialization,
9002 Info)) {
9003 // FIXME: make a note of the failed deduction for diagnostics.
9004 (void)Result;
9005 return false;
9006 }
9007
9008 // Template argument deduction ensures that we have an exact match.
9009 // This function template specicalization works.
9010 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9011 assert(TargetFunctionType
9012 == Context.getCanonicalType(Specialization->getType()));
9013 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9014 return true;
9015 }
9016
9017 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9018 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009019 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009020 // Skip non-static functions when converting to pointer, and static
9021 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009022 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9023 return false;
9024 }
9025 else if (TargetTypeIsNonStaticMemberFunction)
9026 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009027
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009028 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009029 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009030 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9031 if (S.CheckCUDATarget(Caller, FunDecl))
9032 return false;
9033
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009034 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009035 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9036 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009037 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9038 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009039 Matches.push_back(std::make_pair(CurAccessFunPair,
9040 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009041 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009042 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009043 }
Mike Stump11289f42009-09-09 15:08:12 +00009044 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009045
9046 return false;
9047 }
9048
9049 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9050 bool Ret = false;
9051
9052 // If the overload expression doesn't have the form of a pointer to
9053 // member, don't try to convert it to a pointer-to-member type.
9054 if (IsInvalidFormOfPointerToMemberFunction())
9055 return false;
9056
9057 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9058 E = OvlExpr->decls_end();
9059 I != E; ++I) {
9060 // Look through any using declarations to find the underlying function.
9061 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9062
9063 // C++ [over.over]p3:
9064 // Non-member functions and static member functions match
9065 // targets of type "pointer-to-function" or "reference-to-function."
9066 // Nonstatic member functions match targets of
9067 // type "pointer-to-member-function."
9068 // Note that according to DR 247, the containing class does not matter.
9069 if (FunctionTemplateDecl *FunctionTemplate
9070 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9071 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9072 Ret = true;
9073 }
9074 // If we have explicit template arguments supplied, skip non-templates.
9075 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9076 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9077 Ret = true;
9078 }
9079 assert(Ret || Matches.empty());
9080 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009081 }
9082
Douglas Gregorb491ed32011-02-19 21:32:49 +00009083 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00009084 // [...] and any given function template specialization F1 is
9085 // eliminated if the set contains a second function template
9086 // specialization whose function template is more specialized
9087 // than the function template of F1 according to the partial
9088 // ordering rules of 14.5.5.2.
9089
9090 // The algorithm specified above is quadratic. We instead use a
9091 // two-pass algorithm (similar to the one used to identify the
9092 // best viable function in an overload set) that identifies the
9093 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00009094
9095 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9096 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9097 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009098
John McCall58cc69d2010-01-27 01:50:18 +00009099 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009100 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9101 TPOC_Other, 0, SourceExpr->getLocStart(),
9102 S.PDiag(),
9103 S.PDiag(diag::err_addr_ovl_ambiguous)
9104 << Matches[0].second->getDeclName(),
9105 S.PDiag(diag::note_ovl_candidate)
9106 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00009107 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009108
Douglas Gregorb491ed32011-02-19 21:32:49 +00009109 if (Result != MatchesCopy.end()) {
9110 // Make it the first and only element
9111 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9112 Matches[0].second = cast<FunctionDecl>(*Result);
9113 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00009114 }
9115 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009116
Douglas Gregorb491ed32011-02-19 21:32:49 +00009117 void EliminateAllTemplateMatches() {
9118 // [...] any function template specializations in the set are
9119 // eliminated if the set also contains a non-template function, [...]
9120 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9121 if (Matches[I].second->getPrimaryTemplate() == 0)
9122 ++I;
9123 else {
9124 Matches[I] = Matches[--N];
9125 Matches.set_size(N);
9126 }
9127 }
9128 }
9129
9130public:
9131 void ComplainNoMatchesFound() const {
9132 assert(Matches.empty());
9133 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9134 << OvlExpr->getName() << TargetFunctionType
9135 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009136 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009137 }
9138
9139 bool IsInvalidFormOfPointerToMemberFunction() const {
9140 return TargetTypeIsNonStaticMemberFunction &&
9141 !OvlExprInfo.HasFormOfMemberPointer;
9142 }
9143
9144 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9145 // TODO: Should we condition this on whether any functions might
9146 // have matched, or is it more appropriate to do that in callers?
9147 // TODO: a fixit wouldn't hurt.
9148 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9149 << TargetType << OvlExpr->getSourceRange();
9150 }
9151
9152 void ComplainOfInvalidConversion() const {
9153 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9154 << OvlExpr->getName() << TargetType;
9155 }
9156
9157 void ComplainMultipleMatchesFound() const {
9158 assert(Matches.size() > 1);
9159 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9160 << OvlExpr->getName()
9161 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009162 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009163 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009164
9165 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9166
Douglas Gregorb491ed32011-02-19 21:32:49 +00009167 int getNumMatches() const { return Matches.size(); }
9168
9169 FunctionDecl* getMatchingFunctionDecl() const {
9170 if (Matches.size() != 1) return 0;
9171 return Matches[0].second;
9172 }
9173
9174 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9175 if (Matches.size() != 1) return 0;
9176 return &Matches[0].first;
9177 }
9178};
9179
9180/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9181/// an overloaded function (C++ [over.over]), where @p From is an
9182/// expression with overloaded function type and @p ToType is the type
9183/// we're trying to resolve to. For example:
9184///
9185/// @code
9186/// int f(double);
9187/// int f(int);
9188///
9189/// int (*pfd)(double) = f; // selects f(double)
9190/// @endcode
9191///
9192/// This routine returns the resulting FunctionDecl if it could be
9193/// resolved, and NULL otherwise. When @p Complain is true, this
9194/// routine will emit diagnostics if there is an error.
9195FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009196Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9197 QualType TargetType,
9198 bool Complain,
9199 DeclAccessPair &FoundResult,
9200 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009201 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009202
9203 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9204 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009205 int NumMatches = Resolver.getNumMatches();
9206 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009207 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009208 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9209 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9210 else
9211 Resolver.ComplainNoMatchesFound();
9212 }
9213 else if (NumMatches > 1 && Complain)
9214 Resolver.ComplainMultipleMatchesFound();
9215 else if (NumMatches == 1) {
9216 Fn = Resolver.getMatchingFunctionDecl();
9217 assert(Fn);
9218 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedmanfa0df832012-02-02 03:46:19 +00009219 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00009220 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00009221 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00009222 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009223
9224 if (pHadMultipleCandidates)
9225 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009226 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009227}
9228
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009229/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009230/// resolve that overloaded function expression down to a single function.
9231///
9232/// This routine can only resolve template-ids that refer to a single function
9233/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009234/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009235/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00009236FunctionDecl *
9237Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9238 bool Complain,
9239 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009240 // C++ [over.over]p1:
9241 // [...] [Note: any redundant set of parentheses surrounding the
9242 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009243 // C++ [over.over]p1:
9244 // [...] The overloaded function name can be preceded by the &
9245 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009246
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009247 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009248 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009249 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009250
9251 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009252 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009253
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009254 // Look through all of the overloaded functions, searching for one
9255 // whose type matches exactly.
9256 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009257 for (UnresolvedSetIterator I = ovl->decls_begin(),
9258 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009259 // C++0x [temp.arg.explicit]p3:
9260 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009261 // where deduction is not done, if a template argument list is
9262 // specified and it, along with any default template arguments,
9263 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009264 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009265 FunctionTemplateDecl *FunctionTemplate
9266 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009267
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009268 // C++ [over.over]p2:
9269 // If the name is a function template, template argument deduction is
9270 // done (14.8.2.2), and if the argument deduction succeeds, the
9271 // resulting template argument list is used to generate a single
9272 // function template specialization, which is added to the set of
9273 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009274 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009275 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009276 if (TemplateDeductionResult Result
9277 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9278 Specialization, Info)) {
9279 // FIXME: make a note of the failed deduction for diagnostics.
9280 (void)Result;
9281 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009282 }
9283
John McCall0009fcc2011-04-26 20:42:42 +00009284 assert(Specialization && "no specialization and no error?");
9285
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009286 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009287 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009288 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00009289 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9290 << ovl->getName();
9291 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009292 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009293 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00009294 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009295
John McCall0009fcc2011-04-26 20:42:42 +00009296 Matched = Specialization;
9297 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009298 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009299
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009300 return Matched;
9301}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009302
Douglas Gregor1beec452011-03-12 01:48:56 +00009303
9304
9305
John McCall50a2c2c2011-10-11 23:14:30 +00009306// Resolve and fix an overloaded expression that can be resolved
9307// because it identifies a single function template specialization.
9308//
Douglas Gregor1beec452011-03-12 01:48:56 +00009309// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00009310//
9311// Return true if it was logically possible to so resolve the
9312// expression, regardless of whether or not it succeeded. Always
9313// returns true if 'complain' is set.
9314bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9315 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9316 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00009317 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00009318 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00009319 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00009320
John McCall50a2c2c2011-10-11 23:14:30 +00009321 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00009322
John McCall0009fcc2011-04-26 20:42:42 +00009323 DeclAccessPair found;
9324 ExprResult SingleFunctionExpression;
9325 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9326 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009327 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +00009328 SrcExpr = ExprError();
9329 return true;
9330 }
John McCall0009fcc2011-04-26 20:42:42 +00009331
9332 // It is only correct to resolve to an instance method if we're
9333 // resolving a form that's permitted to be a pointer to member.
9334 // Otherwise we'll end up making a bound member expression, which
9335 // is illegal in all the contexts we resolve like this.
9336 if (!ovl.HasFormOfMemberPointer &&
9337 isa<CXXMethodDecl>(fn) &&
9338 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00009339 if (!complain) return false;
9340
9341 Diag(ovl.Expression->getExprLoc(),
9342 diag::err_bound_member_function)
9343 << 0 << ovl.Expression->getSourceRange();
9344
9345 // TODO: I believe we only end up here if there's a mix of
9346 // static and non-static candidates (otherwise the expression
9347 // would have 'bound member' type, not 'overload' type).
9348 // Ideally we would note which candidate was chosen and why
9349 // the static candidates were rejected.
9350 SrcExpr = ExprError();
9351 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009352 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009353
Sylvestre Ledrua5202662012-07-31 06:56:50 +00009354 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +00009355 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00009356 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00009357
9358 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00009359 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00009360 SingleFunctionExpression =
9361 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00009362 if (SingleFunctionExpression.isInvalid()) {
9363 SrcExpr = ExprError();
9364 return true;
9365 }
9366 }
John McCall0009fcc2011-04-26 20:42:42 +00009367 }
9368
9369 if (!SingleFunctionExpression.isUsable()) {
9370 if (complain) {
9371 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9372 << ovl.Expression->getName()
9373 << DestTypeForComplaining
9374 << OpRangeForComplaining
9375 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00009376 NoteAllOverloadCandidates(SrcExpr.get());
9377
9378 SrcExpr = ExprError();
9379 return true;
9380 }
9381
9382 return false;
John McCall0009fcc2011-04-26 20:42:42 +00009383 }
9384
John McCall50a2c2c2011-10-11 23:14:30 +00009385 SrcExpr = SingleFunctionExpression;
9386 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009387}
9388
Douglas Gregorcabea402009-09-22 15:41:20 +00009389/// \brief Add a single candidate to the overload set.
9390static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00009391 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00009392 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009393 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009394 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00009395 bool PartialOverloading,
9396 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00009397 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00009398 if (isa<UsingShadowDecl>(Callee))
9399 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9400
Douglas Gregorcabea402009-09-22 15:41:20 +00009401 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00009402 if (ExplicitTemplateArgs) {
9403 assert(!KnownValid && "Explicit template arguments?");
9404 return;
9405 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009406 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9407 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009408 return;
John McCalld14a8642009-11-21 08:51:07 +00009409 }
9410
9411 if (FunctionTemplateDecl *FuncTemplate
9412 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00009413 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009414 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00009415 return;
9416 }
9417
Richard Smith95ce4f62011-06-26 22:19:54 +00009418 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00009419}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009420
Douglas Gregorcabea402009-09-22 15:41:20 +00009421/// \brief Add the overload candidates named by callee and/or found by argument
9422/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00009423void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009424 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009425 OverloadCandidateSet &CandidateSet,
9426 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00009427
9428#ifndef NDEBUG
9429 // Verify that ArgumentDependentLookup is consistent with the rules
9430 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00009431 //
Douglas Gregorcabea402009-09-22 15:41:20 +00009432 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9433 // and let Y be the lookup set produced by argument dependent
9434 // lookup (defined as follows). If X contains
9435 //
9436 // -- a declaration of a class member, or
9437 //
9438 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00009439 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00009440 //
9441 // -- a declaration that is neither a function or a function
9442 // template
9443 //
9444 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00009445
John McCall57500772009-12-16 12:17:52 +00009446 if (ULE->requiresADL()) {
9447 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9448 E = ULE->decls_end(); I != E; ++I) {
9449 assert(!(*I)->getDeclContext()->isRecord());
9450 assert(isa<UsingShadowDecl>(*I) ||
9451 !(*I)->getDeclContext()->isFunctionOrMethod());
9452 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00009453 }
9454 }
9455#endif
9456
John McCall57500772009-12-16 12:17:52 +00009457 // It would be nice to avoid this copy.
9458 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00009459 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009460 if (ULE->hasExplicitTemplateArgs()) {
9461 ULE->copyTemplateArgumentsInto(TABuffer);
9462 ExplicitTemplateArgs = &TABuffer;
9463 }
9464
9465 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9466 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009467 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9468 CandidateSet, PartialOverloading,
9469 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00009470
John McCall57500772009-12-16 12:17:52 +00009471 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00009472 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +00009473 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009474 Args, ExplicitTemplateArgs,
9475 CandidateSet, PartialOverloading,
Richard Smith02e85f32011-04-14 22:09:26 +00009476 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00009477}
John McCalld681c392009-12-16 08:11:27 +00009478
Richard Smith998a5912011-06-05 22:42:48 +00009479/// Attempt to recover from an ill-formed use of a non-dependent name in a
9480/// template, where the non-dependent name was declared after the template
9481/// was defined. This is common in code written for a compilers which do not
9482/// correctly implement two-stage name lookup.
9483///
9484/// Returns true if a viable candidate was found and a diagnostic was issued.
9485static bool
9486DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9487 const CXXScopeSpec &SS, LookupResult &R,
9488 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009489 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009490 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9491 return false;
9492
9493 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +00009494 if (DC->isTransparentContext())
9495 continue;
9496
Richard Smith998a5912011-06-05 22:42:48 +00009497 SemaRef.LookupQualifiedName(R, DC);
9498
9499 if (!R.empty()) {
9500 R.suppressDiagnostics();
9501
9502 if (isa<CXXRecordDecl>(DC)) {
9503 // Don't diagnose names we find in classes; we get much better
9504 // diagnostics for these from DiagnoseEmptyLookup.
9505 R.clear();
9506 return false;
9507 }
9508
9509 OverloadCandidateSet Candidates(FnLoc);
9510 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9511 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009512 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +00009513 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00009514
9515 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00009516 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00009517 // No viable functions. Don't bother the user with notes for functions
9518 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00009519 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00009520 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00009521 }
Richard Smith998a5912011-06-05 22:42:48 +00009522
9523 // Find the namespaces where ADL would have looked, and suggest
9524 // declaring the function there instead.
9525 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9526 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00009527 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +00009528 AssociatedNamespaces,
9529 AssociatedClasses);
9530 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00009531 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009532 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00009533 for (Sema::AssociatedNamespaceSet::iterator
9534 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00009535 end = AssociatedNamespaces.end(); it != end; ++it) {
9536 if (!Std->Encloses(*it))
9537 SuggestedNamespaces.insert(*it);
9538 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00009539 } else {
9540 // Lacking the 'std::' namespace, use all of the associated namespaces.
9541 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00009542 }
9543
9544 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9545 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00009546 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00009547 SemaRef.Diag(Best->Function->getLocation(),
9548 diag::note_not_found_by_two_phase_lookup)
9549 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00009550 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00009551 SemaRef.Diag(Best->Function->getLocation(),
9552 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00009553 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00009554 } else {
9555 // FIXME: It would be useful to list the associated namespaces here,
9556 // but the diagnostics infrastructure doesn't provide a way to produce
9557 // a localized representation of a list of items.
9558 SemaRef.Diag(Best->Function->getLocation(),
9559 diag::note_not_found_by_two_phase_lookup)
9560 << R.getLookupName() << 2;
9561 }
9562
9563 // Try to recover by calling this function.
9564 return true;
9565 }
9566
9567 R.clear();
9568 }
9569
9570 return false;
9571}
9572
9573/// Attempt to recover from ill-formed use of a non-dependent operator in a
9574/// template, where the non-dependent operator was declared after the template
9575/// was defined.
9576///
9577/// Returns true if a viable candidate was found and a diagnostic was issued.
9578static bool
9579DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9580 SourceLocation OpLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009581 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009582 DeclarationName OpName =
9583 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9584 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9585 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009586 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +00009587}
9588
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009589namespace {
9590// Callback to limit the allowed keywords and to only accept typo corrections
9591// that are keywords or whose decls refer to functions (or template functions)
9592// that accept the given number of arguments.
9593class RecoveryCallCCC : public CorrectionCandidateCallback {
9594 public:
9595 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9596 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009597 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009598 WantRemainingKeywords = false;
9599 }
9600
9601 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9602 if (!candidate.getCorrectionDecl())
9603 return candidate.isKeyword();
9604
9605 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9606 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9607 FunctionDecl *FD = 0;
9608 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9609 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9610 FD = FTD->getTemplatedDecl();
9611 if (!HasExplicitTemplateArgs && !FD) {
9612 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9613 // If the Decl is neither a function nor a template function,
9614 // determine if it is a pointer or reference to a function. If so,
9615 // check against the number of arguments expected for the pointee.
9616 QualType ValType = cast<ValueDecl>(ND)->getType();
9617 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9618 ValType = ValType->getPointeeType();
9619 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9620 if (FPT->getNumArgs() == NumArgs)
9621 return true;
9622 }
9623 }
9624 if (FD && FD->getNumParams() >= NumArgs &&
9625 FD->getMinRequiredArguments() <= NumArgs)
9626 return true;
9627 }
9628 return false;
9629 }
9630
9631 private:
9632 unsigned NumArgs;
9633 bool HasExplicitTemplateArgs;
9634};
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009635
9636// Callback that effectively disabled typo correction
9637class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9638 public:
9639 NoTypoCorrectionCCC() {
9640 WantTypeSpecifiers = false;
9641 WantExpressionKeywords = false;
9642 WantCXXNamedCasts = false;
9643 WantRemainingKeywords = false;
9644 }
9645
9646 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9647 return false;
9648 }
9649};
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009650}
9651
John McCalld681c392009-12-16 08:11:27 +00009652/// Attempts to recover from a call where no functions were found.
9653///
9654/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00009655static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009656BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00009657 UnresolvedLookupExpr *ULE,
9658 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009659 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +00009660 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009661 bool EmptyLookup, bool AllowTypoCorrection) {
John McCalld681c392009-12-16 08:11:27 +00009662
9663 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00009664 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00009665 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +00009666
John McCall57500772009-12-16 12:17:52 +00009667 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00009668 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009669 if (ULE->hasExplicitTemplateArgs()) {
9670 ULE->copyTemplateArgumentsInto(TABuffer);
9671 ExplicitTemplateArgs = &TABuffer;
9672 }
9673
John McCalld681c392009-12-16 08:11:27 +00009674 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9675 Sema::LookupOrdinaryName);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009676 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009677 NoTypoCorrectionCCC RejectAll;
9678 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9679 (CorrectionCandidateCallback*)&Validator :
9680 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +00009681 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009682 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +00009683 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009684 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009685 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +00009686 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00009687
John McCall57500772009-12-16 12:17:52 +00009688 assert(!R.empty() && "lookup results empty despite recovery");
9689
9690 // Build an implicit member call if appropriate. Just drop the
9691 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00009692 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00009693 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009694 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9695 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009696 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009697 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009698 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00009699 else
9700 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9701
9702 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009703 return ExprError();
John McCall57500772009-12-16 12:17:52 +00009704
9705 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00009706 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00009707 // end up here.
John McCallb268a282010-08-23 23:25:46 +00009708 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009709 MultiExprArg(Args.data(), Args.size()),
9710 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00009711}
Douglas Gregor4038cf42010-06-08 17:35:15 +00009712
Sam Panzer0f384432012-08-21 00:52:01 +00009713/// \brief Constructs and populates an OverloadedCandidateSet from
9714/// the given function.
9715/// \returns true when an the ExprResult output parameter has been set.
9716bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9717 UnresolvedLookupExpr *ULE,
9718 Expr **Args, unsigned NumArgs,
9719 SourceLocation RParenLoc,
9720 OverloadCandidateSet *CandidateSet,
9721 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +00009722#ifndef NDEBUG
9723 if (ULE->requiresADL()) {
9724 // To do ADL, we must have found an unqualified name.
9725 assert(!ULE->getQualifier() && "qualified name with ADL");
9726
9727 // We don't perform ADL for implicit declarations of builtins.
9728 // Verify that this was correctly set up.
9729 FunctionDecl *F;
9730 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9731 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9732 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00009733 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009734
John McCall57500772009-12-16 12:17:52 +00009735 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009736 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00009737 } else
9738 assert(!ULE->isStdAssociatedNamespace() &&
9739 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00009740#endif
9741
John McCall4124c492011-10-17 18:40:02 +00009742 UnbridgedCastsSet UnbridgedCasts;
Sam Panzer0f384432012-08-21 00:52:01 +00009743 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9744 *Result = ExprError();
9745 return true;
9746 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00009747
John McCall57500772009-12-16 12:17:52 +00009748 // Add the functions denoted by the callee to the set of candidate
9749 // functions, including those from argument-dependent lookup.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009750 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
Sam Panzer0f384432012-08-21 00:52:01 +00009751 *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00009752
9753 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00009754 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9755 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +00009756 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009757 // In Microsoft mode, if we are inside a template class member function then
9758 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00009759 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009760 // classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009761 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00009762 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00009763 CallExpr *CE = new (Context) CallExpr(Context, Fn,
9764 llvm::makeArrayRef(Args, NumArgs),
9765 Context.DependentTy, VK_RValue,
9766 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009767 CE->setTypeDependent(true);
Sam Panzer0f384432012-08-21 00:52:01 +00009768 *Result = Owned(CE);
9769 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009770 }
Sam Panzer0f384432012-08-21 00:52:01 +00009771 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +00009772 }
John McCalld681c392009-12-16 08:11:27 +00009773
John McCall4124c492011-10-17 18:40:02 +00009774 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +00009775 return false;
9776}
John McCall4124c492011-10-17 18:40:02 +00009777
Sam Panzer0f384432012-08-21 00:52:01 +00009778/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9779/// the completed call expression. If overload resolution fails, emits
9780/// diagnostics and returns ExprError()
9781static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9782 UnresolvedLookupExpr *ULE,
9783 SourceLocation LParenLoc,
9784 Expr **Args, unsigned NumArgs,
9785 SourceLocation RParenLoc,
9786 Expr *ExecConfig,
9787 OverloadCandidateSet *CandidateSet,
9788 OverloadCandidateSet::iterator *Best,
9789 OverloadingResult OverloadResult,
9790 bool AllowTypoCorrection) {
9791 if (CandidateSet->empty())
9792 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9793 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9794 RParenLoc, /*EmptyLookup=*/true,
9795 AllowTypoCorrection);
9796
9797 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +00009798 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +00009799 FunctionDecl *FDecl = (*Best)->Function;
9800 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9801 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9802 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9803 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9804 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9805 RParenLoc, ExecConfig);
John McCall57500772009-12-16 12:17:52 +00009806 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009807
Richard Smith998a5912011-06-05 22:42:48 +00009808 case OR_No_Viable_Function: {
9809 // Try to recover by looking for viable functions which the user might
9810 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +00009811 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009812 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9813 RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009814 /*EmptyLookup=*/false,
9815 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +00009816 if (!Recovery.isInvalid())
9817 return Recovery;
9818
Sam Panzer0f384432012-08-21 00:52:01 +00009819 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009820 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00009821 << ULE->getName() << Fn->getSourceRange();
Sam Panzer0f384432012-08-21 00:52:01 +00009822 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9823 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009824 break;
Richard Smith998a5912011-06-05 22:42:48 +00009825 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009826
9827 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +00009828 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00009829 << ULE->getName() << Fn->getSourceRange();
Sam Panzer0f384432012-08-21 00:52:01 +00009830 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9831 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009832 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009833
Sam Panzer0f384432012-08-21 00:52:01 +00009834 case OR_Deleted: {
9835 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9836 << (*Best)->Function->isDeleted()
9837 << ULE->getName()
9838 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9839 << Fn->getSourceRange();
9840 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9841 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00009842
Sam Panzer0f384432012-08-21 00:52:01 +00009843 // We emitted an error for the unvailable/deleted function call but keep
9844 // the call in the AST.
9845 FunctionDecl *FDecl = (*Best)->Function;
9846 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9847 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9848 RParenLoc, ExecConfig);
9849 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009850 }
9851
Douglas Gregorb412e172010-07-25 18:17:45 +00009852 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009853 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009854}
9855
Sam Panzer0f384432012-08-21 00:52:01 +00009856/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9857/// (which eventually refers to the declaration Func) and the call
9858/// arguments Args/NumArgs, attempt to resolve the function call down
9859/// to a specific function. If overload resolution succeeds, returns
9860/// the call expression produced by overload resolution.
9861/// Otherwise, emits diagnostics and returns ExprError.
9862ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9863 UnresolvedLookupExpr *ULE,
9864 SourceLocation LParenLoc,
9865 Expr **Args, unsigned NumArgs,
9866 SourceLocation RParenLoc,
9867 Expr *ExecConfig,
9868 bool AllowTypoCorrection) {
9869 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9870 ExprResult result;
9871
9872 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9873 &CandidateSet, &result))
9874 return result;
9875
9876 OverloadCandidateSet::iterator Best;
9877 OverloadingResult OverloadResult =
9878 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
9879
9880 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9881 RParenLoc, ExecConfig, &CandidateSet,
9882 &Best, OverloadResult,
9883 AllowTypoCorrection);
9884}
9885
John McCall4c4c1df2010-01-26 03:27:55 +00009886static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009887 return Functions.size() > 1 ||
9888 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9889}
9890
Douglas Gregor084d8552009-03-13 23:49:33 +00009891/// \brief Create a unary operation that may resolve to an overloaded
9892/// operator.
9893///
9894/// \param OpLoc The location of the operator itself (e.g., '*').
9895///
9896/// \param OpcIn The UnaryOperator::Opcode that describes this
9897/// operator.
9898///
James Dennett18348b62012-06-22 08:52:37 +00009899/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +00009900/// considered by overload resolution. The caller needs to build this
9901/// set based on the context using, e.g.,
9902/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9903/// set should not contain any member functions; those will be added
9904/// by CreateOverloadedUnaryOp().
9905///
James Dennett91738ff2012-06-22 10:32:46 +00009906/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009907ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009908Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9909 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009910 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009911 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009912
9913 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9914 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9915 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009916 // TODO: provide better source location info.
9917 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009918
John McCall4124c492011-10-17 18:40:02 +00009919 if (checkPlaceholderForOverload(*this, Input))
9920 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009921
Douglas Gregor084d8552009-03-13 23:49:33 +00009922 Expr *Args[2] = { Input, 0 };
9923 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009924
Douglas Gregor084d8552009-03-13 23:49:33 +00009925 // For post-increment and post-decrement, add the implicit '0' as
9926 // the second argument, so that we know this is a post-increment or
9927 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009928 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009929 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009930 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9931 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009932 NumArgs = 2;
9933 }
9934
9935 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009936 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009937 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009938 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009939 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009940 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009941 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009942
John McCall58cc69d2010-01-27 01:50:18 +00009943 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009944 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009945 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009946 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009947 /*ADL*/ true, IsOverloaded(Fns),
9948 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009949 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +00009950 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor084d8552009-03-13 23:49:33 +00009951 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009952 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009953 OpLoc));
9954 }
9955
9956 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009957 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009958
9959 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009960 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9961 false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009962
9963 // Add operator candidates that are member functions.
9964 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9965
John McCall4c4c1df2010-01-26 03:27:55 +00009966 // Add candidates from ADL.
9967 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009968 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall4c4c1df2010-01-26 03:27:55 +00009969 /*ExplicitTemplateArgs*/ 0,
9970 CandidateSet);
9971
Douglas Gregor084d8552009-03-13 23:49:33 +00009972 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009973 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009974
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009975 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9976
Douglas Gregor084d8552009-03-13 23:49:33 +00009977 // Perform overload resolution.
9978 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009979 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009980 case OR_Success: {
9981 // We found a built-in operator or an overloaded operator.
9982 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009983
Douglas Gregor084d8552009-03-13 23:49:33 +00009984 if (FnDecl) {
9985 // We matched an overloaded operator. Build a call to that
9986 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009987
Eli Friedmanfa0df832012-02-02 03:46:19 +00009988 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +00009989
Douglas Gregor084d8552009-03-13 23:49:33 +00009990 // Convert the arguments.
9991 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009992 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009993
John Wiegley01296292011-04-08 18:41:53 +00009994 ExprResult InputRes =
9995 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9996 Best->FoundDecl, Method);
9997 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009998 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009999 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010000 } else {
10001 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010002 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010003 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010004 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010005 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010006 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010007 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010008 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010009 return ExprError();
John McCallb268a282010-08-23 23:25:46 +000010010 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010011 }
10012
John McCall4fa0d5f2010-05-06 18:15:07 +000010013 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10014
John McCall7decc9e2010-11-18 06:31:45 +000010015 // Determine the result type.
10016 QualType ResultTy = FnDecl->getResultType();
10017 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10018 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +000010019
Douglas Gregor084d8552009-03-13 23:49:33 +000010020 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010021 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010022 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010023 if (FnExpr.isInvalid())
10024 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000010025
Eli Friedman030eee42009-11-18 03:58:17 +000010026 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000010027 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010028 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000010029 llvm::makeArrayRef(Args, NumArgs),
10030 ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +000010031
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010032 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +000010033 FnDecl))
10034 return ExprError();
10035
John McCallb268a282010-08-23 23:25:46 +000010036 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000010037 } else {
10038 // We matched a built-in operator. Convert the arguments, then
10039 // break out so that we will build the appropriate built-in
10040 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010041 ExprResult InputRes =
10042 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10043 Best->Conversions[0], AA_Passing);
10044 if (InputRes.isInvalid())
10045 return ExprError();
10046 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010047 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000010048 }
John Wiegley01296292011-04-08 18:41:53 +000010049 }
10050
10051 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000010052 // This is an erroneous use of an operator which can be overloaded by
10053 // a non-member function. Check for non-member operators which were
10054 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010055 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10056 llvm::makeArrayRef(Args, NumArgs)))
Richard Smith998a5912011-06-05 22:42:48 +000010057 // FIXME: Recover by calling the found function.
10058 return ExprError();
10059
John Wiegley01296292011-04-08 18:41:53 +000010060 // No viable function; fall through to handling this as a
10061 // built-in operator, which will produce an error message for us.
10062 break;
10063
10064 case OR_Ambiguous:
10065 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10066 << UnaryOperator::getOpcodeStr(Opc)
10067 << Input->getType()
10068 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010069 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10070 llvm::makeArrayRef(Args, NumArgs),
John Wiegley01296292011-04-08 18:41:53 +000010071 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10072 return ExprError();
10073
10074 case OR_Deleted:
10075 Diag(OpLoc, diag::err_ovl_deleted_oper)
10076 << Best->Function->isDeleted()
10077 << UnaryOperator::getOpcodeStr(Opc)
10078 << getDeletedOrUnavailableSuffix(Best->Function)
10079 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010080 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10081 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010082 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010083 return ExprError();
10084 }
Douglas Gregor084d8552009-03-13 23:49:33 +000010085
10086 // Either we found no viable overloaded operator or we matched a
10087 // built-in operator. In either case, fall through to trying to
10088 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000010089 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000010090}
10091
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010092/// \brief Create a binary operation that may resolve to an overloaded
10093/// operator.
10094///
10095/// \param OpLoc The location of the operator itself (e.g., '+').
10096///
10097/// \param OpcIn The BinaryOperator::Opcode that describes this
10098/// operator.
10099///
James Dennett18348b62012-06-22 08:52:37 +000010100/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010101/// considered by overload resolution. The caller needs to build this
10102/// set based on the context using, e.g.,
10103/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10104/// set should not contain any member functions; those will be added
10105/// by CreateOverloadedBinOp().
10106///
10107/// \param LHS Left-hand argument.
10108/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000010109ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010110Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000010111 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000010112 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010113 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010114 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +000010115 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010116
10117 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10118 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10119 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10120
10121 // If either side is type-dependent, create an appropriate dependent
10122 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000010123 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000010124 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010125 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000010126 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000010127 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +000010128 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +000010129 Context.DependentTy,
10130 VK_RValue, OK_Ordinary,
10131 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010132
Douglas Gregor5287f092009-11-05 00:51:44 +000010133 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10134 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010135 VK_LValue,
10136 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +000010137 Context.DependentTy,
10138 Context.DependentTy,
10139 OpLoc));
10140 }
John McCall4c4c1df2010-01-26 03:27:55 +000010141
10142 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +000010143 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010144 // TODO: provide better source location info in DNLoc component.
10145 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000010146 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000010147 = UnresolvedLookupExpr::Create(Context, NamingClass,
10148 NestedNameSpecifierLoc(), OpNameInfo,
10149 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010150 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010151 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010152 Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010153 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010154 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010155 OpLoc));
10156 }
10157
John McCall4124c492011-10-17 18:40:02 +000010158 // Always do placeholder-like conversions on the RHS.
10159 if (checkPlaceholderForOverload(*this, Args[1]))
10160 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010161
John McCall526ab472011-10-25 17:37:35 +000010162 // Do placeholder-like conversion on the LHS; note that we should
10163 // not get here with a PseudoObject LHS.
10164 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000010165 if (checkPlaceholderForOverload(*this, Args[0]))
10166 return ExprError();
10167
Sebastian Redl6a96bf72009-11-18 23:10:33 +000010168 // If this is the assignment operator, we only perform overload resolution
10169 // if the left-hand side is a class or enumeration type. This is actually
10170 // a hack. The standard requires that we do overload resolution between the
10171 // various built-in candidates, but as DR507 points out, this can lead to
10172 // problems. So we do it this way, which pretty much follows what GCC does.
10173 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000010174 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000010175 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010176
John McCalle26a8722010-12-04 08:14:53 +000010177 // If this is the .* operator, which is not overloadable, just
10178 // create a built-in binary operator.
10179 if (Opc == BO_PtrMemD)
10180 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10181
Douglas Gregor084d8552009-03-13 23:49:33 +000010182 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010183 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010184
10185 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010186 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010187
10188 // Add operator candidates that are member functions.
10189 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10190
John McCall4c4c1df2010-01-26 03:27:55 +000010191 // Add candidates from ADL.
10192 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010193 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +000010194 /*ExplicitTemplateArgs*/ 0,
10195 CandidateSet);
10196
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010197 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +000010198 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010199
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010200 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10201
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010202 // Perform overload resolution.
10203 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010204 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000010205 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010206 // We found a built-in operator or an overloaded operator.
10207 FunctionDecl *FnDecl = Best->Function;
10208
10209 if (FnDecl) {
10210 // We matched an overloaded operator. Build a call to that
10211 // operator.
10212
Eli Friedmanfa0df832012-02-02 03:46:19 +000010213 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010214
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010215 // Convert the arguments.
10216 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000010217 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000010218 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010219
Chandler Carruth8e543b32010-12-12 08:17:55 +000010220 ExprResult Arg1 =
10221 PerformCopyInitialization(
10222 InitializedEntity::InitializeParameter(Context,
10223 FnDecl->getParamDecl(0)),
10224 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010225 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010226 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010227
John Wiegley01296292011-04-08 18:41:53 +000010228 ExprResult Arg0 =
10229 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10230 Best->FoundDecl, Method);
10231 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010232 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010233 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010234 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010235 } else {
10236 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000010237 ExprResult Arg0 = PerformCopyInitialization(
10238 InitializedEntity::InitializeParameter(Context,
10239 FnDecl->getParamDecl(0)),
10240 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010241 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010242 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010243
Chandler Carruth8e543b32010-12-12 08:17:55 +000010244 ExprResult Arg1 =
10245 PerformCopyInitialization(
10246 InitializedEntity::InitializeParameter(Context,
10247 FnDecl->getParamDecl(1)),
10248 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010249 if (Arg1.isInvalid())
10250 return ExprError();
10251 Args[0] = LHS = Arg0.takeAs<Expr>();
10252 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010253 }
10254
John McCall4fa0d5f2010-05-06 18:15:07 +000010255 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10256
John McCall7decc9e2010-11-18 06:31:45 +000010257 // Determine the result type.
10258 QualType ResultTy = FnDecl->getResultType();
10259 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10260 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010261
10262 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010263 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10264 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010265 if (FnExpr.isInvalid())
10266 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010267
John McCallb268a282010-08-23 23:25:46 +000010268 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010269 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000010270 Args, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010271
10272 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010273 FnDecl))
10274 return ExprError();
10275
John McCallb268a282010-08-23 23:25:46 +000010276 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010277 } else {
10278 // We matched a built-in operator. Convert the arguments, then
10279 // break out so that we will build the appropriate built-in
10280 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010281 ExprResult ArgsRes0 =
10282 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10283 Best->Conversions[0], AA_Passing);
10284 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010285 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010286 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010287
John Wiegley01296292011-04-08 18:41:53 +000010288 ExprResult ArgsRes1 =
10289 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10290 Best->Conversions[1], AA_Passing);
10291 if (ArgsRes1.isInvalid())
10292 return ExprError();
10293 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010294 break;
10295 }
10296 }
10297
Douglas Gregor66950a32009-09-30 21:46:01 +000010298 case OR_No_Viable_Function: {
10299 // C++ [over.match.oper]p9:
10300 // If the operator is the operator , [...] and there are no
10301 // viable functions, then the operator is assumed to be the
10302 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000010303 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000010304 break;
10305
Chandler Carruth8e543b32010-12-12 08:17:55 +000010306 // For class as left operand for assignment or compound assigment
10307 // operator do not fall through to handling in built-in, but report that
10308 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000010309 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010310 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000010311 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000010312 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10313 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000010314 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +000010315 } else {
Richard Smith998a5912011-06-05 22:42:48 +000010316 // This is an erroneous use of an operator which can be overloaded by
10317 // a non-member function. Check for non-member operators which were
10318 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010319 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000010320 // FIXME: Recover by calling the found function.
10321 return ExprError();
10322
Douglas Gregor66950a32009-09-30 21:46:01 +000010323 // No viable function; try to create a built-in operation, which will
10324 // produce an error. Then, show the non-viable candidates.
10325 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000010326 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010327 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000010328 "C++ binary operator overloading is missing candidates!");
10329 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010330 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010331 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010332 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000010333 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010334
10335 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010336 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010337 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000010338 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000010339 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010340 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010341 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010342 return ExprError();
10343
10344 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000010345 if (isImplicitlyDeleted(Best->Function)) {
10346 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10347 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10348 << getSpecialMember(Method)
10349 << BinaryOperator::getOpcodeStr(Opc)
10350 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith6f1e2c62012-04-02 20:59:25 +000010351
10352 if (getSpecialMember(Method) != CXXInvalid) {
10353 // The user probably meant to call this special member. Just
10354 // explain why it's deleted.
10355 NoteDeletedFunction(Method);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010356 return ExprError();
10357 }
10358 } else {
10359 Diag(OpLoc, diag::err_ovl_deleted_oper)
10360 << Best->Function->isDeleted()
10361 << BinaryOperator::getOpcodeStr(Opc)
10362 << getDeletedOrUnavailableSuffix(Best->Function)
10363 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10364 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010365 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010366 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010367 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000010368 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010369
Douglas Gregor66950a32009-09-30 21:46:01 +000010370 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000010371 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010372}
10373
John McCalldadc5752010-08-24 06:29:42 +000010374ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000010375Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10376 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000010377 Expr *Base, Expr *Idx) {
10378 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000010379 DeclarationName OpName =
10380 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10381
10382 // If either side is type-dependent, create an appropriate dependent
10383 // expression.
10384 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10385
John McCall58cc69d2010-01-27 01:50:18 +000010386 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010387 // CHECKME: no 'operator' keyword?
10388 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10389 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000010390 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010391 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010392 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010393 /*ADL*/ true, /*Overloaded*/ false,
10394 UnresolvedSetIterator(),
10395 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000010396 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000010397
Sebastian Redladba46e2009-10-29 20:17:01 +000010398 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010399 Args,
Sebastian Redladba46e2009-10-29 20:17:01 +000010400 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010401 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +000010402 RLoc));
10403 }
10404
John McCall4124c492011-10-17 18:40:02 +000010405 // Handle placeholders on both operands.
10406 if (checkPlaceholderForOverload(*this, Args[0]))
10407 return ExprError();
10408 if (checkPlaceholderForOverload(*this, Args[1]))
10409 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010410
Sebastian Redladba46e2009-10-29 20:17:01 +000010411 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010412 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010413
10414 // Subscript can only be overloaded as a member function.
10415
10416 // Add operator candidates that are member functions.
10417 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10418
10419 // Add builtin operator candidates.
10420 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10421
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010422 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10423
Sebastian Redladba46e2009-10-29 20:17:01 +000010424 // Perform overload resolution.
10425 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010426 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000010427 case OR_Success: {
10428 // We found a built-in operator or an overloaded operator.
10429 FunctionDecl *FnDecl = Best->Function;
10430
10431 if (FnDecl) {
10432 // We matched an overloaded operator. Build a call to that
10433 // operator.
10434
Eli Friedmanfa0df832012-02-02 03:46:19 +000010435 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010436
John McCalla0296f72010-03-19 07:35:19 +000010437 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010438 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +000010439
Sebastian Redladba46e2009-10-29 20:17:01 +000010440 // Convert the arguments.
10441 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000010442 ExprResult Arg0 =
10443 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10444 Best->FoundDecl, Method);
10445 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010446 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010447 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010448
Anders Carlssona68e51e2010-01-29 18:37:50 +000010449 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010450 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000010451 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010452 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000010453 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010454 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000010455 Owned(Args[1]));
10456 if (InputInit.isInvalid())
10457 return ExprError();
10458
10459 Args[1] = InputInit.takeAs<Expr>();
10460
Sebastian Redladba46e2009-10-29 20:17:01 +000010461 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +000010462 QualType ResultTy = FnDecl->getResultType();
10463 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10464 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +000010465
10466 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010467 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10468 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010469 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10470 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010471 OpLocInfo.getLoc(),
10472 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010473 if (FnExpr.isInvalid())
10474 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010475
John McCallb268a282010-08-23 23:25:46 +000010476 CXXOperatorCallExpr *TheCall =
10477 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010478 FnExpr.take(), Args,
John McCall7decc9e2010-11-18 06:31:45 +000010479 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010480
John McCallb268a282010-08-23 23:25:46 +000010481 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000010482 FnDecl))
10483 return ExprError();
10484
John McCallb268a282010-08-23 23:25:46 +000010485 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000010486 } else {
10487 // We matched a built-in operator. Convert the arguments, then
10488 // break out so that we will build the appropriate built-in
10489 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010490 ExprResult ArgsRes0 =
10491 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10492 Best->Conversions[0], AA_Passing);
10493 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010494 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010495 Args[0] = ArgsRes0.take();
10496
10497 ExprResult ArgsRes1 =
10498 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10499 Best->Conversions[1], AA_Passing);
10500 if (ArgsRes1.isInvalid())
10501 return ExprError();
10502 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010503
10504 break;
10505 }
10506 }
10507
10508 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000010509 if (CandidateSet.empty())
10510 Diag(LLoc, diag::err_ovl_no_oper)
10511 << Args[0]->getType() << /*subscript*/ 0
10512 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10513 else
10514 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10515 << Args[0]->getType()
10516 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010517 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010518 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000010519 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010520 }
10521
10522 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010523 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010524 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000010525 << Args[0]->getType() << Args[1]->getType()
10526 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010527 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010528 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010529 return ExprError();
10530
10531 case OR_Deleted:
10532 Diag(LLoc, diag::err_ovl_deleted_oper)
10533 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010534 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000010535 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010536 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010537 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010538 return ExprError();
10539 }
10540
10541 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000010542 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010543}
10544
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010545/// BuildCallToMemberFunction - Build a call to a member
10546/// function. MemExpr is the expression that refers to the member
10547/// function (and includes the object parameter), Args/NumArgs are the
10548/// arguments to the function call (not including the object
10549/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000010550/// expression refers to a non-static member function or an overloaded
10551/// member function.
John McCalldadc5752010-08-24 06:29:42 +000010552ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000010553Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10554 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +000010555 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000010556 assert(MemExprE->getType() == Context.BoundMemberTy ||
10557 MemExprE->getType() == Context.OverloadTy);
10558
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010559 // Dig out the member expression. This holds both the object
10560 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000010561 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010562
John McCall0009fcc2011-04-26 20:42:42 +000010563 // Determine whether this is a call to a pointer-to-member function.
10564 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10565 assert(op->getType() == Context.BoundMemberTy);
10566 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10567
10568 QualType fnType =
10569 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10570
10571 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10572 QualType resultType = proto->getCallResultType(Context);
10573 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10574
10575 // Check that the object type isn't more qualified than the
10576 // member function we're calling.
10577 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10578
10579 QualType objectType = op->getLHS()->getType();
10580 if (op->getOpcode() == BO_PtrMemI)
10581 objectType = objectType->castAs<PointerType>()->getPointeeType();
10582 Qualifiers objectQuals = objectType.getQualifiers();
10583
10584 Qualifiers difference = objectQuals - funcQuals;
10585 difference.removeObjCGCAttr();
10586 difference.removeAddressSpace();
10587 if (difference) {
10588 std::string qualsString = difference.getAsString();
10589 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10590 << fnType.getUnqualifiedType()
10591 << qualsString
10592 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10593 }
10594
10595 CXXMemberCallExpr *call
Benjamin Kramerc215e762012-08-24 11:54:20 +000010596 = new (Context) CXXMemberCallExpr(Context, MemExprE,
10597 llvm::makeArrayRef(Args, NumArgs),
John McCall0009fcc2011-04-26 20:42:42 +000010598 resultType, valueKind, RParenLoc);
10599
10600 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010601 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000010602 call, 0))
10603 return ExprError();
10604
10605 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10606 return ExprError();
10607
10608 return MaybeBindToTemporary(call);
10609 }
10610
John McCall4124c492011-10-17 18:40:02 +000010611 UnbridgedCastsSet UnbridgedCasts;
10612 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10613 return ExprError();
10614
John McCall10eae182009-11-30 22:42:35 +000010615 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010616 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000010617 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010618 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000010619 if (isa<MemberExpr>(NakedMemExpr)) {
10620 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000010621 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000010622 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010623 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000010624 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000010625 } else {
10626 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010627 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010628
John McCall6e9f8f62009-12-03 04:06:58 +000010629 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000010630 Expr::Classification ObjectClassification
10631 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10632 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000010633
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010634 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000010635 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000010636
John McCall2d74de92009-12-01 22:10:20 +000010637 // FIXME: avoid copy.
10638 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10639 if (UnresExpr->hasExplicitTemplateArgs()) {
10640 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10641 TemplateArgs = &TemplateArgsBuffer;
10642 }
10643
John McCall10eae182009-11-30 22:42:35 +000010644 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10645 E = UnresExpr->decls_end(); I != E; ++I) {
10646
John McCall6e9f8f62009-12-03 04:06:58 +000010647 NamedDecl *Func = *I;
10648 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10649 if (isa<UsingShadowDecl>(Func))
10650 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10651
Douglas Gregor02824322011-01-26 19:30:28 +000010652
Francois Pichet64225792011-01-18 05:04:39 +000010653 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010654 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010655 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10656 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000010657 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000010658 // If explicit template arguments were provided, we can't call a
10659 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000010660 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000010661 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010662
John McCalla0296f72010-03-19 07:35:19 +000010663 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010664 ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010665 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000010666 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010667 } else {
John McCall10eae182009-11-30 22:42:35 +000010668 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000010669 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010670 ObjectType, ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010671 llvm::makeArrayRef(Args, NumArgs),
10672 CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010673 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010674 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010675 }
Mike Stump11289f42009-09-09 15:08:12 +000010676
John McCall10eae182009-11-30 22:42:35 +000010677 DeclarationName DeclName = UnresExpr->getMemberName();
10678
John McCall4124c492011-10-17 18:40:02 +000010679 UnbridgedCasts.restore();
10680
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010681 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010682 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000010683 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010684 case OR_Success:
10685 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010686 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +000010687 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000010688 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010689 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010690 break;
10691
10692 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000010693 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010694 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010695 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010696 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10697 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010698 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010699 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010700
10701 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000010702 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010703 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010704 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10705 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010706 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010707 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010708
10709 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000010710 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000010711 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010712 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010713 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010714 << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010715 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10716 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010717 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010718 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010719 }
10720
John McCall16df1e52010-03-30 21:47:33 +000010721 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000010722
John McCall2d74de92009-12-01 22:10:20 +000010723 // If overload resolution picked a static member, build a
10724 // non-member call based on that function.
10725 if (Method->isStatic()) {
10726 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10727 Args, NumArgs, RParenLoc);
10728 }
10729
John McCall10eae182009-11-30 22:42:35 +000010730 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010731 }
10732
John McCall7decc9e2010-11-18 06:31:45 +000010733 QualType ResultType = Method->getResultType();
10734 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10735 ResultType = ResultType.getNonLValueExprType(Context);
10736
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010737 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010738 CXXMemberCallExpr *TheCall =
Benjamin Kramerc215e762012-08-24 11:54:20 +000010739 new (Context) CXXMemberCallExpr(Context, MemExprE,
10740 llvm::makeArrayRef(Args, NumArgs),
John McCall7decc9e2010-11-18 06:31:45 +000010741 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010742
Anders Carlssonc4859ba2009-10-10 00:06:20 +000010743 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010744 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000010745 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000010746 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010747
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010748 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000010749 // We only need to do this if there was actually an overload; otherwise
10750 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000010751 if (!Method->isStatic()) {
10752 ExprResult ObjectArg =
10753 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10754 FoundDecl, Method);
10755 if (ObjectArg.isInvalid())
10756 return ExprError();
10757 MemExpr->setBase(ObjectArg.take());
10758 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010759
10760 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000010761 const FunctionProtoType *Proto =
10762 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +000010763 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010764 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000010765 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010766
Eli Friedmanff4b4072012-02-18 04:48:30 +000010767 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10768
Richard Smith55ce3522012-06-25 20:30:08 +000010769 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000010770 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000010771
Anders Carlsson47061ee2011-05-06 14:25:31 +000010772 if ((isa<CXXConstructorDecl>(CurContext) ||
10773 isa<CXXDestructorDecl>(CurContext)) &&
10774 TheCall->getMethodDecl()->isPure()) {
10775 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10776
Chandler Carruth59259262011-06-27 08:31:58 +000010777 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000010778 Diag(MemExpr->getLocStart(),
10779 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10780 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10781 << MD->getParent()->getDeclName();
10782
10783 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000010784 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000010785 }
John McCallb268a282010-08-23 23:25:46 +000010786 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010787}
10788
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010789/// BuildCallToObjectOfClassType - Build a call to an object of class
10790/// type (C++ [over.call.object]), which can end up invoking an
10791/// overloaded function call operator (@c operator()) or performing a
10792/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000010793ExprResult
John Wiegley01296292011-04-08 18:41:53 +000010794Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000010795 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010796 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010797 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000010798 if (checkPlaceholderForOverload(*this, Obj))
10799 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010800 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000010801
10802 UnbridgedCastsSet UnbridgedCasts;
10803 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10804 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010805
John Wiegley01296292011-04-08 18:41:53 +000010806 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10807 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000010808
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010809 // C++ [over.call.object]p1:
10810 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000010811 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010812 // candidate functions includes at least the function call
10813 // operators of T. The function call operators of T are obtained by
10814 // ordinary lookup of the name operator() in the context of
10815 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000010816 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000010817 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010818
John Wiegley01296292011-04-08 18:41:53 +000010819 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010820 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010821 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010822
John McCall27b18f82009-11-17 02:14:36 +000010823 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10824 LookupQualifiedName(R, Record->getDecl());
10825 R.suppressDiagnostics();
10826
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010827 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000010828 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000010829 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10830 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000010831 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000010832 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010833
Douglas Gregorab7897a2008-11-19 22:57:39 +000010834 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010835 // In addition, for each (non-explicit in C++0x) conversion function
10836 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000010837 //
10838 // operator conversion-type-id () cv-qualifier;
10839 //
10840 // where cv-qualifier is the same cv-qualification as, or a
10841 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000010842 // denotes the type "pointer to function of (P1,...,Pn) returning
10843 // R", or the type "reference to pointer to function of
10844 // (P1,...,Pn) returning R", or the type "reference to function
10845 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000010846 // is also considered as a candidate function. Similarly,
10847 // surrogate call functions are added to the set of candidate
10848 // functions for each conversion function declared in an
10849 // accessible base class provided the function is not hidden
10850 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +000010851 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000010852 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +000010853 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +000010854 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000010855 NamedDecl *D = *I;
10856 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10857 if (isa<UsingShadowDecl>(D))
10858 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010859
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010860 // Skip over templated conversion functions; they aren't
10861 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000010862 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010863 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000010864
John McCall6e9f8f62009-12-03 04:06:58 +000010865 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010866 if (!Conv->isExplicit()) {
10867 // Strip the reference type (if any) and then the pointer type (if
10868 // any) to get down to what might be a function type.
10869 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10870 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10871 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000010872
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010873 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10874 {
10875 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010876 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10877 CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010878 }
10879 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000010880 }
Mike Stump11289f42009-09-09 15:08:12 +000010881
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010882 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10883
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010884 // Perform overload resolution.
10885 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000010886 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000010887 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010888 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000010889 // Overload resolution succeeded; we'll build the appropriate call
10890 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010891 break;
10892
10893 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000010894 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010895 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000010896 << Object.get()->getType() << /*call*/ 1
10897 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000010898 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010899 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000010900 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010901 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010902 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10903 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010904 break;
10905
10906 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010907 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010908 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010909 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010910 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10911 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010912 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010913
10914 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010915 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010916 diag::err_ovl_deleted_object_call)
10917 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010918 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010919 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010920 << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010921 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10922 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010923 break;
Mike Stump11289f42009-09-09 15:08:12 +000010924 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010925
Douglas Gregorb412e172010-07-25 18:17:45 +000010926 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010927 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010928
John McCall4124c492011-10-17 18:40:02 +000010929 UnbridgedCasts.restore();
10930
Douglas Gregorab7897a2008-11-19 22:57:39 +000010931 if (Best->Function == 0) {
10932 // Since there is no function declaration, this is one of the
10933 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010934 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010935 = cast<CXXConversionDecl>(
10936 Best->Conversions[0].UserDefined.ConversionFunction);
10937
John Wiegley01296292011-04-08 18:41:53 +000010938 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010939 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010940
Douglas Gregorab7897a2008-11-19 22:57:39 +000010941 // We selected one of the surrogate functions that converts the
10942 // object parameter to a function pointer. Perform the conversion
10943 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010944
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010945 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010946 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010947 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10948 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010949 if (Call.isInvalid())
10950 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010951 // Record usage of conversion in an implicit cast.
10952 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10953 CK_UserDefinedConversion,
10954 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010955
Douglas Gregor668443e2011-01-20 00:18:04 +000010956 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010957 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010958 }
10959
Eli Friedmanfa0df832012-02-02 03:46:19 +000010960 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010961 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010962 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010963
Douglas Gregorab7897a2008-11-19 22:57:39 +000010964 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10965 // that calls this method, using Object for the implicit object
10966 // parameter and passing along the remaining arguments.
10967 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010968 const FunctionProtoType *Proto =
10969 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010970
10971 unsigned NumArgsInProto = Proto->getNumArgs();
10972 unsigned NumArgsToCheck = NumArgs;
10973
10974 // Build the full argument list for the method call (the
10975 // implicit object parameter is placed at the beginning of the
10976 // list).
10977 Expr **MethodArgs;
10978 if (NumArgs < NumArgsInProto) {
10979 NumArgsToCheck = NumArgsInProto;
10980 MethodArgs = new Expr*[NumArgsInProto + 1];
10981 } else {
10982 MethodArgs = new Expr*[NumArgs + 1];
10983 }
John Wiegley01296292011-04-08 18:41:53 +000010984 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010985 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10986 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010987
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010988 DeclarationNameInfo OpLocInfo(
10989 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10990 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010991 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010992 HadMultipleCandidates,
10993 OpLocInfo.getLoc(),
10994 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010995 if (NewFn.isInvalid())
10996 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010997
10998 // Once we've built TheCall, all of the expressions are properly
10999 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000011000 QualType ResultTy = Method->getResultType();
11001 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11002 ResultTy = ResultTy.getNonLValueExprType(Context);
11003
John McCallb268a282010-08-23 23:25:46 +000011004 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011005 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000011006 llvm::makeArrayRef(MethodArgs, NumArgs+1),
John McCall7decc9e2010-11-18 06:31:45 +000011007 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011008 delete [] MethodArgs;
11009
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011010 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000011011 Method))
11012 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011013
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011014 // We may have default arguments. If so, we need to allocate more
11015 // slots in the call for them.
11016 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000011017 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011018 else if (NumArgs > NumArgsInProto)
11019 NumArgsToCheck = NumArgsInProto;
11020
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011021 bool IsError = false;
11022
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011023 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000011024 ExprResult ObjRes =
11025 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11026 Best->FoundDecl, Method);
11027 if (ObjRes.isInvalid())
11028 IsError = true;
11029 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011030 Object = ObjRes;
John Wiegley01296292011-04-08 18:41:53 +000011031 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011032
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011033 // Check the argument types.
11034 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011035 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011036 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011037 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000011038
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011039 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011040
John McCalldadc5752010-08-24 06:29:42 +000011041 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011042 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011043 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011044 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000011045 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011046
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011047 IsError |= InputInit.isInvalid();
11048 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011049 } else {
John McCalldadc5752010-08-24 06:29:42 +000011050 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011051 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11052 if (DefArg.isInvalid()) {
11053 IsError = true;
11054 break;
11055 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011056
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011057 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011058 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011059
11060 TheCall->setArg(i + 1, Arg);
11061 }
11062
11063 // If this is a variadic call, handle args passed through "...".
11064 if (Proto->isVariadic()) {
11065 // Promote the arguments (C99 6.5.2.2p7).
Aaron Ballman9bca21e2012-07-20 20:40:35 +000011066 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000011067 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11068 IsError |= Arg.isInvalid();
11069 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011070 }
11071 }
11072
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011073 if (IsError) return true;
11074
Eli Friedmanff4b4072012-02-18 04:48:30 +000011075 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11076
Richard Smith55ce3522012-06-25 20:30:08 +000011077 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000011078 return true;
11079
John McCalle172be52010-08-24 06:09:16 +000011080 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011081}
11082
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011083/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000011084/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011085/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000011086ExprResult
John McCallb268a282010-08-23 23:25:46 +000011087Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000011088 assert(Base->getType()->isRecordType() &&
11089 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000011090
John McCall4124c492011-10-17 18:40:02 +000011091 if (checkPlaceholderForOverload(*this, Base))
11092 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011093
John McCallbc077cf2010-02-08 23:07:23 +000011094 SourceLocation Loc = Base->getExprLoc();
11095
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011096 // C++ [over.ref]p1:
11097 //
11098 // [...] An expression x->m is interpreted as (x.operator->())->m
11099 // for a class object x of type T if T::operator->() exists and if
11100 // the operator is selected as the best match function by the
11101 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000011102 DeclarationName OpName =
11103 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000011104 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011105 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000011106
John McCallbc077cf2010-02-08 23:07:23 +000011107 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011108 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000011109 return ExprError();
11110
John McCall27b18f82009-11-17 02:14:36 +000011111 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11112 LookupQualifiedName(R, BaseRecord->getDecl());
11113 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000011114
11115 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000011116 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000011117 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11118 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000011119 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011120
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011121 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11122
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011123 // Perform overload resolution.
11124 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011125 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011126 case OR_Success:
11127 // Overload resolution succeeded; we'll build the call below.
11128 break;
11129
11130 case OR_No_Viable_Function:
11131 if (CandidateSet.empty())
11132 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000011133 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011134 else
11135 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000011136 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011137 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011138 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011139
11140 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011141 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11142 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011143 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011144 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011145
11146 case OR_Deleted:
11147 Diag(OpLoc, diag::err_ovl_deleted_oper)
11148 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011149 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011150 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011151 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011152 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011153 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011154 }
11155
Eli Friedmanfa0df832012-02-02 03:46:19 +000011156 MarkFunctionReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000011157 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000011158 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000011159
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011160 // Convert the object parameter.
11161 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000011162 ExprResult BaseResult =
11163 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11164 Best->FoundDecl, Method);
11165 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000011166 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011167 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000011168
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011169 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011170 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011171 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011172 if (FnExpr.isInvalid())
11173 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011174
John McCall7decc9e2010-11-18 06:31:45 +000011175 QualType ResultTy = Method->getResultType();
11176 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11177 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000011178 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011179 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000011180 Base, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011181
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011182 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011183 Method))
11184 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000011185
11186 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011187}
11188
Richard Smithbcc22fc2012-03-09 08:00:36 +000011189/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11190/// a literal operator described by the provided lookup results.
11191ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11192 DeclarationNameInfo &SuffixInfo,
11193 ArrayRef<Expr*> Args,
11194 SourceLocation LitEndLoc,
11195 TemplateArgumentListInfo *TemplateArgs) {
11196 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000011197
Richard Smithbcc22fc2012-03-09 08:00:36 +000011198 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11199 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11200 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000011201
Richard Smithbcc22fc2012-03-09 08:00:36 +000011202 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11203
Richard Smithbcc22fc2012-03-09 08:00:36 +000011204 // Perform overload resolution. This will usually be trivial, but might need
11205 // to perform substitutions for a literal operator template.
11206 OverloadCandidateSet::iterator Best;
11207 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11208 case OR_Success:
11209 case OR_Deleted:
11210 break;
11211
11212 case OR_No_Viable_Function:
11213 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11214 << R.getLookupName();
11215 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11216 return ExprError();
11217
11218 case OR_Ambiguous:
11219 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11220 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11221 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000011222 }
11223
Richard Smithbcc22fc2012-03-09 08:00:36 +000011224 FunctionDecl *FD = Best->Function;
11225 MarkFunctionReferenced(UDSuffixLoc, FD);
11226 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smithc67fdd42012-03-07 08:35:16 +000011227
Richard Smithbcc22fc2012-03-09 08:00:36 +000011228 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11229 SuffixInfo.getLoc(),
11230 SuffixInfo.getInfo());
11231 if (Fn.isInvalid())
11232 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000011233
11234 // Check the argument types. This should almost always be a no-op, except
11235 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000011236 Expr *ConvArgs[2];
11237 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11238 ExprResult InputInit = PerformCopyInitialization(
11239 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11240 SourceLocation(), Args[ArgIdx]);
11241 if (InputInit.isInvalid())
11242 return true;
11243 ConvArgs[ArgIdx] = InputInit.take();
11244 }
11245
Richard Smithc67fdd42012-03-07 08:35:16 +000011246 QualType ResultTy = FD->getResultType();
11247 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11248 ResultTy = ResultTy.getNonLValueExprType(Context);
11249
Richard Smithc67fdd42012-03-07 08:35:16 +000011250 UserDefinedLiteral *UDL =
Benjamin Kramerc215e762012-08-24 11:54:20 +000011251 new (Context) UserDefinedLiteral(Context, Fn.take(),
11252 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000011253 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11254
11255 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11256 return ExprError();
11257
Richard Smith55ce3522012-06-25 20:30:08 +000011258 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smithc67fdd42012-03-07 08:35:16 +000011259 return ExprError();
11260
11261 return MaybeBindToTemporary(UDL);
11262}
11263
Sam Panzer0f384432012-08-21 00:52:01 +000011264/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11265/// given LookupResult is non-empty, it is assumed to describe a member which
11266/// will be invoked. Otherwise, the function will be found via argument
11267/// dependent lookup.
11268/// CallExpr is set to a valid expression and FRS_Success returned on success,
11269/// otherwise CallExpr is set to ExprError() and some non-success value
11270/// is returned.
11271Sema::ForRangeStatus
11272Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11273 SourceLocation RangeLoc, VarDecl *Decl,
11274 BeginEndFunction BEF,
11275 const DeclarationNameInfo &NameInfo,
11276 LookupResult &MemberLookup,
11277 OverloadCandidateSet *CandidateSet,
11278 Expr *Range, ExprResult *CallExpr) {
11279 CandidateSet->clear();
11280 if (!MemberLookup.empty()) {
11281 ExprResult MemberRef =
11282 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11283 /*IsPtr=*/false, CXXScopeSpec(),
11284 /*TemplateKWLoc=*/SourceLocation(),
11285 /*FirstQualifierInScope=*/0,
11286 MemberLookup,
11287 /*TemplateArgs=*/0);
11288 if (MemberRef.isInvalid()) {
11289 *CallExpr = ExprError();
11290 Diag(Range->getLocStart(), diag::note_in_for_range)
11291 << RangeLoc << BEF << Range->getType();
11292 return FRS_DiagnosticIssued;
11293 }
11294 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11295 if (CallExpr->isInvalid()) {
11296 *CallExpr = ExprError();
11297 Diag(Range->getLocStart(), diag::note_in_for_range)
11298 << RangeLoc << BEF << Range->getType();
11299 return FRS_DiagnosticIssued;
11300 }
11301 } else {
11302 UnresolvedSet<0> FoundNames;
11303 // C++11 [stmt.ranged]p1: For the purposes of this name lookup, namespace
11304 // std is an associated namespace.
11305 UnresolvedLookupExpr *Fn =
11306 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11307 NestedNameSpecifierLoc(), NameInfo,
11308 /*NeedsADL=*/true, /*Overloaded=*/false,
11309 FoundNames.begin(), FoundNames.end(),
11310 /*LookInStdNamespace=*/true);
11311
11312 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11313 CandidateSet, CallExpr);
11314 if (CandidateSet->empty() || CandidateSetError) {
11315 *CallExpr = ExprError();
11316 return FRS_NoViableFunction;
11317 }
11318 OverloadCandidateSet::iterator Best;
11319 OverloadingResult OverloadResult =
11320 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11321
11322 if (OverloadResult == OR_No_Viable_Function) {
11323 *CallExpr = ExprError();
11324 return FRS_NoViableFunction;
11325 }
11326 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11327 Loc, 0, CandidateSet, &Best,
11328 OverloadResult,
11329 /*AllowTypoCorrection=*/false);
11330 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11331 *CallExpr = ExprError();
11332 Diag(Range->getLocStart(), diag::note_in_for_range)
11333 << RangeLoc << BEF << Range->getType();
11334 return FRS_DiagnosticIssued;
11335 }
11336 }
11337 return FRS_Success;
11338}
11339
11340
Douglas Gregorcd695e52008-11-10 20:40:00 +000011341/// FixOverloadedFunctionReference - E is an expression that refers to
11342/// a C++ overloaded function (possibly with some parentheses and
11343/// perhaps a '&' around it). We have resolved the overloaded function
11344/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000011345/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000011346Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000011347 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000011348 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011349 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11350 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011351 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011352 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011353
Douglas Gregor51c538b2009-11-20 19:42:02 +000011354 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011355 }
11356
Douglas Gregor51c538b2009-11-20 19:42:02 +000011357 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011358 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11359 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011360 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000011361 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000011362 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000011363 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000011364 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011365 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011366
11367 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000011368 ICE->getCastKind(),
11369 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000011370 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011371 }
11372
Douglas Gregor51c538b2009-11-20 19:42:02 +000011373 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000011374 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000011375 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011376 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11377 if (Method->isStatic()) {
11378 // Do nothing: static member functions aren't any different
11379 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000011380 } else {
John McCalle66edc12009-11-24 19:00:30 +000011381 // Fix the sub expression, which really has to be an
11382 // UnresolvedLookupExpr holding an overloaded member function
11383 // or template.
John McCall16df1e52010-03-30 21:47:33 +000011384 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11385 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000011386 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011387 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011388
John McCalld14a8642009-11-21 08:51:07 +000011389 assert(isa<DeclRefExpr>(SubExpr)
11390 && "fixed to something other than a decl ref");
11391 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11392 && "fixed to a member ref with no nested name qualifier");
11393
11394 // We have taken the address of a pointer to member
11395 // function. Perform the computation here so that we get the
11396 // appropriate pointer to member type.
11397 QualType ClassType
11398 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11399 QualType MemPtrType
11400 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11401
John McCall7decc9e2010-11-18 06:31:45 +000011402 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11403 VK_RValue, OK_Ordinary,
11404 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011405 }
11406 }
John McCall16df1e52010-03-30 21:47:33 +000011407 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11408 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011409 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011410 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011411
John McCalle3027922010-08-25 11:45:40 +000011412 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011413 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000011414 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011415 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011416 }
John McCalld14a8642009-11-21 08:51:07 +000011417
11418 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000011419 // FIXME: avoid copy.
11420 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000011421 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000011422 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11423 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000011424 }
11425
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011426 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11427 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011428 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011429 Fn,
John McCall113bee02012-03-10 09:33:50 +000011430 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011431 ULE->getNameLoc(),
11432 Fn->getType(),
11433 VK_LValue,
11434 Found.getDecl(),
11435 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011436 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011437 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11438 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000011439 }
11440
John McCall10eae182009-11-30 22:42:35 +000011441 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000011442 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000011443 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11444 if (MemExpr->hasExplicitTemplateArgs()) {
11445 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11446 TemplateArgs = &TemplateArgsBuffer;
11447 }
John McCall6b51f282009-11-23 01:53:49 +000011448
John McCall2d74de92009-12-01 22:10:20 +000011449 Expr *Base;
11450
John McCall7decc9e2010-11-18 06:31:45 +000011451 // If we're filling in a static method where we used to have an
11452 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000011453 if (MemExpr->isImplicitAccess()) {
11454 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011455 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11456 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011457 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011458 Fn,
John McCall113bee02012-03-10 09:33:50 +000011459 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011460 MemExpr->getMemberLoc(),
11461 Fn->getType(),
11462 VK_LValue,
11463 Found.getDecl(),
11464 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011465 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011466 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11467 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000011468 } else {
11469 SourceLocation Loc = MemExpr->getMemberLoc();
11470 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000011471 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000011472 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000011473 Base = new (Context) CXXThisExpr(Loc,
11474 MemExpr->getBaseType(),
11475 /*isImplicit=*/true);
11476 }
John McCall2d74de92009-12-01 22:10:20 +000011477 } else
John McCallc3007a22010-10-26 07:05:15 +000011478 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000011479
John McCall4adb38c2011-04-27 00:36:17 +000011480 ExprValueKind valueKind;
11481 QualType type;
11482 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11483 valueKind = VK_LValue;
11484 type = Fn->getType();
11485 } else {
11486 valueKind = VK_RValue;
11487 type = Context.BoundMemberTy;
11488 }
11489
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011490 MemberExpr *ME = MemberExpr::Create(Context, Base,
11491 MemExpr->isArrow(),
11492 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011493 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011494 Fn,
11495 Found,
11496 MemExpr->getMemberNameInfo(),
11497 TemplateArgs,
11498 type, valueKind, OK_Ordinary);
11499 ME->setHadMultipleCandidates(true);
11500 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011502
John McCallc3007a22010-10-26 07:05:15 +000011503 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000011504}
11505
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011506ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000011507 DeclAccessPair Found,
11508 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000011509 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000011510}
11511
Douglas Gregor5251f1b2008-10-21 16:13:35 +000011512} // end namespace clang