blob: f31c12bb77e0e06b9cb7364d7f66b0fe8f1e6048 [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
Benjamin Kramer97e59492012-10-09 15:52:25 +0000743void OverloadCandidateSet::destroyCandidates() {
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 Kramer97e59492012-10-09 15:52:25 +0000750}
751
752void OverloadCandidateSet::clear() {
753 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000754 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000755 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000756 Functions.clear();
757}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000758
John McCall4124c492011-10-17 18:40:02 +0000759namespace {
760 class UnbridgedCastsSet {
761 struct Entry {
762 Expr **Addr;
763 Expr *Saved;
764 };
765 SmallVector<Entry, 2> Entries;
766
767 public:
768 void save(Sema &S, Expr *&E) {
769 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
770 Entry entry = { &E, E };
771 Entries.push_back(entry);
772 E = S.stripARCUnbridgedCast(E);
773 }
774
775 void restore() {
776 for (SmallVectorImpl<Entry>::iterator
777 i = Entries.begin(), e = Entries.end(); i != e; ++i)
778 *i->Addr = i->Saved;
779 }
780 };
781}
782
783/// checkPlaceholderForOverload - Do any interesting placeholder-like
784/// preprocessing on the given expression.
785///
786/// \param unbridgedCasts a collection to which to add unbridged casts;
787/// without this, they will be immediately diagnosed as errors
788///
789/// Return true on unrecoverable error.
790static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
791 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000792 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
793 // We can't handle overloaded expressions here because overload
794 // resolution might reasonably tweak them.
795 if (placeholder->getKind() == BuiltinType::Overload) return false;
796
797 // If the context potentially accepts unbridged ARC casts, strip
798 // the unbridged cast and add it to the collection for later restoration.
799 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
800 unbridgedCasts) {
801 unbridgedCasts->save(S, E);
802 return false;
803 }
804
805 // Go ahead and check everything else.
806 ExprResult result = S.CheckPlaceholderExpr(E);
807 if (result.isInvalid())
808 return true;
809
810 E = result.take();
811 return false;
812 }
813
814 // Nothing to do.
815 return false;
816}
817
818/// checkArgPlaceholdersForOverload - Check a set of call operands for
819/// placeholders.
820static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
821 unsigned numArgs,
822 UnbridgedCastsSet &unbridged) {
823 for (unsigned i = 0; i != numArgs; ++i)
824 if (checkPlaceholderForOverload(S, args[i], &unbridged))
825 return true;
826
827 return false;
828}
829
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000830// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000831// overload of the declarations in Old. This routine returns false if
832// New and Old cannot be overloaded, e.g., if New has the same
833// signature as some function in Old (C++ 1.3.10) or if the Old
834// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000835// it does return false, MatchedDecl will point to the decl that New
836// cannot be overloaded with. This decl may be a UsingShadowDecl on
837// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000838//
839// Example: Given the following input:
840//
841// void f(int, float); // #1
842// void f(int, int); // #2
843// int f(int, int); // #3
844//
845// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000846// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000847//
John McCall3d988d92009-12-02 08:47:38 +0000848// When we process #2, Old contains only the FunctionDecl for #1. By
849// comparing the parameter types, we see that #1 and #2 are overloaded
850// (since they have different signatures), so this routine returns
851// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000852//
John McCall3d988d92009-12-02 08:47:38 +0000853// When we process #3, Old is an overload set containing #1 and #2. We
854// compare the signatures of #3 to #1 (they're overloaded, so we do
855// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
856// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000857// signature), IsOverload returns false and MatchedDecl will be set to
858// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000859//
860// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
861// into a class by a using declaration. The rules for whether to hide
862// shadow declarations ignore some properties which otherwise figure
863// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000864Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000865Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
866 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000867 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000868 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000869 NamedDecl *OldD = *I;
870
871 bool OldIsUsingDecl = false;
872 if (isa<UsingShadowDecl>(OldD)) {
873 OldIsUsingDecl = true;
874
875 // We can always introduce two using declarations into the same
876 // context, even if they have identical signatures.
877 if (NewIsUsingDecl) continue;
878
879 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
880 }
881
882 // If either declaration was introduced by a using declaration,
883 // we'll need to use slightly different rules for matching.
884 // Essentially, these rules are the normal rules, except that
885 // function templates hide function templates with different
886 // return types or template parameter lists.
887 bool UseMemberUsingDeclRules =
888 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
889
John McCall3d988d92009-12-02 08:47:38 +0000890 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000891 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
892 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
893 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
894 continue;
895 }
896
John McCalldaa3d6b2009-12-09 03:35:25 +0000897 Match = *I;
898 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000899 }
John McCall3d988d92009-12-02 08:47:38 +0000900 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000901 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
902 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
903 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
904 continue;
905 }
906
John McCalldaa3d6b2009-12-09 03:35:25 +0000907 Match = *I;
908 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000909 }
John McCalla8987a2942010-11-10 03:01:53 +0000910 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000911 // We can overload with these, which can show up when doing
912 // redeclaration checks for UsingDecls.
913 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000914 } else if (isa<TagDecl>(OldD)) {
915 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000916 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
917 // Optimistically assume that an unresolved using decl will
918 // overload; if it doesn't, we'll have to diagnose during
919 // template instantiation.
920 } else {
John McCall1f82f242009-11-18 22:49:29 +0000921 // (C++ 13p1):
922 // Only function declarations can be overloaded; object and type
923 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000924 Match = *I;
925 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000926 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000927 }
John McCall1f82f242009-11-18 22:49:29 +0000928
John McCalldaa3d6b2009-12-09 03:35:25 +0000929 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000930}
931
John McCalle9cccd82010-06-16 08:42:20 +0000932bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
933 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000934 // If both of the functions are extern "C", then they are not
935 // overloads.
936 if (Old->isExternC() && New->isExternC())
937 return false;
938
John McCall1f82f242009-11-18 22:49:29 +0000939 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
940 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
941
942 // C++ [temp.fct]p2:
943 // A function template can be overloaded with other function templates
944 // and with normal (non-template) functions.
945 if ((OldTemplate == 0) != (NewTemplate == 0))
946 return true;
947
948 // Is the function New an overload of the function Old?
949 QualType OldQType = Context.getCanonicalType(Old->getType());
950 QualType NewQType = Context.getCanonicalType(New->getType());
951
952 // Compare the signatures (C++ 1.3.10) of the two functions to
953 // determine whether they are overloads. If we find any mismatch
954 // in the signature, they are overloads.
955
956 // If either of these functions is a K&R-style function (no
957 // prototype), then we consider them to have matching signatures.
958 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
959 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
960 return false;
961
John McCall424cec92011-01-19 06:33:43 +0000962 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
963 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000964
965 // The signature of a function includes the types of its
966 // parameters (C++ 1.3.10), which includes the presence or absence
967 // of the ellipsis; see C++ DR 357).
968 if (OldQType != NewQType &&
969 (OldType->getNumArgs() != NewType->getNumArgs() ||
970 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000971 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000972 return true;
973
974 // C++ [temp.over.link]p4:
975 // The signature of a function template consists of its function
976 // signature, its return type and its template parameter list. The names
977 // of the template parameters are significant only for establishing the
978 // relationship between the template parameters and the rest of the
979 // signature.
980 //
981 // We check the return type and template parameter lists for function
982 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000983 //
984 // However, we don't consider either of these when deciding whether
985 // a member introduced by a shadow declaration is hidden.
986 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000987 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
988 OldTemplate->getTemplateParameters(),
989 false, TPL_TemplateMatch) ||
990 OldType->getResultType() != NewType->getResultType()))
991 return true;
992
993 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000994 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000995 //
996 // As part of this, also check whether one of the member functions
997 // is static, in which case they are not overloads (C++
998 // 13.1p2). While not part of the definition of the signature,
999 // this check is important to determine whether these functions
1000 // can be overloaded.
1001 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1002 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1003 if (OldMethod && NewMethod &&
1004 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001005 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +00001006 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
1007 if (!UseUsingDeclRules &&
1008 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
1009 (OldMethod->getRefQualifier() == RQ_None ||
1010 NewMethod->getRefQualifier() == RQ_None)) {
1011 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001012 // - Member function declarations with the same name and the same
1013 // parameter-type-list as well as member function template
1014 // declarations with the same name, the same parameter-type-list, and
1015 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +00001016 // them, but not all, have a ref-qualifier (8.3.5).
1017 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1018 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1019 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1020 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001021
John McCall1f82f242009-11-18 22:49:29 +00001022 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001023 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001024
John McCall1f82f242009-11-18 22:49:29 +00001025 // The signatures match; this is not an overload.
1026 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001027}
1028
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001029/// \brief Checks availability of the function depending on the current
1030/// function context. Inside an unavailable function, unavailability is ignored.
1031///
1032/// \returns true if \arg FD is unavailable and current context is inside
1033/// an available function, false otherwise.
1034bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1035 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1036}
1037
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001038/// \brief Tries a user-defined conversion from From to ToType.
1039///
1040/// Produces an implicit conversion sequence for when a standard conversion
1041/// is not an option. See TryImplicitConversion for more information.
1042static ImplicitConversionSequence
1043TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1044 bool SuppressUserConversions,
1045 bool AllowExplicit,
1046 bool InOverloadResolution,
1047 bool CStyle,
1048 bool AllowObjCWritebackConversion) {
1049 ImplicitConversionSequence ICS;
1050
1051 if (SuppressUserConversions) {
1052 // We're not in the case above, so there is no conversion that
1053 // we can perform.
1054 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1055 return ICS;
1056 }
1057
1058 // Attempt user-defined conversion.
1059 OverloadCandidateSet Conversions(From->getExprLoc());
1060 OverloadingResult UserDefResult
1061 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1062 AllowExplicit);
1063
1064 if (UserDefResult == OR_Success) {
1065 ICS.setUserDefined();
1066 // C++ [over.ics.user]p4:
1067 // A conversion of an expression of class type to the same class
1068 // type is given Exact Match rank, and a conversion of an
1069 // expression of class type to a base class of that type is
1070 // given Conversion rank, in spite of the fact that a copy
1071 // constructor (i.e., a user-defined conversion function) is
1072 // called for those cases.
1073 if (CXXConstructorDecl *Constructor
1074 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1075 QualType FromCanon
1076 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1077 QualType ToCanon
1078 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1079 if (Constructor->isCopyConstructor() &&
1080 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1081 // Turn this into a "standard" conversion sequence, so that it
1082 // gets ranked with standard conversion sequences.
1083 ICS.setStandard();
1084 ICS.Standard.setAsIdentityConversion();
1085 ICS.Standard.setFromType(From->getType());
1086 ICS.Standard.setAllToTypes(ToType);
1087 ICS.Standard.CopyConstructor = Constructor;
1088 if (ToCanon != FromCanon)
1089 ICS.Standard.Second = ICK_Derived_To_Base;
1090 }
1091 }
1092
1093 // C++ [over.best.ics]p4:
1094 // However, when considering the argument of a user-defined
1095 // conversion function that is a candidate by 13.3.1.3 when
1096 // invoked for the copying of the temporary in the second step
1097 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1098 // 13.3.1.6 in all cases, only standard conversion sequences and
1099 // ellipsis conversion sequences are allowed.
1100 if (SuppressUserConversions && ICS.isUserDefined()) {
1101 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1102 }
1103 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1104 ICS.setAmbiguous();
1105 ICS.Ambiguous.setFromType(From->getType());
1106 ICS.Ambiguous.setToType(ToType);
1107 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1108 Cand != Conversions.end(); ++Cand)
1109 if (Cand->Viable)
1110 ICS.Ambiguous.addConversion(Cand->Function);
1111 } else {
1112 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1113 }
1114
1115 return ICS;
1116}
1117
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001118/// TryImplicitConversion - Attempt to perform an implicit conversion
1119/// from the given expression (Expr) to the given type (ToType). This
1120/// function returns an implicit conversion sequence that can be used
1121/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001122///
1123/// void f(float f);
1124/// void g(int i) { f(i); }
1125///
1126/// this routine would produce an implicit conversion sequence to
1127/// describe the initialization of f from i, which will be a standard
1128/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1129/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1130//
1131/// Note that this routine only determines how the conversion can be
1132/// performed; it does not actually perform the conversion. As such,
1133/// it will not produce any diagnostics if no conversion is available,
1134/// but will instead return an implicit conversion sequence of kind
1135/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001136///
1137/// If @p SuppressUserConversions, then user-defined conversions are
1138/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001139/// If @p AllowExplicit, then explicit user-defined conversions are
1140/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001141///
1142/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1143/// writeback conversion, which allows __autoreleasing id* parameters to
1144/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001145static ImplicitConversionSequence
1146TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1147 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001148 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001149 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001150 bool CStyle,
1151 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001152 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001153 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001154 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001155 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001156 return ICS;
1157 }
1158
David Blaikiebbafb8a2012-03-11 07:00:24 +00001159 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001160 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001161 return ICS;
1162 }
1163
Douglas Gregor836a7e82010-08-11 02:15:33 +00001164 // C++ [over.ics.user]p4:
1165 // A conversion of an expression of class type to the same class
1166 // type is given Exact Match rank, and a conversion of an
1167 // expression of class type to a base class of that type is
1168 // given Conversion rank, in spite of the fact that a copy/move
1169 // constructor (i.e., a user-defined conversion function) is
1170 // called for those cases.
1171 QualType FromType = From->getType();
1172 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001173 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1174 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001175 ICS.setStandard();
1176 ICS.Standard.setAsIdentityConversion();
1177 ICS.Standard.setFromType(FromType);
1178 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001179
Douglas Gregor5ab11652010-04-17 22:01:05 +00001180 // We don't actually check at this point whether there is a valid
1181 // copy/move constructor, since overloading just assumes that it
1182 // exists. When we actually perform initialization, we'll find the
1183 // appropriate constructor to copy the returned object, if needed.
1184 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001185
Douglas Gregor5ab11652010-04-17 22:01:05 +00001186 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001187 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001188 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001189
Douglas Gregor836a7e82010-08-11 02:15:33 +00001190 return ICS;
1191 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001192
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001193 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1194 AllowExplicit, InOverloadResolution, CStyle,
1195 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001196}
1197
John McCall31168b02011-06-15 23:02:42 +00001198ImplicitConversionSequence
1199Sema::TryImplicitConversion(Expr *From, QualType ToType,
1200 bool SuppressUserConversions,
1201 bool AllowExplicit,
1202 bool InOverloadResolution,
1203 bool CStyle,
1204 bool AllowObjCWritebackConversion) {
1205 return clang::TryImplicitConversion(*this, From, ToType,
1206 SuppressUserConversions, AllowExplicit,
1207 InOverloadResolution, CStyle,
1208 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +00001209}
1210
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001211/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001212/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001213/// converted expression. Flavor is the kind of conversion we're
1214/// performing, used in the error message. If @p AllowExplicit,
1215/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001216ExprResult
1217Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001218 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001219 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001220 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001221}
1222
John Wiegley01296292011-04-08 18:41:53 +00001223ExprResult
1224Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001225 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001226 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001227 if (checkPlaceholderForOverload(*this, From))
1228 return ExprError();
1229
John McCall31168b02011-06-15 23:02:42 +00001230 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1231 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001232 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001233 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001234
John McCall5c32be02010-08-24 20:38:10 +00001235 ICS = clang::TryImplicitConversion(*this, From, ToType,
1236 /*SuppressUserConversions=*/false,
1237 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001238 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001239 /*CStyle=*/false,
1240 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001241 return PerformImplicitConversion(From, ToType, ICS, Action);
1242}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001243
1244/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001245/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001246bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1247 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001248 if (Context.hasSameUnqualifiedType(FromType, ToType))
1249 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001250
John McCall991eb4b2010-12-21 00:44:39 +00001251 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1252 // where F adds one of the following at most once:
1253 // - a pointer
1254 // - a member pointer
1255 // - a block pointer
1256 CanQualType CanTo = Context.getCanonicalType(ToType);
1257 CanQualType CanFrom = Context.getCanonicalType(FromType);
1258 Type::TypeClass TyClass = CanTo->getTypeClass();
1259 if (TyClass != CanFrom->getTypeClass()) return false;
1260 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1261 if (TyClass == Type::Pointer) {
1262 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1263 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1264 } else if (TyClass == Type::BlockPointer) {
1265 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1266 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1267 } else if (TyClass == Type::MemberPointer) {
1268 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1269 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1270 } else {
1271 return false;
1272 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001273
John McCall991eb4b2010-12-21 00:44:39 +00001274 TyClass = CanTo->getTypeClass();
1275 if (TyClass != CanFrom->getTypeClass()) return false;
1276 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1277 return false;
1278 }
1279
1280 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1281 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1282 if (!EInfo.getNoReturn()) return false;
1283
1284 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1285 assert(QualType(FromFn, 0).isCanonical());
1286 if (QualType(FromFn, 0) != CanTo) return false;
1287
1288 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001289 return true;
1290}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001291
Douglas Gregor46188682010-05-18 22:42:18 +00001292/// \brief Determine whether the conversion from FromType to ToType is a valid
1293/// vector conversion.
1294///
1295/// \param ICK Will be set to the vector conversion kind, if this is a vector
1296/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001297static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1298 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001299 // We need at least one of these types to be a vector type to have a vector
1300 // conversion.
1301 if (!ToType->isVectorType() && !FromType->isVectorType())
1302 return false;
1303
1304 // Identical types require no conversions.
1305 if (Context.hasSameUnqualifiedType(FromType, ToType))
1306 return false;
1307
1308 // There are no conversions between extended vector types, only identity.
1309 if (ToType->isExtVectorType()) {
1310 // There are no conversions between extended vector types other than the
1311 // identity conversion.
1312 if (FromType->isExtVectorType())
1313 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001314
Douglas Gregor46188682010-05-18 22:42:18 +00001315 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001316 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001317 ICK = ICK_Vector_Splat;
1318 return true;
1319 }
1320 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001321
1322 // We can perform the conversion between vector types in the following cases:
1323 // 1)vector types are equivalent AltiVec and GCC vector types
1324 // 2)lax vector conversions are permitted and the vector types are of the
1325 // same size
1326 if (ToType->isVectorType() && FromType->isVectorType()) {
1327 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001328 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruth9c524c12010-08-08 05:02:51 +00001329 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001330 ICK = ICK_Vector_Conversion;
1331 return true;
1332 }
Douglas Gregor46188682010-05-18 22:42:18 +00001333 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001334
Douglas Gregor46188682010-05-18 22:42:18 +00001335 return false;
1336}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001337
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001338static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1339 bool InOverloadResolution,
1340 StandardConversionSequence &SCS,
1341 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001342
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001343/// IsStandardConversion - Determines whether there is a standard
1344/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1345/// expression From to the type ToType. Standard conversion sequences
1346/// only consider non-class types; for conversions that involve class
1347/// types, use TryImplicitConversion. If a conversion exists, SCS will
1348/// contain the standard conversion sequence required to perform this
1349/// conversion and this routine will return true. Otherwise, this
1350/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001351static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1352 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001353 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001354 bool CStyle,
1355 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001356 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001357
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001358 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001359 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001360 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001361 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001362 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001363 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001364
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001365 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001366 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001367 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001368 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001369 return false;
1370
Mike Stump11289f42009-09-09 15:08:12 +00001371 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001372 }
1373
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001374 // The first conversion can be an lvalue-to-rvalue conversion,
1375 // array-to-pointer conversion, or function-to-pointer conversion
1376 // (C++ 4p1).
1377
John McCall5c32be02010-08-24 20:38:10 +00001378 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001379 DeclAccessPair AccessPair;
1380 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001381 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001382 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001383 // We were able to resolve the address of the overloaded function,
1384 // so we can convert to the type of that function.
1385 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001386
1387 // we can sometimes resolve &foo<int> regardless of ToType, so check
1388 // if the type matches (identity) or we are converting to bool
1389 if (!S.Context.hasSameUnqualifiedType(
1390 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1391 QualType resultTy;
1392 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001393 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001394 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1395 // otherwise, only a boolean conversion is standard
1396 if (!ToType->isBooleanType())
1397 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001398 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001399
Chandler Carruthffce2452011-03-29 08:08:18 +00001400 // Check if the "from" expression is taking the address of an overloaded
1401 // function and recompute the FromType accordingly. Take advantage of the
1402 // fact that non-static member functions *must* have such an address-of
1403 // expression.
1404 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1405 if (Method && !Method->isStatic()) {
1406 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1407 "Non-unary operator on non-static member address");
1408 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1409 == UO_AddrOf &&
1410 "Non-address-of operator on non-static member address");
1411 const Type *ClassType
1412 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1413 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001414 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1415 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1416 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001417 "Non-address-of operator for overloaded function expression");
1418 FromType = S.Context.getPointerType(FromType);
1419 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001420
Douglas Gregor980fb162010-04-29 18:24:40 +00001421 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001422 assert(S.Context.hasSameType(
1423 FromType,
1424 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001425 } else {
1426 return false;
1427 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001428 }
John McCall154a2fd2011-08-30 00:57:29 +00001429 // Lvalue-to-rvalue conversion (C++11 4.1):
1430 // A glvalue (3.10) of a non-function, non-array type T can
1431 // be converted to a prvalue.
1432 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001433 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001434 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001435 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001436 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001437
Douglas Gregorc79862f2012-04-12 17:51:55 +00001438 // C11 6.3.2.1p2:
1439 // ... if the lvalue has atomic type, the value has the non-atomic version
1440 // of the type of the lvalue ...
1441 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1442 FromType = Atomic->getValueType();
1443
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001444 // If T is a non-class type, the type of the rvalue is the
1445 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001446 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1447 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001448 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001449 } else if (FromType->isArrayType()) {
1450 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001451 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001452
1453 // An lvalue or rvalue of type "array of N T" or "array of unknown
1454 // bound of T" can be converted to an rvalue of type "pointer to
1455 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001456 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001457
John McCall5c32be02010-08-24 20:38:10 +00001458 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001459 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001460 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001461
1462 // For the purpose of ranking in overload resolution
1463 // (13.3.3.1.1), this conversion is considered an
1464 // array-to-pointer conversion followed by a qualification
1465 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001466 SCS.Second = ICK_Identity;
1467 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001468 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001469 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001470 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001471 }
John McCall086a4642010-11-24 05:12:34 +00001472 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001473 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001474 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001475
1476 // An lvalue of function type T can be converted to an rvalue of
1477 // type "pointer to T." The result is a pointer to the
1478 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001479 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001480 } else {
1481 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001482 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001483 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001484 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001485
1486 // The second conversion can be an integral promotion, floating
1487 // point promotion, integral conversion, floating point conversion,
1488 // floating-integral conversion, pointer conversion,
1489 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001490 // For overloading in C, this can also be a "compatible-type"
1491 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001492 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001493 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001494 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001495 // The unqualified versions of the types are the same: there's no
1496 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001497 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001498 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001499 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001500 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001501 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001502 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001503 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001504 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001505 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001506 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001507 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001508 SCS.Second = ICK_Complex_Promotion;
1509 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001510 } else if (ToType->isBooleanType() &&
1511 (FromType->isArithmeticType() ||
1512 FromType->isAnyPointerType() ||
1513 FromType->isBlockPointerType() ||
1514 FromType->isMemberPointerType() ||
1515 FromType->isNullPtrType())) {
1516 // Boolean conversions (C++ 4.12).
1517 SCS.Second = ICK_Boolean_Conversion;
1518 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001519 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001520 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001521 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001522 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001523 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001524 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001525 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001526 SCS.Second = ICK_Complex_Conversion;
1527 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001528 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1529 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001530 // Complex-real conversions (C99 6.3.1.7)
1531 SCS.Second = ICK_Complex_Real;
1532 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001533 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001534 // Floating point conversions (C++ 4.8).
1535 SCS.Second = ICK_Floating_Conversion;
1536 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001537 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001538 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001539 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001540 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001541 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001542 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001543 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001544 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001545 SCS.Second = ICK_Block_Pointer_Conversion;
1546 } else if (AllowObjCWritebackConversion &&
1547 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1548 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001549 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1550 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001551 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001552 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001553 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001554 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001555 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001556 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001557 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001558 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001559 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001560 SCS.Second = SecondICK;
1561 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001562 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001563 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001564 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001565 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001566 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001567 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001568 // Treat a conversion that strips "noreturn" as an identity conversion.
1569 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001570 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1571 InOverloadResolution,
1572 SCS, CStyle)) {
1573 SCS.Second = ICK_TransparentUnionConversion;
1574 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001575 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1576 CStyle)) {
1577 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001578 // appropriately.
1579 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001580 } else {
1581 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001582 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001583 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001584 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001585
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001586 QualType CanonFrom;
1587 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001588 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001589 bool ObjCLifetimeConversion;
1590 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1591 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001592 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001593 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001594 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001595 CanonFrom = S.Context.getCanonicalType(FromType);
1596 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001597 } else {
1598 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001599 SCS.Third = ICK_Identity;
1600
Mike Stump11289f42009-09-09 15:08:12 +00001601 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001602 // [...] Any difference in top-level cv-qualification is
1603 // subsumed by the initialization itself and does not constitute
1604 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001605 CanonFrom = S.Context.getCanonicalType(FromType);
1606 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001607 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001608 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001609 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001610 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1611 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001612 FromType = ToType;
1613 CanonFrom = CanonTo;
1614 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001615 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001616 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001617
1618 // If we have not converted the argument type to the parameter type,
1619 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001620 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001621 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001622
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001623 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001624}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001625
1626static bool
1627IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1628 QualType &ToType,
1629 bool InOverloadResolution,
1630 StandardConversionSequence &SCS,
1631 bool CStyle) {
1632
1633 const RecordType *UT = ToType->getAsUnionType();
1634 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1635 return false;
1636 // The field to initialize within the transparent union.
1637 RecordDecl *UD = UT->getDecl();
1638 // It's compatible if the expression matches any of the fields.
1639 for (RecordDecl::field_iterator it = UD->field_begin(),
1640 itend = UD->field_end();
1641 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001642 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1643 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001644 ToType = it->getType();
1645 return true;
1646 }
1647 }
1648 return false;
1649}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001650
1651/// IsIntegralPromotion - Determines whether the conversion from the
1652/// expression From (whose potentially-adjusted type is FromType) to
1653/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1654/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001655bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001656 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001657 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001658 if (!To) {
1659 return false;
1660 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001661
1662 // An rvalue of type char, signed char, unsigned char, short int, or
1663 // unsigned short int can be converted to an rvalue of type int if
1664 // int can represent all the values of the source type; otherwise,
1665 // the source rvalue can be converted to an rvalue of type unsigned
1666 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001667 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1668 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001669 if (// We can promote any signed, promotable integer type to an int
1670 (FromType->isSignedIntegerType() ||
1671 // We can promote any unsigned integer type whose size is
1672 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001673 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001674 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001675 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001676 }
1677
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001678 return To->getKind() == BuiltinType::UInt;
1679 }
1680
Richard Smithb9c5a602012-09-13 21:18:54 +00001681 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001682 // A prvalue of an unscoped enumeration type whose underlying type is not
1683 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1684 // following types that can represent all the values of the enumeration
1685 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1686 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001687 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001688 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001689 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001690 // with lowest integer conversion rank (4.13) greater than the rank of long
1691 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001692 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001693 // C++11 [conv.prom]p4:
1694 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1695 // can be converted to a prvalue of its underlying type. Moreover, if
1696 // integral promotion can be applied to its underlying type, a prvalue of an
1697 // unscoped enumeration type whose underlying type is fixed can also be
1698 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001699 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1700 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1701 // provided for a scoped enumeration.
1702 if (FromEnumType->getDecl()->isScoped())
1703 return false;
1704
Richard Smithb9c5a602012-09-13 21:18:54 +00001705 // We can perform an integral promotion to the underlying type of the enum,
1706 // even if that's not the promoted type.
1707 if (FromEnumType->getDecl()->isFixed()) {
1708 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1709 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1710 IsIntegralPromotion(From, Underlying, ToType);
1711 }
1712
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001713 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001714 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001715 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001716 return Context.hasSameUnqualifiedType(ToType,
1717 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001718 }
John McCall56774992009-12-09 09:09:27 +00001719
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001720 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001721 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1722 // to an rvalue a prvalue of the first of the following types that can
1723 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001724 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001725 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001726 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001728 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001729 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001730 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001731 // Determine whether the type we're converting from is signed or
1732 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001733 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001734 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001735
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001736 // The types we'll try to promote to, in the appropriate
1737 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001738 QualType PromoteTypes[6] = {
1739 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001740 Context.LongTy, Context.UnsignedLongTy ,
1741 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001742 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001743 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001744 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1745 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001746 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001747 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1748 // We found the type that we can promote to. If this is the
1749 // type we wanted, we have a promotion. Otherwise, no
1750 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001751 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001752 }
1753 }
1754 }
1755
1756 // An rvalue for an integral bit-field (9.6) can be converted to an
1757 // rvalue of type int if int can represent all the values of the
1758 // bit-field; otherwise, it can be converted to unsigned int if
1759 // unsigned int can represent all the values of the bit-field. If
1760 // the bit-field is larger yet, no integral promotion applies to
1761 // it. If the bit-field has an enumerated type, it is treated as any
1762 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001763 // FIXME: We should delay checking of bit-fields until we actually perform the
1764 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001765 using llvm::APSInt;
1766 if (From)
1767 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001768 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001769 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001770 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1771 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1772 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001773
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001774 // Are we promoting to an int from a bitfield that fits in an int?
1775 if (BitWidth < ToSize ||
1776 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1777 return To->getKind() == BuiltinType::Int;
1778 }
Mike Stump11289f42009-09-09 15:08:12 +00001779
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001780 // Are we promoting to an unsigned int from an unsigned bitfield
1781 // that fits into an unsigned int?
1782 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1783 return To->getKind() == BuiltinType::UInt;
1784 }
Mike Stump11289f42009-09-09 15:08:12 +00001785
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001786 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001787 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001788 }
Mike Stump11289f42009-09-09 15:08:12 +00001789
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001790 // An rvalue of type bool can be converted to an rvalue of type int,
1791 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001792 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001793 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001794 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001795
1796 return false;
1797}
1798
1799/// IsFloatingPointPromotion - Determines whether the conversion from
1800/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1801/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001802bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001803 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1804 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001805 /// An rvalue of type float can be converted to an rvalue of type
1806 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001807 if (FromBuiltin->getKind() == BuiltinType::Float &&
1808 ToBuiltin->getKind() == BuiltinType::Double)
1809 return true;
1810
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001811 // C99 6.3.1.5p1:
1812 // When a float is promoted to double or long double, or a
1813 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001814 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001815 (FromBuiltin->getKind() == BuiltinType::Float ||
1816 FromBuiltin->getKind() == BuiltinType::Double) &&
1817 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1818 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001819
1820 // Half can be promoted to float.
1821 if (FromBuiltin->getKind() == BuiltinType::Half &&
1822 ToBuiltin->getKind() == BuiltinType::Float)
1823 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001824 }
1825
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001826 return false;
1827}
1828
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001829/// \brief Determine if a conversion is a complex promotion.
1830///
1831/// A complex promotion is defined as a complex -> complex conversion
1832/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001833/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001834bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001835 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001836 if (!FromComplex)
1837 return false;
1838
John McCall9dd450b2009-09-21 23:43:11 +00001839 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001840 if (!ToComplex)
1841 return false;
1842
1843 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001844 ToComplex->getElementType()) ||
1845 IsIntegralPromotion(0, FromComplex->getElementType(),
1846 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001847}
1848
Douglas Gregor237f96c2008-11-26 23:31:11 +00001849/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1850/// the pointer type FromPtr to a pointer to type ToPointee, with the
1851/// same type qualifiers as FromPtr has on its pointee type. ToType,
1852/// if non-empty, will be a pointer to ToType that may or may not have
1853/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001854///
Mike Stump11289f42009-09-09 15:08:12 +00001855static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001856BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001857 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001858 ASTContext &Context,
1859 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001860 assert((FromPtr->getTypeClass() == Type::Pointer ||
1861 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1862 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001863
John McCall31168b02011-06-15 23:02:42 +00001864 /// Conversions to 'id' subsume cv-qualifier conversions.
1865 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001866 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001867
1868 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001869 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001870 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001871 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001872
John McCall31168b02011-06-15 23:02:42 +00001873 if (StripObjCLifetime)
1874 Quals.removeObjCLifetime();
1875
Mike Stump11289f42009-09-09 15:08:12 +00001876 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001877 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001878 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001879 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001880 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001881
1882 // Build a pointer to ToPointee. It has the right qualifiers
1883 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001884 if (isa<ObjCObjectPointerType>(ToType))
1885 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001886 return Context.getPointerType(ToPointee);
1887 }
1888
1889 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001890 QualType QualifiedCanonToPointee
1891 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001892
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001893 if (isa<ObjCObjectPointerType>(ToType))
1894 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1895 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001896}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001897
Mike Stump11289f42009-09-09 15:08:12 +00001898static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001899 bool InOverloadResolution,
1900 ASTContext &Context) {
1901 // Handle value-dependent integral null pointer constants correctly.
1902 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1903 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001904 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001905 return !InOverloadResolution;
1906
Douglas Gregor56751b52009-09-25 04:25:58 +00001907 return Expr->isNullPointerConstant(Context,
1908 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1909 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001910}
Mike Stump11289f42009-09-09 15:08:12 +00001911
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001912/// IsPointerConversion - Determines whether the conversion of the
1913/// expression From, which has the (possibly adjusted) type FromType,
1914/// can be converted to the type ToType via a pointer conversion (C++
1915/// 4.10). If so, returns true and places the converted type (that
1916/// might differ from ToType in its cv-qualifiers at some level) into
1917/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001918///
Douglas Gregora29dc052008-11-27 01:19:21 +00001919/// This routine also supports conversions to and from block pointers
1920/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1921/// pointers to interfaces. FIXME: Once we've determined the
1922/// appropriate overloading rules for Objective-C, we may want to
1923/// split the Objective-C checks into a different routine; however,
1924/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001925/// conversions, so for now they live here. IncompatibleObjC will be
1926/// set if the conversion is an allowed Objective-C conversion that
1927/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001928bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001929 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001930 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001931 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001932 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001933 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1934 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001935 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001936
Mike Stump11289f42009-09-09 15:08:12 +00001937 // Conversion from a null pointer constant to any Objective-C pointer type.
1938 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001939 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001940 ConvertedType = ToType;
1941 return true;
1942 }
1943
Douglas Gregor231d1c62008-11-27 00:15:41 +00001944 // Blocks: Block pointers can be converted to void*.
1945 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001946 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001947 ConvertedType = ToType;
1948 return true;
1949 }
1950 // Blocks: A null pointer constant can be converted to a block
1951 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001952 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001953 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001954 ConvertedType = ToType;
1955 return true;
1956 }
1957
Sebastian Redl576fd422009-05-10 18:38:11 +00001958 // If the left-hand-side is nullptr_t, the right side can be a null
1959 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001960 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001961 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001962 ConvertedType = ToType;
1963 return true;
1964 }
1965
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001966 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001967 if (!ToTypePtr)
1968 return false;
1969
1970 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001971 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001972 ConvertedType = ToType;
1973 return true;
1974 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001975
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001976 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001977 // , including objective-c pointers.
1978 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001979 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001980 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001981 ConvertedType = BuildSimilarlyQualifiedPointerType(
1982 FromType->getAs<ObjCObjectPointerType>(),
1983 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001984 ToType, Context);
1985 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001986 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001987 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001988 if (!FromTypePtr)
1989 return false;
1990
1991 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001992
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001993 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001994 // pointer conversion, so don't do all of the work below.
1995 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1996 return false;
1997
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001998 // An rvalue of type "pointer to cv T," where T is an object type,
1999 // can be converted to an rvalue of type "pointer to cv void" (C++
2000 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002001 if (FromPointeeType->isIncompleteOrObjectType() &&
2002 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002003 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002004 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002005 ToType, Context,
2006 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002007 return true;
2008 }
2009
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002010 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002011 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002012 ToPointeeType->isVoidType()) {
2013 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2014 ToPointeeType,
2015 ToType, Context);
2016 return true;
2017 }
2018
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002019 // When we're overloading in C, we allow a special kind of pointer
2020 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002021 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002022 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002023 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002024 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002025 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002026 return true;
2027 }
2028
Douglas Gregor5c407d92008-10-23 00:40:37 +00002029 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002030 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002031 // An rvalue of type "pointer to cv D," where D is a class type,
2032 // can be converted to an rvalue of type "pointer to cv B," where
2033 // B is a base class (clause 10) of D. If B is an inaccessible
2034 // (clause 11) or ambiguous (10.2) base class of D, a program that
2035 // necessitates this conversion is ill-formed. The result of the
2036 // conversion is a pointer to the base class sub-object of the
2037 // derived class object. The null pointer value is converted to
2038 // the null pointer value of the destination type.
2039 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002040 // Note that we do not check for ambiguity or inaccessibility
2041 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002042 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002043 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002044 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002045 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002046 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002047 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002048 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002049 ToType, Context);
2050 return true;
2051 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002052
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002053 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2054 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2055 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2056 ToPointeeType,
2057 ToType, Context);
2058 return true;
2059 }
2060
Douglas Gregora119f102008-12-19 19:13:09 +00002061 return false;
2062}
Douglas Gregoraec25842011-04-26 23:16:46 +00002063
2064/// \brief Adopt the given qualifiers for the given type.
2065static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2066 Qualifiers TQs = T.getQualifiers();
2067
2068 // Check whether qualifiers already match.
2069 if (TQs == Qs)
2070 return T;
2071
2072 if (Qs.compatiblyIncludes(TQs))
2073 return Context.getQualifiedType(T, Qs);
2074
2075 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2076}
Douglas Gregora119f102008-12-19 19:13:09 +00002077
2078/// isObjCPointerConversion - Determines whether this is an
2079/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2080/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002081bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002082 QualType& ConvertedType,
2083 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002084 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002085 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002086
Douglas Gregoraec25842011-04-26 23:16:46 +00002087 // The set of qualifiers on the type we're converting from.
2088 Qualifiers FromQualifiers = FromType.getQualifiers();
2089
Steve Naroff7cae42b2009-07-10 23:34:53 +00002090 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002091 const ObjCObjectPointerType* ToObjCPtr =
2092 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002093 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002094 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002095
Steve Naroff7cae42b2009-07-10 23:34:53 +00002096 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002097 // If the pointee types are the same (ignoring qualifications),
2098 // then this is not a pointer conversion.
2099 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2100 FromObjCPtr->getPointeeType()))
2101 return false;
2102
Douglas Gregoraec25842011-04-26 23:16:46 +00002103 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002104 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002105 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002106 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002107 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002108 return true;
2109 }
2110 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002111 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002112 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002113 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002114 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002115 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002116 return true;
2117 }
2118 // Objective C++: We're able to convert from a pointer to an
2119 // interface to a pointer to a different interface.
2120 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002121 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2122 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002123 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002124 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2125 FromObjCPtr->getPointeeType()))
2126 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002127 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002128 ToObjCPtr->getPointeeType(),
2129 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002130 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002131 return true;
2132 }
2133
2134 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2135 // Okay: this is some kind of implicit downcast of Objective-C
2136 // interfaces, which is permitted. However, we're going to
2137 // complain about it.
2138 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002139 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002140 ToObjCPtr->getPointeeType(),
2141 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002142 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002143 return true;
2144 }
Mike Stump11289f42009-09-09 15:08:12 +00002145 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002146 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002147 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002148 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002149 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002150 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002151 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002152 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002153 // to a block pointer type.
2154 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002155 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002156 return true;
2157 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002158 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002159 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002160 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002161 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002162 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002163 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002164 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002165 return true;
2166 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002167 else
Douglas Gregora119f102008-12-19 19:13:09 +00002168 return false;
2169
Douglas Gregor033f56d2008-12-23 00:53:59 +00002170 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002171 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002172 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002173 else if (const BlockPointerType *FromBlockPtr =
2174 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002175 FromPointeeType = FromBlockPtr->getPointeeType();
2176 else
Douglas Gregora119f102008-12-19 19:13:09 +00002177 return false;
2178
Douglas Gregora119f102008-12-19 19:13:09 +00002179 // If we have pointers to pointers, recursively check whether this
2180 // is an Objective-C conversion.
2181 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2182 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2183 IncompatibleObjC)) {
2184 // We always complain about this conversion.
2185 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002186 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002187 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002188 return true;
2189 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002190 // Allow conversion of pointee being objective-c pointer to another one;
2191 // as in I* to id.
2192 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2193 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2194 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2195 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002196
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002197 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002198 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002199 return true;
2200 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002201
Douglas Gregor033f56d2008-12-23 00:53:59 +00002202 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002203 // differences in the argument and result types are in Objective-C
2204 // pointer conversions. If so, we permit the conversion (but
2205 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002206 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002207 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002208 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002209 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002210 if (FromFunctionType && ToFunctionType) {
2211 // If the function types are exactly the same, this isn't an
2212 // Objective-C pointer conversion.
2213 if (Context.getCanonicalType(FromPointeeType)
2214 == Context.getCanonicalType(ToPointeeType))
2215 return false;
2216
2217 // Perform the quick checks that will tell us whether these
2218 // function types are obviously different.
2219 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2220 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2221 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2222 return false;
2223
2224 bool HasObjCConversion = false;
2225 if (Context.getCanonicalType(FromFunctionType->getResultType())
2226 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2227 // Okay, the types match exactly. Nothing to do.
2228 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2229 ToFunctionType->getResultType(),
2230 ConvertedType, IncompatibleObjC)) {
2231 // Okay, we have an Objective-C pointer conversion.
2232 HasObjCConversion = true;
2233 } else {
2234 // Function types are too different. Abort.
2235 return false;
2236 }
Mike Stump11289f42009-09-09 15:08:12 +00002237
Douglas Gregora119f102008-12-19 19:13:09 +00002238 // Check argument types.
2239 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2240 ArgIdx != NumArgs; ++ArgIdx) {
2241 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2242 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2243 if (Context.getCanonicalType(FromArgType)
2244 == Context.getCanonicalType(ToArgType)) {
2245 // Okay, the types match exactly. Nothing to do.
2246 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2247 ConvertedType, IncompatibleObjC)) {
2248 // Okay, we have an Objective-C pointer conversion.
2249 HasObjCConversion = true;
2250 } else {
2251 // Argument types are too different. Abort.
2252 return false;
2253 }
2254 }
2255
2256 if (HasObjCConversion) {
2257 // We had an Objective-C conversion. Allow this pointer
2258 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002259 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002260 IncompatibleObjC = true;
2261 return true;
2262 }
2263 }
2264
Sebastian Redl72b597d2009-01-25 19:43:20 +00002265 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002266}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002267
John McCall31168b02011-06-15 23:02:42 +00002268/// \brief Determine whether this is an Objective-C writeback conversion,
2269/// used for parameter passing when performing automatic reference counting.
2270///
2271/// \param FromType The type we're converting form.
2272///
2273/// \param ToType The type we're converting to.
2274///
2275/// \param ConvertedType The type that will be produced after applying
2276/// this conversion.
2277bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2278 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002279 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002280 Context.hasSameUnqualifiedType(FromType, ToType))
2281 return false;
2282
2283 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2284 QualType ToPointee;
2285 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2286 ToPointee = ToPointer->getPointeeType();
2287 else
2288 return false;
2289
2290 Qualifiers ToQuals = ToPointee.getQualifiers();
2291 if (!ToPointee->isObjCLifetimeType() ||
2292 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002293 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002294 return false;
2295
2296 // Argument must be a pointer to __strong to __weak.
2297 QualType FromPointee;
2298 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2299 FromPointee = FromPointer->getPointeeType();
2300 else
2301 return false;
2302
2303 Qualifiers FromQuals = FromPointee.getQualifiers();
2304 if (!FromPointee->isObjCLifetimeType() ||
2305 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2306 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2307 return false;
2308
2309 // Make sure that we have compatible qualifiers.
2310 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2311 if (!ToQuals.compatiblyIncludes(FromQuals))
2312 return false;
2313
2314 // Remove qualifiers from the pointee type we're converting from; they
2315 // aren't used in the compatibility check belong, and we'll be adding back
2316 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2317 FromPointee = FromPointee.getUnqualifiedType();
2318
2319 // The unqualified form of the pointee types must be compatible.
2320 ToPointee = ToPointee.getUnqualifiedType();
2321 bool IncompatibleObjC;
2322 if (Context.typesAreCompatible(FromPointee, ToPointee))
2323 FromPointee = ToPointee;
2324 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2325 IncompatibleObjC))
2326 return false;
2327
2328 /// \brief Construct the type we're converting to, which is a pointer to
2329 /// __autoreleasing pointee.
2330 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2331 ConvertedType = Context.getPointerType(FromPointee);
2332 return true;
2333}
2334
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002335bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2336 QualType& ConvertedType) {
2337 QualType ToPointeeType;
2338 if (const BlockPointerType *ToBlockPtr =
2339 ToType->getAs<BlockPointerType>())
2340 ToPointeeType = ToBlockPtr->getPointeeType();
2341 else
2342 return false;
2343
2344 QualType FromPointeeType;
2345 if (const BlockPointerType *FromBlockPtr =
2346 FromType->getAs<BlockPointerType>())
2347 FromPointeeType = FromBlockPtr->getPointeeType();
2348 else
2349 return false;
2350 // We have pointer to blocks, check whether the only
2351 // differences in the argument and result types are in Objective-C
2352 // pointer conversions. If so, we permit the conversion.
2353
2354 const FunctionProtoType *FromFunctionType
2355 = FromPointeeType->getAs<FunctionProtoType>();
2356 const FunctionProtoType *ToFunctionType
2357 = ToPointeeType->getAs<FunctionProtoType>();
2358
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002359 if (!FromFunctionType || !ToFunctionType)
2360 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002361
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002362 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002363 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002364
2365 // Perform the quick checks that will tell us whether these
2366 // function types are obviously different.
2367 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2368 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2369 return false;
2370
2371 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2372 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2373 if (FromEInfo != ToEInfo)
2374 return false;
2375
2376 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002377 if (Context.hasSameType(FromFunctionType->getResultType(),
2378 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002379 // Okay, the types match exactly. Nothing to do.
2380 } else {
2381 QualType RHS = FromFunctionType->getResultType();
2382 QualType LHS = ToFunctionType->getResultType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002383 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002384 !RHS.hasQualifiers() && LHS.hasQualifiers())
2385 LHS = LHS.getUnqualifiedType();
2386
2387 if (Context.hasSameType(RHS,LHS)) {
2388 // OK exact match.
2389 } else if (isObjCPointerConversion(RHS, LHS,
2390 ConvertedType, IncompatibleObjC)) {
2391 if (IncompatibleObjC)
2392 return false;
2393 // Okay, we have an Objective-C pointer conversion.
2394 }
2395 else
2396 return false;
2397 }
2398
2399 // Check argument types.
2400 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2401 ArgIdx != NumArgs; ++ArgIdx) {
2402 IncompatibleObjC = false;
2403 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2404 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2405 if (Context.hasSameType(FromArgType, ToArgType)) {
2406 // Okay, the types match exactly. Nothing to do.
2407 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2408 ConvertedType, IncompatibleObjC)) {
2409 if (IncompatibleObjC)
2410 return false;
2411 // Okay, we have an Objective-C pointer conversion.
2412 } else
2413 // Argument types are too different. Abort.
2414 return false;
2415 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002416 if (LangOpts.ObjCAutoRefCount &&
2417 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2418 ToFunctionType))
2419 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002420
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002421 ConvertedType = ToType;
2422 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002423}
2424
Richard Trieucaff2472011-11-23 22:32:32 +00002425enum {
2426 ft_default,
2427 ft_different_class,
2428 ft_parameter_arity,
2429 ft_parameter_mismatch,
2430 ft_return_type,
2431 ft_qualifer_mismatch
2432};
2433
2434/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2435/// function types. Catches different number of parameter, mismatch in
2436/// parameter types, and different return types.
2437void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2438 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002439 // If either type is not valid, include no extra info.
2440 if (FromType.isNull() || ToType.isNull()) {
2441 PDiag << ft_default;
2442 return;
2443 }
2444
Richard Trieucaff2472011-11-23 22:32:32 +00002445 // Get the function type from the pointers.
2446 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2447 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2448 *ToMember = ToType->getAs<MemberPointerType>();
2449 if (FromMember->getClass() != ToMember->getClass()) {
2450 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2451 << QualType(FromMember->getClass(), 0);
2452 return;
2453 }
2454 FromType = FromMember->getPointeeType();
2455 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002456 }
2457
Richard Trieu96ed5b62011-12-13 23:19:45 +00002458 if (FromType->isPointerType())
2459 FromType = FromType->getPointeeType();
2460 if (ToType->isPointerType())
2461 ToType = ToType->getPointeeType();
2462
2463 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002464 FromType = FromType.getNonReferenceType();
2465 ToType = ToType.getNonReferenceType();
2466
Richard Trieucaff2472011-11-23 22:32:32 +00002467 // Don't print extra info for non-specialized template functions.
2468 if (FromType->isInstantiationDependentType() &&
2469 !FromType->getAs<TemplateSpecializationType>()) {
2470 PDiag << ft_default;
2471 return;
2472 }
2473
Richard Trieu96ed5b62011-12-13 23:19:45 +00002474 // No extra info for same types.
2475 if (Context.hasSameType(FromType, ToType)) {
2476 PDiag << ft_default;
2477 return;
2478 }
2479
Richard Trieucaff2472011-11-23 22:32:32 +00002480 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2481 *ToFunction = ToType->getAs<FunctionProtoType>();
2482
2483 // Both types need to be function types.
2484 if (!FromFunction || !ToFunction) {
2485 PDiag << ft_default;
2486 return;
2487 }
2488
2489 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2490 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2491 << FromFunction->getNumArgs();
2492 return;
2493 }
2494
2495 // Handle different parameter types.
2496 unsigned ArgPos;
2497 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2498 PDiag << ft_parameter_mismatch << ArgPos + 1
2499 << ToFunction->getArgType(ArgPos)
2500 << FromFunction->getArgType(ArgPos);
2501 return;
2502 }
2503
2504 // Handle different return type.
2505 if (!Context.hasSameType(FromFunction->getResultType(),
2506 ToFunction->getResultType())) {
2507 PDiag << ft_return_type << ToFunction->getResultType()
2508 << FromFunction->getResultType();
2509 return;
2510 }
2511
2512 unsigned FromQuals = FromFunction->getTypeQuals(),
2513 ToQuals = ToFunction->getTypeQuals();
2514 if (FromQuals != ToQuals) {
2515 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2516 return;
2517 }
2518
2519 // Unable to find a difference, so add no extra info.
2520 PDiag << ft_default;
2521}
2522
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002523/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002524/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002525/// they have same number of arguments. This routine assumes that Objective-C
2526/// pointer types which only differ in their protocol qualifiers are equal.
Sylvestre Ledru830885c2012-07-23 08:59:39 +00002527/// If the parameters are different, ArgPos will have the parameter index
Richard Trieucaff2472011-11-23 22:32:32 +00002528/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002529bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002530 const FunctionProtoType *NewType,
2531 unsigned *ArgPos) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002532 if (!getLangOpts().ObjC1) {
Richard Trieucaff2472011-11-23 22:32:32 +00002533 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2534 N = NewType->arg_type_begin(),
2535 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2536 if (!Context.hasSameType(*O, *N)) {
2537 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2538 return false;
2539 }
2540 }
2541 return true;
2542 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002543
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002544 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2545 N = NewType->arg_type_begin(),
2546 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2547 QualType ToType = (*O);
2548 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002549 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002550 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2551 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002552 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2553 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2554 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2555 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002556 continue;
2557 }
John McCall8b07ec22010-05-15 11:32:37 +00002558 else if (const ObjCObjectPointerType *PTTo =
2559 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002560 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002561 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002562 if (Context.hasSameUnqualifiedType(
2563 PTTo->getObjectType()->getBaseType(),
2564 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002565 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002566 }
Richard Trieucaff2472011-11-23 22:32:32 +00002567 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002568 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002569 }
2570 }
2571 return true;
2572}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002573
Douglas Gregor39c16d42008-10-24 04:54:22 +00002574/// CheckPointerConversion - Check the pointer conversion from the
2575/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002576/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002577/// conversions for which IsPointerConversion has already returned
2578/// true. It returns true and produces a diagnostic if there was an
2579/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002580bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002581 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002582 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002583 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002584 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002585 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002586
John McCall8cb679e2010-11-15 09:13:47 +00002587 Kind = CK_BitCast;
2588
David Blaikie1c7c8f72012-08-08 17:33:31 +00002589 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2590 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2591 Expr::NPCK_ZeroExpression) {
2592 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2593 DiagRuntimeBehavior(From->getExprLoc(), From,
2594 PDiag(diag::warn_impcast_bool_to_null_pointer)
2595 << ToType << From->getSourceRange());
2596 else if (!isUnevaluatedContext())
2597 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2598 << ToType << From->getSourceRange();
2599 }
John McCall9320b872011-09-09 05:25:32 +00002600 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2601 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002602 QualType FromPointeeType = FromPtrType->getPointeeType(),
2603 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002604
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002605 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2606 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002607 // We must have a derived-to-base conversion. Check an
2608 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002609 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2610 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002611 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002612 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002613 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002614
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002615 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002616 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002617 }
2618 }
John McCall9320b872011-09-09 05:25:32 +00002619 } else if (const ObjCObjectPointerType *ToPtrType =
2620 ToType->getAs<ObjCObjectPointerType>()) {
2621 if (const ObjCObjectPointerType *FromPtrType =
2622 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002623 // Objective-C++ conversions are always okay.
2624 // FIXME: We should have a different class of conversions for the
2625 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002626 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002627 return false;
John McCall9320b872011-09-09 05:25:32 +00002628 } else if (FromType->isBlockPointerType()) {
2629 Kind = CK_BlockPointerToObjCPointerCast;
2630 } else {
2631 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002632 }
John McCall9320b872011-09-09 05:25:32 +00002633 } else if (ToType->isBlockPointerType()) {
2634 if (!FromType->isBlockPointerType())
2635 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002636 }
John McCall8cb679e2010-11-15 09:13:47 +00002637
2638 // We shouldn't fall into this case unless it's valid for other
2639 // reasons.
2640 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2641 Kind = CK_NullToPointer;
2642
Douglas Gregor39c16d42008-10-24 04:54:22 +00002643 return false;
2644}
2645
Sebastian Redl72b597d2009-01-25 19:43:20 +00002646/// IsMemberPointerConversion - Determines whether the conversion of the
2647/// expression From, which has the (possibly adjusted) type FromType, can be
2648/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2649/// If so, returns true and places the converted type (that might differ from
2650/// ToType in its cv-qualifiers at some level) into ConvertedType.
2651bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002652 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002653 bool InOverloadResolution,
2654 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002655 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002656 if (!ToTypePtr)
2657 return false;
2658
2659 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002660 if (From->isNullPointerConstant(Context,
2661 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2662 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002663 ConvertedType = ToType;
2664 return true;
2665 }
2666
2667 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002668 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002669 if (!FromTypePtr)
2670 return false;
2671
2672 // A pointer to member of B can be converted to a pointer to member of D,
2673 // where D is derived from B (C++ 4.11p2).
2674 QualType FromClass(FromTypePtr->getClass(), 0);
2675 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002676
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002677 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002678 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002679 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002680 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2681 ToClass.getTypePtr());
2682 return true;
2683 }
2684
2685 return false;
2686}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002687
Sebastian Redl72b597d2009-01-25 19:43:20 +00002688/// CheckMemberPointerConversion - Check the member pointer conversion from the
2689/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002690/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002691/// for which IsMemberPointerConversion has already returned true. It returns
2692/// true and produces a diagnostic if there was an error, or returns false
2693/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002694bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002695 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002696 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002697 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002698 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002699 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002700 if (!FromPtrType) {
2701 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002702 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002703 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002704 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002705 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002706 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002707 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002708
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002709 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002710 assert(ToPtrType && "No member pointer cast has a target type "
2711 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002712
Sebastian Redled8f2002009-01-28 18:33:18 +00002713 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2714 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002715
Sebastian Redled8f2002009-01-28 18:33:18 +00002716 // FIXME: What about dependent types?
2717 assert(FromClass->isRecordType() && "Pointer into non-class.");
2718 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002719
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002720 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002721 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002722 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2723 assert(DerivationOkay &&
2724 "Should not have been called if derivation isn't OK.");
2725 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002726
Sebastian Redled8f2002009-01-28 18:33:18 +00002727 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2728 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002729 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2730 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2731 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2732 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002733 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002734
Douglas Gregor89ee6822009-02-28 01:32:25 +00002735 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002736 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2737 << FromClass << ToClass << QualType(VBase, 0)
2738 << From->getSourceRange();
2739 return true;
2740 }
2741
John McCall5b0829a2010-02-10 09:31:12 +00002742 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002743 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2744 Paths.front(),
2745 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002746
Anders Carlssond7923c62009-08-22 23:33:40 +00002747 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002748 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002749 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002750 return false;
2751}
2752
Douglas Gregor9a657932008-10-21 23:43:52 +00002753/// IsQualificationConversion - Determines whether the conversion from
2754/// an rvalue of type FromType to ToType is a qualification conversion
2755/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002756///
2757/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2758/// when the qualification conversion involves a change in the Objective-C
2759/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002760bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002761Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002762 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002763 FromType = Context.getCanonicalType(FromType);
2764 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002765 ObjCLifetimeConversion = false;
2766
Douglas Gregor9a657932008-10-21 23:43:52 +00002767 // If FromType and ToType are the same type, this is not a
2768 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002769 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002770 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002771
Douglas Gregor9a657932008-10-21 23:43:52 +00002772 // (C++ 4.4p4):
2773 // A conversion can add cv-qualifiers at levels other than the first
2774 // in multi-level pointers, subject to the following rules: [...]
2775 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002776 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002777 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002778 // Within each iteration of the loop, we check the qualifiers to
2779 // determine if this still looks like a qualification
2780 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002781 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002782 // until there are no more pointers or pointers-to-members left to
2783 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002784 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002785
Douglas Gregor90609aa2011-04-25 18:40:17 +00002786 Qualifiers FromQuals = FromType.getQualifiers();
2787 Qualifiers ToQuals = ToType.getQualifiers();
2788
John McCall31168b02011-06-15 23:02:42 +00002789 // Objective-C ARC:
2790 // Check Objective-C lifetime conversions.
2791 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2792 UnwrappedAnyPointer) {
2793 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2794 ObjCLifetimeConversion = true;
2795 FromQuals.removeObjCLifetime();
2796 ToQuals.removeObjCLifetime();
2797 } else {
2798 // Qualification conversions cannot cast between different
2799 // Objective-C lifetime qualifiers.
2800 return false;
2801 }
2802 }
2803
Douglas Gregorf30053d2011-05-08 06:09:53 +00002804 // Allow addition/removal of GC attributes but not changing GC attributes.
2805 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2806 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2807 FromQuals.removeObjCGCAttr();
2808 ToQuals.removeObjCGCAttr();
2809 }
2810
Douglas Gregor9a657932008-10-21 23:43:52 +00002811 // -- for every j > 0, if const is in cv 1,j then const is in cv
2812 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002813 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002814 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002815
Douglas Gregor9a657932008-10-21 23:43:52 +00002816 // -- if the cv 1,j and cv 2,j are different, then const is in
2817 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002818 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002819 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002820 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002821
Douglas Gregor9a657932008-10-21 23:43:52 +00002822 // Keep track of whether all prior cv-qualifiers in the "to" type
2823 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002824 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002825 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002826 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002827
2828 // We are left with FromType and ToType being the pointee types
2829 // after unwrapping the original FromType and ToType the same number
2830 // of types. If we unwrapped any pointers, and if FromType and
2831 // ToType have the same unqualified type (since we checked
2832 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002833 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002834}
2835
Douglas Gregorc79862f2012-04-12 17:51:55 +00002836/// \brief - Determine whether this is a conversion from a scalar type to an
2837/// atomic type.
2838///
2839/// If successful, updates \c SCS's second and third steps in the conversion
2840/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002841static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2842 bool InOverloadResolution,
2843 StandardConversionSequence &SCS,
2844 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002845 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2846 if (!ToAtomic)
2847 return false;
2848
2849 StandardConversionSequence InnerSCS;
2850 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2851 InOverloadResolution, InnerSCS,
2852 CStyle, /*AllowObjCWritebackConversion=*/false))
2853 return false;
2854
2855 SCS.Second = InnerSCS.Second;
2856 SCS.setToType(1, InnerSCS.getToType(1));
2857 SCS.Third = InnerSCS.Third;
2858 SCS.QualificationIncludesObjCLifetime
2859 = InnerSCS.QualificationIncludesObjCLifetime;
2860 SCS.setToType(2, InnerSCS.getToType(2));
2861 return true;
2862}
2863
Sebastian Redle5417162012-03-27 18:33:03 +00002864static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2865 CXXConstructorDecl *Constructor,
2866 QualType Type) {
2867 const FunctionProtoType *CtorType =
2868 Constructor->getType()->getAs<FunctionProtoType>();
2869 if (CtorType->getNumArgs() > 0) {
2870 QualType FirstArg = CtorType->getArgType(0);
2871 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2872 return true;
2873 }
2874 return false;
2875}
2876
Sebastian Redl82ace982012-02-11 23:51:08 +00002877static OverloadingResult
2878IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2879 CXXRecordDecl *To,
2880 UserDefinedConversionSequence &User,
2881 OverloadCandidateSet &CandidateSet,
2882 bool AllowExplicit) {
2883 DeclContext::lookup_iterator Con, ConEnd;
2884 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2885 Con != ConEnd; ++Con) {
2886 NamedDecl *D = *Con;
2887 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2888
2889 // Find the constructor (which may be a template).
2890 CXXConstructorDecl *Constructor = 0;
2891 FunctionTemplateDecl *ConstructorTmpl
2892 = dyn_cast<FunctionTemplateDecl>(D);
2893 if (ConstructorTmpl)
2894 Constructor
2895 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2896 else
2897 Constructor = cast<CXXConstructorDecl>(D);
2898
2899 bool Usable = !Constructor->isInvalidDecl() &&
2900 S.isInitListConstructor(Constructor) &&
2901 (AllowExplicit || !Constructor->isExplicit());
2902 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002903 // If the first argument is (a reference to) the target type,
2904 // suppress conversions.
2905 bool SuppressUserConversions =
2906 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002907 if (ConstructorTmpl)
2908 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2909 /*ExplicitArgs*/ 0,
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 else
2913 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002914 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002915 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002916 }
2917 }
2918
2919 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2920
2921 OverloadCandidateSet::iterator Best;
2922 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2923 case OR_Success: {
2924 // Record the standard conversion we used and the conversion function.
2925 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002926 QualType ThisType = Constructor->getThisType(S.Context);
2927 // Initializer lists don't have conversions as such.
2928 User.Before.setAsIdentityConversion();
2929 User.HadMultipleCandidates = HadMultipleCandidates;
2930 User.ConversionFunction = Constructor;
2931 User.FoundConversionFunction = Best->FoundDecl;
2932 User.After.setAsIdentityConversion();
2933 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2934 User.After.setAllToTypes(ToType);
2935 return OR_Success;
2936 }
2937
2938 case OR_No_Viable_Function:
2939 return OR_No_Viable_Function;
2940 case OR_Deleted:
2941 return OR_Deleted;
2942 case OR_Ambiguous:
2943 return OR_Ambiguous;
2944 }
2945
2946 llvm_unreachable("Invalid OverloadResult!");
2947}
2948
Douglas Gregor576e98c2009-01-30 23:27:23 +00002949/// Determines whether there is a user-defined conversion sequence
2950/// (C++ [over.ics.user]) that converts expression From to the type
2951/// ToType. If such a conversion exists, User will contain the
2952/// user-defined conversion sequence that performs such a conversion
2953/// and this routine will return true. Otherwise, this routine returns
2954/// false and User is unspecified.
2955///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002956/// \param AllowExplicit true if the conversion should consider C++0x
2957/// "explicit" conversion functions as well as non-explicit conversion
2958/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002959static OverloadingResult
2960IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002961 UserDefinedConversionSequence &User,
2962 OverloadCandidateSet &CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002963 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002964 // Whether we will only visit constructors.
2965 bool ConstructorsOnly = false;
2966
2967 // If the type we are conversion to is a class type, enumerate its
2968 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002969 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002970 // C++ [over.match.ctor]p1:
2971 // When objects of class type are direct-initialized (8.5), or
2972 // copy-initialized from an expression of the same or a
2973 // derived class type (8.5), overload resolution selects the
2974 // constructor. [...] For copy-initialization, the candidate
2975 // functions are all the converting constructors (12.3.1) of
2976 // that class. The argument list is the expression-list within
2977 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002978 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002979 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002980 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002981 ConstructorsOnly = true;
2982
Benjamin Kramer90633e32012-11-23 17:04:52 +00002983 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002984 // RequireCompleteType may have returned true due to some invalid decl
2985 // during template instantiation, but ToType may be complete enough now
2986 // to try to recover.
2987 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002988 // We're not going to find any constructors.
2989 } else if (CXXRecordDecl *ToRecordDecl
2990 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002991
2992 Expr **Args = &From;
2993 unsigned NumArgs = 1;
2994 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002995 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl82ace982012-02-11 23:51:08 +00002996 // But first, see if there is an init-list-contructor that will work.
2997 OverloadingResult Result = IsInitializerListConstructorConversion(
2998 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2999 if (Result != OR_No_Viable_Function)
3000 return Result;
3001 // Never mind.
3002 CandidateSet.clear();
3003
3004 // If we're list-initializing, we pass the individual elements as
3005 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003006 Args = InitList->getInits();
3007 NumArgs = InitList->getNumInits();
3008 ListInitializing = true;
3009 }
3010
Douglas Gregor89ee6822009-02-28 01:32:25 +00003011 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00003012 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00003013 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003014 NamedDecl *D = *Con;
3015 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3016
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003017 // Find the constructor (which may be a template).
3018 CXXConstructorDecl *Constructor = 0;
3019 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003020 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003021 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003022 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003023 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3024 else
John McCalla0296f72010-03-19 07:35:19 +00003025 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003026
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003027 bool Usable = !Constructor->isInvalidDecl();
3028 if (ListInitializing)
3029 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3030 else
3031 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3032 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003033 bool SuppressUserConversions = !ConstructorsOnly;
3034 if (SuppressUserConversions && ListInitializing) {
3035 SuppressUserConversions = false;
3036 if (NumArgs == 1) {
3037 // If the first argument is (a reference to) the target type,
3038 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003039 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3040 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003041 }
3042 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003043 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003044 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3045 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003046 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003047 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003048 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003049 // Allow one user-defined conversion when user specifies a
3050 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003051 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003052 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003053 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003054 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003055 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003056 }
3057 }
3058
Douglas Gregor5ab11652010-04-17 22:01:05 +00003059 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003060 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003061 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003062 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003063 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003064 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003065 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003066 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3067 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003068 std::pair<CXXRecordDecl::conversion_iterator,
3069 CXXRecordDecl::conversion_iterator>
3070 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3071 for (CXXRecordDecl::conversion_iterator
3072 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003073 DeclAccessPair FoundDecl = I.getPair();
3074 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003075 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3076 if (isa<UsingShadowDecl>(D))
3077 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3078
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003079 CXXConversionDecl *Conv;
3080 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003081 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3082 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003083 else
John McCallda4458e2010-03-31 01:36:47 +00003084 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003085
3086 if (AllowExplicit || !Conv->isExplicit()) {
3087 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003088 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3089 ActingContext, From, ToType,
3090 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003091 else
John McCall5c32be02010-08-24 20:38:10 +00003092 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3093 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003094 }
3095 }
3096 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003097 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003098
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003099 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3100
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003101 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003102 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003103 case OR_Success:
3104 // Record the standard conversion we used and the conversion function.
3105 if (CXXConstructorDecl *Constructor
3106 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3107 // C++ [over.ics.user]p1:
3108 // If the user-defined conversion is specified by a
3109 // constructor (12.3.1), the initial standard conversion
3110 // sequence converts the source type to the type required by
3111 // the argument of the constructor.
3112 //
3113 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003114 if (isa<InitListExpr>(From)) {
3115 // Initializer lists don't have conversions as such.
3116 User.Before.setAsIdentityConversion();
3117 } else {
3118 if (Best->Conversions[0].isEllipsis())
3119 User.EllipsisConversion = true;
3120 else {
3121 User.Before = Best->Conversions[0].Standard;
3122 User.EllipsisConversion = false;
3123 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003124 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003125 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003126 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003127 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003128 User.After.setAsIdentityConversion();
3129 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3130 User.After.setAllToTypes(ToType);
3131 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003132 }
3133 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003134 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3135 // C++ [over.ics.user]p1:
3136 //
3137 // [...] If the user-defined conversion is specified by a
3138 // conversion function (12.3.2), the initial standard
3139 // conversion sequence converts the source type to the
3140 // implicit object parameter of the conversion function.
3141 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003142 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003143 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003144 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003145 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003146
John McCall5c32be02010-08-24 20:38:10 +00003147 // C++ [over.ics.user]p2:
3148 // The second standard conversion sequence converts the
3149 // result of the user-defined conversion to the target type
3150 // for the sequence. Since an implicit conversion sequence
3151 // is an initialization, the special rules for
3152 // initialization by user-defined conversion apply when
3153 // selecting the best user-defined conversion for a
3154 // user-defined conversion sequence (see 13.3.3 and
3155 // 13.3.3.1).
3156 User.After = Best->FinalConversion;
3157 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003158 }
David Blaikie8a40f702012-01-17 06:56:22 +00003159 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003160
John McCall5c32be02010-08-24 20:38:10 +00003161 case OR_No_Viable_Function:
3162 return OR_No_Viable_Function;
3163 case OR_Deleted:
3164 // No conversion here! We're done.
3165 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003166
John McCall5c32be02010-08-24 20:38:10 +00003167 case OR_Ambiguous:
3168 return OR_Ambiguous;
3169 }
3170
David Blaikie8a40f702012-01-17 06:56:22 +00003171 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003172}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003173
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003174bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003175Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003176 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003177 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003178 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003179 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00003180 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003181 if (OvResult == OR_Ambiguous)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003182 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003183 diag::err_typecheck_ambiguous_condition)
3184 << From->getType() << ToType << From->getSourceRange();
3185 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003186 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003187 diag::err_typecheck_nonviable_condition)
3188 << From->getType() << ToType << From->getSourceRange();
3189 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003190 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003191 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003192 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003193}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003194
Douglas Gregor2837aa22012-02-22 17:32:19 +00003195/// \brief Compare the user-defined conversion functions or constructors
3196/// of two user-defined conversion sequences to determine whether any ordering
3197/// is possible.
3198static ImplicitConversionSequence::CompareKind
3199compareConversionFunctions(Sema &S,
3200 FunctionDecl *Function1,
3201 FunctionDecl *Function2) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003202 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003203 return ImplicitConversionSequence::Indistinguishable;
3204
3205 // Objective-C++:
3206 // If both conversion functions are implicitly-declared conversions from
3207 // a lambda closure type to a function pointer and a block pointer,
3208 // respectively, always prefer the conversion to a function pointer,
3209 // because the function pointer is more lightweight and is more likely
3210 // to keep code working.
3211 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3212 if (!Conv1)
3213 return ImplicitConversionSequence::Indistinguishable;
3214
3215 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3216 if (!Conv2)
3217 return ImplicitConversionSequence::Indistinguishable;
3218
3219 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3220 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3221 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3222 if (Block1 != Block2)
3223 return Block1? ImplicitConversionSequence::Worse
3224 : ImplicitConversionSequence::Better;
3225 }
3226
3227 return ImplicitConversionSequence::Indistinguishable;
3228}
3229
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003230/// CompareImplicitConversionSequences - Compare two implicit
3231/// conversion sequences to determine whether one is better than the
3232/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003233static ImplicitConversionSequence::CompareKind
3234CompareImplicitConversionSequences(Sema &S,
3235 const ImplicitConversionSequence& ICS1,
3236 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003237{
3238 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3239 // conversion sequences (as defined in 13.3.3.1)
3240 // -- a standard conversion sequence (13.3.3.1.1) is a better
3241 // conversion sequence than a user-defined conversion sequence or
3242 // an ellipsis conversion sequence, and
3243 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3244 // conversion sequence than an ellipsis conversion sequence
3245 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003246 //
John McCall0d1da222010-01-12 00:44:57 +00003247 // C++0x [over.best.ics]p10:
3248 // For the purpose of ranking implicit conversion sequences as
3249 // described in 13.3.3.2, the ambiguous conversion sequence is
3250 // treated as a user-defined sequence that is indistinguishable
3251 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00003252 if (ICS1.getKindRank() < ICS2.getKindRank())
3253 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003254 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003255 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003256
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003257 // The following checks require both conversion sequences to be of
3258 // the same kind.
3259 if (ICS1.getKind() != ICS2.getKind())
3260 return ImplicitConversionSequence::Indistinguishable;
3261
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003262 ImplicitConversionSequence::CompareKind Result =
3263 ImplicitConversionSequence::Indistinguishable;
3264
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003265 // Two implicit conversion sequences of the same form are
3266 // indistinguishable conversion sequences unless one of the
3267 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003268 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003269 Result = CompareStandardConversionSequences(S,
3270 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003271 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003272 // User-defined conversion sequence U1 is a better conversion
3273 // sequence than another user-defined conversion sequence U2 if
3274 // they contain the same user-defined conversion function or
3275 // constructor and if the second standard conversion sequence of
3276 // U1 is better than the second standard conversion sequence of
3277 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003278 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003279 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003280 Result = CompareStandardConversionSequences(S,
3281 ICS1.UserDefined.After,
3282 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003283 else
3284 Result = compareConversionFunctions(S,
3285 ICS1.UserDefined.ConversionFunction,
3286 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003287 }
3288
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003289 // List-initialization sequence L1 is a better conversion sequence than
3290 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3291 // for some X and L2 does not.
3292 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003293 !ICS1.isBad() &&
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003294 ICS1.isListInitializationSequence() &&
3295 ICS2.isListInitializationSequence()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003296 if (ICS1.isStdInitializerListElement() &&
3297 !ICS2.isStdInitializerListElement())
3298 return ImplicitConversionSequence::Better;
3299 if (!ICS1.isStdInitializerListElement() &&
3300 ICS2.isStdInitializerListElement())
3301 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003302 }
3303
3304 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003305}
3306
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003307static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3308 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3309 Qualifiers Quals;
3310 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003311 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003313
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003314 return Context.hasSameUnqualifiedType(T1, T2);
3315}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003316
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003317// Per 13.3.3.2p3, compare the given standard conversion sequences to
3318// determine if one is a proper subset of the other.
3319static ImplicitConversionSequence::CompareKind
3320compareStandardConversionSubsets(ASTContext &Context,
3321 const StandardConversionSequence& SCS1,
3322 const StandardConversionSequence& SCS2) {
3323 ImplicitConversionSequence::CompareKind Result
3324 = ImplicitConversionSequence::Indistinguishable;
3325
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003326 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003327 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003328 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3329 return ImplicitConversionSequence::Better;
3330 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3331 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003332
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003333 if (SCS1.Second != SCS2.Second) {
3334 if (SCS1.Second == ICK_Identity)
3335 Result = ImplicitConversionSequence::Better;
3336 else if (SCS2.Second == ICK_Identity)
3337 Result = ImplicitConversionSequence::Worse;
3338 else
3339 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003340 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003341 return ImplicitConversionSequence::Indistinguishable;
3342
3343 if (SCS1.Third == SCS2.Third) {
3344 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3345 : ImplicitConversionSequence::Indistinguishable;
3346 }
3347
3348 if (SCS1.Third == ICK_Identity)
3349 return Result == ImplicitConversionSequence::Worse
3350 ? ImplicitConversionSequence::Indistinguishable
3351 : ImplicitConversionSequence::Better;
3352
3353 if (SCS2.Third == ICK_Identity)
3354 return Result == ImplicitConversionSequence::Better
3355 ? ImplicitConversionSequence::Indistinguishable
3356 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003357
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003358 return ImplicitConversionSequence::Indistinguishable;
3359}
3360
Douglas Gregore696ebb2011-01-26 14:52:12 +00003361/// \brief Determine whether one of the given reference bindings is better
3362/// than the other based on what kind of bindings they are.
3363static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3364 const StandardConversionSequence &SCS2) {
3365 // C++0x [over.ics.rank]p3b4:
3366 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3367 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003368 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003369 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003370 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003371 // reference*.
3372 //
3373 // FIXME: Rvalue references. We're going rogue with the above edits,
3374 // because the semantics in the current C++0x working paper (N3225 at the
3375 // time of this writing) break the standard definition of std::forward
3376 // and std::reference_wrapper when dealing with references to functions.
3377 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003378 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3379 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3380 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003381
Douglas Gregore696ebb2011-01-26 14:52:12 +00003382 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3383 SCS2.IsLvalueReference) ||
3384 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3385 !SCS2.IsLvalueReference);
3386}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003387
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003388/// CompareStandardConversionSequences - Compare two standard
3389/// conversion sequences to determine whether one is better than the
3390/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003391static ImplicitConversionSequence::CompareKind
3392CompareStandardConversionSequences(Sema &S,
3393 const StandardConversionSequence& SCS1,
3394 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003395{
3396 // Standard conversion sequence S1 is a better conversion sequence
3397 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3398
3399 // -- S1 is a proper subsequence of S2 (comparing the conversion
3400 // sequences in the canonical form defined by 13.3.3.1.1,
3401 // excluding any Lvalue Transformation; the identity conversion
3402 // sequence is considered to be a subsequence of any
3403 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003404 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003405 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003406 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003407
3408 // -- the rank of S1 is better than the rank of S2 (by the rules
3409 // defined below), or, if not that,
3410 ImplicitConversionRank Rank1 = SCS1.getRank();
3411 ImplicitConversionRank Rank2 = SCS2.getRank();
3412 if (Rank1 < Rank2)
3413 return ImplicitConversionSequence::Better;
3414 else if (Rank2 < Rank1)
3415 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003416
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003417 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3418 // are indistinguishable unless one of the following rules
3419 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003420
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003421 // A conversion that is not a conversion of a pointer, or
3422 // pointer to member, to bool is better than another conversion
3423 // that is such a conversion.
3424 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3425 return SCS2.isPointerConversionToBool()
3426 ? ImplicitConversionSequence::Better
3427 : ImplicitConversionSequence::Worse;
3428
Douglas Gregor5c407d92008-10-23 00:40:37 +00003429 // C++ [over.ics.rank]p4b2:
3430 //
3431 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003432 // conversion of B* to A* is better than conversion of B* to
3433 // void*, and conversion of A* to void* is better than conversion
3434 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003435 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003436 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003437 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003438 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003439 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3440 // Exactly one of the conversion sequences is a conversion to
3441 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003442 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3443 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003444 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3445 // Neither conversion sequence converts to a void pointer; compare
3446 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003447 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003448 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003449 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003450 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3451 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003452 // Both conversion sequences are conversions to void
3453 // pointers. Compare the source types to determine if there's an
3454 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003455 QualType FromType1 = SCS1.getFromType();
3456 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003457
3458 // Adjust the types we're converting from via the array-to-pointer
3459 // conversion, if we need to.
3460 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003461 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003462 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003463 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003464
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003465 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3466 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003467
John McCall5c32be02010-08-24 20:38:10 +00003468 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003469 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003470 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003471 return ImplicitConversionSequence::Worse;
3472
3473 // Objective-C++: If one interface is more specific than the
3474 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003475 const ObjCObjectPointerType* FromObjCPtr1
3476 = FromType1->getAs<ObjCObjectPointerType>();
3477 const ObjCObjectPointerType* FromObjCPtr2
3478 = FromType2->getAs<ObjCObjectPointerType>();
3479 if (FromObjCPtr1 && FromObjCPtr2) {
3480 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3481 FromObjCPtr2);
3482 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3483 FromObjCPtr1);
3484 if (AssignLeft != AssignRight) {
3485 return AssignLeft? ImplicitConversionSequence::Better
3486 : ImplicitConversionSequence::Worse;
3487 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003488 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003489 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003490
3491 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3492 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003493 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003494 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003495 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003496
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003497 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003498 // Check for a better reference binding based on the kind of bindings.
3499 if (isBetterReferenceBindingKind(SCS1, SCS2))
3500 return ImplicitConversionSequence::Better;
3501 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3502 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003503
Sebastian Redlb28b4072009-03-22 23:49:27 +00003504 // C++ [over.ics.rank]p3b4:
3505 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3506 // which the references refer are the same type except for
3507 // top-level cv-qualifiers, and the type to which the reference
3508 // initialized by S2 refers is more cv-qualified than the type
3509 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003510 QualType T1 = SCS1.getToType(2);
3511 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003512 T1 = S.Context.getCanonicalType(T1);
3513 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003514 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003515 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3516 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003517 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003518 // Objective-C++ ARC: If the references refer to objects with different
3519 // lifetimes, prefer bindings that don't change lifetime.
3520 if (SCS1.ObjCLifetimeConversionBinding !=
3521 SCS2.ObjCLifetimeConversionBinding) {
3522 return SCS1.ObjCLifetimeConversionBinding
3523 ? ImplicitConversionSequence::Worse
3524 : ImplicitConversionSequence::Better;
3525 }
3526
Chandler Carruth8e543b32010-12-12 08:17:55 +00003527 // If the type is an array type, promote the element qualifiers to the
3528 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003529 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003530 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003531 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003532 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003533 if (T2.isMoreQualifiedThan(T1))
3534 return ImplicitConversionSequence::Better;
3535 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003536 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003537 }
3538 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003539
Francois Pichet08d2fa02011-09-18 21:37:37 +00003540 // In Microsoft mode, prefer an integral conversion to a
3541 // floating-to-integral conversion if the integral conversion
3542 // is between types of the same size.
3543 // For example:
3544 // void f(float);
3545 // void f(int);
3546 // int main {
3547 // long a;
3548 // f(a);
3549 // }
3550 // Here, MSVC will call f(int) instead of generating a compile error
3551 // as clang will do in standard mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003552 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003553 SCS1.Second == ICK_Integral_Conversion &&
3554 SCS2.Second == ICK_Floating_Integral &&
3555 S.Context.getTypeSize(SCS1.getFromType()) ==
3556 S.Context.getTypeSize(SCS1.getToType(2)))
3557 return ImplicitConversionSequence::Better;
3558
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003559 return ImplicitConversionSequence::Indistinguishable;
3560}
3561
3562/// CompareQualificationConversions - Compares two standard conversion
3563/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003564/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3565ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003566CompareQualificationConversions(Sema &S,
3567 const StandardConversionSequence& SCS1,
3568 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003569 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003570 // -- S1 and S2 differ only in their qualification conversion and
3571 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3572 // cv-qualification signature of type T1 is a proper subset of
3573 // the cv-qualification signature of type T2, and S1 is not the
3574 // deprecated string literal array-to-pointer conversion (4.2).
3575 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3576 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3577 return ImplicitConversionSequence::Indistinguishable;
3578
3579 // FIXME: the example in the standard doesn't use a qualification
3580 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003581 QualType T1 = SCS1.getToType(2);
3582 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003583 T1 = S.Context.getCanonicalType(T1);
3584 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003585 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003586 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3587 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003588
3589 // If the types are the same, we won't learn anything by unwrapped
3590 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003591 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003592 return ImplicitConversionSequence::Indistinguishable;
3593
Chandler Carruth607f38e2009-12-29 07:16:59 +00003594 // If the type is an array type, promote the element qualifiers to the type
3595 // for comparison.
3596 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003597 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003598 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003599 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003600
Mike Stump11289f42009-09-09 15:08:12 +00003601 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003602 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003603
3604 // Objective-C++ ARC:
3605 // Prefer qualification conversions not involving a change in lifetime
3606 // to qualification conversions that do not change lifetime.
3607 if (SCS1.QualificationIncludesObjCLifetime !=
3608 SCS2.QualificationIncludesObjCLifetime) {
3609 Result = SCS1.QualificationIncludesObjCLifetime
3610 ? ImplicitConversionSequence::Worse
3611 : ImplicitConversionSequence::Better;
3612 }
3613
John McCall5c32be02010-08-24 20:38:10 +00003614 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003615 // Within each iteration of the loop, we check the qualifiers to
3616 // determine if this still looks like a qualification
3617 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003618 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003619 // until there are no more pointers or pointers-to-members left
3620 // to unwrap. This essentially mimics what
3621 // IsQualificationConversion does, but here we're checking for a
3622 // strict subset of qualifiers.
3623 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3624 // The qualifiers are the same, so this doesn't tell us anything
3625 // about how the sequences rank.
3626 ;
3627 else if (T2.isMoreQualifiedThan(T1)) {
3628 // T1 has fewer qualifiers, so it could be the better sequence.
3629 if (Result == ImplicitConversionSequence::Worse)
3630 // Neither has qualifiers that are a subset of the other's
3631 // qualifiers.
3632 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003633
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003634 Result = ImplicitConversionSequence::Better;
3635 } else if (T1.isMoreQualifiedThan(T2)) {
3636 // T2 has fewer qualifiers, so it could be the better sequence.
3637 if (Result == ImplicitConversionSequence::Better)
3638 // Neither has qualifiers that are a subset of the other's
3639 // qualifiers.
3640 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003641
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003642 Result = ImplicitConversionSequence::Worse;
3643 } else {
3644 // Qualifiers are disjoint.
3645 return ImplicitConversionSequence::Indistinguishable;
3646 }
3647
3648 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003649 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003650 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003651 }
3652
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003653 // Check that the winning standard conversion sequence isn't using
3654 // the deprecated string literal array to pointer conversion.
3655 switch (Result) {
3656 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003657 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003658 Result = ImplicitConversionSequence::Indistinguishable;
3659 break;
3660
3661 case ImplicitConversionSequence::Indistinguishable:
3662 break;
3663
3664 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003665 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003666 Result = ImplicitConversionSequence::Indistinguishable;
3667 break;
3668 }
3669
3670 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003671}
3672
Douglas Gregor5c407d92008-10-23 00:40:37 +00003673/// CompareDerivedToBaseConversions - Compares two standard conversion
3674/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003675/// various kinds of derived-to-base conversions (C++
3676/// [over.ics.rank]p4b3). As part of these checks, we also look at
3677/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003678ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003679CompareDerivedToBaseConversions(Sema &S,
3680 const StandardConversionSequence& SCS1,
3681 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003682 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003683 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003684 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003685 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003686
3687 // Adjust the types we're converting from via the array-to-pointer
3688 // conversion, if we need to.
3689 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003690 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003691 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003692 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003693
3694 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003695 FromType1 = S.Context.getCanonicalType(FromType1);
3696 ToType1 = S.Context.getCanonicalType(ToType1);
3697 FromType2 = S.Context.getCanonicalType(FromType2);
3698 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003699
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003700 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003701 //
3702 // If class B is derived directly or indirectly from class A and
3703 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003704 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003705 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003706 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003707 SCS2.Second == ICK_Pointer_Conversion &&
3708 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3709 FromType1->isPointerType() && FromType2->isPointerType() &&
3710 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003711 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003712 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003713 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003714 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003715 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003716 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003717 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003718 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003719
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003720 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003721 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003722 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003723 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003724 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003725 return ImplicitConversionSequence::Worse;
3726 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003727
3728 // -- conversion of B* to A* is better than conversion of C* to A*,
3729 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003730 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003731 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003732 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003733 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003734 }
3735 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3736 SCS2.Second == ICK_Pointer_Conversion) {
3737 const ObjCObjectPointerType *FromPtr1
3738 = FromType1->getAs<ObjCObjectPointerType>();
3739 const ObjCObjectPointerType *FromPtr2
3740 = FromType2->getAs<ObjCObjectPointerType>();
3741 const ObjCObjectPointerType *ToPtr1
3742 = ToType1->getAs<ObjCObjectPointerType>();
3743 const ObjCObjectPointerType *ToPtr2
3744 = ToType2->getAs<ObjCObjectPointerType>();
3745
3746 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3747 // Apply the same conversion ranking rules for Objective-C pointer types
3748 // that we do for C++ pointers to class types. However, we employ the
3749 // Objective-C pseudo-subtyping relationship used for assignment of
3750 // Objective-C pointer types.
3751 bool FromAssignLeft
3752 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3753 bool FromAssignRight
3754 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3755 bool ToAssignLeft
3756 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3757 bool ToAssignRight
3758 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3759
3760 // A conversion to an a non-id object pointer type or qualified 'id'
3761 // type is better than a conversion to 'id'.
3762 if (ToPtr1->isObjCIdType() &&
3763 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3764 return ImplicitConversionSequence::Worse;
3765 if (ToPtr2->isObjCIdType() &&
3766 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3767 return ImplicitConversionSequence::Better;
3768
3769 // A conversion to a non-id object pointer type is better than a
3770 // conversion to a qualified 'id' type
3771 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3772 return ImplicitConversionSequence::Worse;
3773 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3774 return ImplicitConversionSequence::Better;
3775
3776 // A conversion to an a non-Class object pointer type or qualified 'Class'
3777 // type is better than a conversion to 'Class'.
3778 if (ToPtr1->isObjCClassType() &&
3779 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3780 return ImplicitConversionSequence::Worse;
3781 if (ToPtr2->isObjCClassType() &&
3782 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3783 return ImplicitConversionSequence::Better;
3784
3785 // A conversion to a non-Class object pointer type is better than a
3786 // conversion to a qualified 'Class' type.
3787 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3788 return ImplicitConversionSequence::Worse;
3789 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3790 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003791
Douglas Gregor058d3de2011-01-31 18:51:41 +00003792 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3793 if (S.Context.hasSameType(FromType1, FromType2) &&
3794 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3795 (ToAssignLeft != ToAssignRight))
3796 return ToAssignLeft? ImplicitConversionSequence::Worse
3797 : ImplicitConversionSequence::Better;
3798
3799 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3800 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3801 (FromAssignLeft != FromAssignRight))
3802 return FromAssignLeft? ImplicitConversionSequence::Better
3803 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003804 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003805 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003806
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003807 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003808 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3809 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3810 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003811 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003812 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003813 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003814 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003815 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003816 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003817 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003818 ToType2->getAs<MemberPointerType>();
3819 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3820 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3821 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3822 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3823 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3824 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3825 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3826 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003827 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003828 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003829 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003830 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003831 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003832 return ImplicitConversionSequence::Better;
3833 }
3834 // conversion of B::* to C::* is better than conversion of A::* to C::*
3835 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003836 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003837 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003838 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003839 return ImplicitConversionSequence::Worse;
3840 }
3841 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003842
Douglas Gregor5ab11652010-04-17 22:01:05 +00003843 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003844 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003845 // -- binding of an expression of type C to a reference of type
3846 // B& is better than binding an expression of type C to a
3847 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003848 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3849 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3850 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003851 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003852 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003853 return ImplicitConversionSequence::Worse;
3854 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003855
Douglas Gregor2fe98832008-11-03 19:09:14 +00003856 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003857 // -- binding of an expression of type B to a reference of type
3858 // A& is better than binding an expression of type C to a
3859 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003860 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3861 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3862 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003863 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003864 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003865 return ImplicitConversionSequence::Worse;
3866 }
3867 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003868
Douglas Gregor5c407d92008-10-23 00:40:37 +00003869 return ImplicitConversionSequence::Indistinguishable;
3870}
3871
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003872/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3873/// determine whether they are reference-related,
3874/// reference-compatible, reference-compatible with added
3875/// qualification, or incompatible, for use in C++ initialization by
3876/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3877/// type, and the first type (T1) is the pointee type of the reference
3878/// type being initialized.
3879Sema::ReferenceCompareResult
3880Sema::CompareReferenceRelationship(SourceLocation Loc,
3881 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003882 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003883 bool &ObjCConversion,
3884 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003885 assert(!OrigT1->isReferenceType() &&
3886 "T1 must be the pointee type of the reference type");
3887 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3888
3889 QualType T1 = Context.getCanonicalType(OrigT1);
3890 QualType T2 = Context.getCanonicalType(OrigT2);
3891 Qualifiers T1Quals, T2Quals;
3892 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3893 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3894
3895 // C++ [dcl.init.ref]p4:
3896 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3897 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3898 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003899 DerivedToBase = false;
3900 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003901 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003902 if (UnqualT1 == UnqualT2) {
3903 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003904 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003905 IsDerivedFrom(UnqualT2, UnqualT1))
3906 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003907 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3908 UnqualT2->isObjCObjectOrInterfaceType() &&
3909 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3910 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003911 else
3912 return Ref_Incompatible;
3913
3914 // At this point, we know that T1 and T2 are reference-related (at
3915 // least).
3916
3917 // If the type is an array type, promote the element qualifiers to the type
3918 // for comparison.
3919 if (isa<ArrayType>(T1) && T1Quals)
3920 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3921 if (isa<ArrayType>(T2) && T2Quals)
3922 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3923
3924 // C++ [dcl.init.ref]p4:
3925 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3926 // reference-related to T2 and cv1 is the same cv-qualification
3927 // as, or greater cv-qualification than, cv2. For purposes of
3928 // overload resolution, cases for which cv1 is greater
3929 // cv-qualification than cv2 are identified as
3930 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003931 //
3932 // Note that we also require equivalence of Objective-C GC and address-space
3933 // qualifiers when performing these computations, so that e.g., an int in
3934 // address space 1 is not reference-compatible with an int in address
3935 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003936 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3937 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3938 T1Quals.removeObjCLifetime();
3939 T2Quals.removeObjCLifetime();
3940 ObjCLifetimeConversion = true;
3941 }
3942
Douglas Gregord517d552011-04-28 17:56:11 +00003943 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003944 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003945 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003946 return Ref_Compatible_With_Added_Qualification;
3947 else
3948 return Ref_Related;
3949}
3950
Douglas Gregor836a7e82010-08-11 02:15:33 +00003951/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003952/// with DeclType. Return true if something definite is found.
3953static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003954FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3955 QualType DeclType, SourceLocation DeclLoc,
3956 Expr *Init, QualType T2, bool AllowRvalues,
3957 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003958 assert(T2->isRecordType() && "Can only find conversions of record types.");
3959 CXXRecordDecl *T2RecordDecl
3960 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3961
3962 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003963 std::pair<CXXRecordDecl::conversion_iterator,
3964 CXXRecordDecl::conversion_iterator>
3965 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3966 for (CXXRecordDecl::conversion_iterator
3967 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003968 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
4048 ICS.setUserDefined();
4049 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4050 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004051 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004052 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004053 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004054 ICS.UserDefined.EllipsisConversion = false;
4055 assert(ICS.UserDefined.After.ReferenceBinding &&
4056 ICS.UserDefined.After.DirectBinding &&
4057 "Expected a direct reference binding!");
4058 return true;
4059
4060 case OR_Ambiguous:
4061 ICS.setAmbiguous();
4062 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4063 Cand != CandidateSet.end(); ++Cand)
4064 if (Cand->Viable)
4065 ICS.Ambiguous.addConversion(Cand->Function);
4066 return true;
4067
4068 case OR_No_Viable_Function:
4069 case OR_Deleted:
4070 // There was no suitable conversion, or we found a deleted
4071 // conversion; continue with other checks.
4072 return false;
4073 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004074
David Blaikie8a40f702012-01-17 06:56:22 +00004075 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004076}
4077
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004078/// \brief Compute an implicit conversion sequence for reference
4079/// initialization.
4080static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004081TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004082 SourceLocation DeclLoc,
4083 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004084 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004085 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4086
4087 // Most paths end in a failed conversion.
4088 ImplicitConversionSequence ICS;
4089 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4090
4091 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4092 QualType T2 = Init->getType();
4093
4094 // If the initializer is the address of an overloaded function, try
4095 // to resolve the overloaded function. If all goes well, T2 is the
4096 // type of the resulting function.
4097 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4098 DeclAccessPair Found;
4099 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4100 false, Found))
4101 T2 = Fn->getType();
4102 }
4103
4104 // Compute some basic properties of the types and the initializer.
4105 bool isRValRef = DeclType->isRValueReferenceType();
4106 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004107 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004108 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004109 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004110 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004111 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004112 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004113
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004114
Sebastian Redld92badf2010-06-30 18:13:39 +00004115 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004116 // A reference to type "cv1 T1" is initialized by an expression
4117 // of type "cv2 T2" as follows:
4118
Sebastian Redld92badf2010-06-30 18:13:39 +00004119 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004120 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004121 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4122 // reference-compatible with "cv2 T2," or
4123 //
4124 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4125 if (InitCategory.isLValue() &&
4126 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004127 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004128 // When a parameter of reference type binds directly (8.5.3)
4129 // to an argument expression, the implicit conversion sequence
4130 // is the identity conversion, unless the argument expression
4131 // has a type that is a derived class of the parameter type,
4132 // in which case the implicit conversion sequence is a
4133 // derived-to-base Conversion (13.3.3.1).
4134 ICS.setStandard();
4135 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004136 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4137 : ObjCConversion? ICK_Compatible_Conversion
4138 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004139 ICS.Standard.Third = ICK_Identity;
4140 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4141 ICS.Standard.setToType(0, T2);
4142 ICS.Standard.setToType(1, T1);
4143 ICS.Standard.setToType(2, T1);
4144 ICS.Standard.ReferenceBinding = true;
4145 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004146 ICS.Standard.IsLvalueReference = !isRValRef;
4147 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4148 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004149 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004150 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004151 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004152
Sebastian Redld92badf2010-06-30 18:13:39 +00004153 // Nothing more to do: the inaccessibility/ambiguity check for
4154 // derived-to-base conversions is suppressed when we're
4155 // computing the implicit conversion sequence (C++
4156 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004157 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004158 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004159
Sebastian Redld92badf2010-06-30 18:13:39 +00004160 // -- has a class type (i.e., T2 is a class type), where T1 is
4161 // not reference-related to T2, and can be implicitly
4162 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4163 // is reference-compatible with "cv3 T3" 92) (this
4164 // conversion is selected by enumerating the applicable
4165 // conversion functions (13.3.1.6) and choosing the best
4166 // one through overload resolution (13.3)),
4167 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004168 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004169 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004170 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4171 Init, T2, /*AllowRvalues=*/false,
4172 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004173 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004174 }
4175 }
4176
Sebastian Redld92badf2010-06-30 18:13:39 +00004177 // -- Otherwise, the reference shall be an lvalue reference to a
4178 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004179 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004180 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004181 // We actually handle one oddity of C++ [over.ics.ref] at this
4182 // point, which is that, due to p2 (which short-circuits reference
4183 // binding by only attempting a simple conversion for non-direct
4184 // bindings) and p3's strange wording, we allow a const volatile
4185 // reference to bind to an rvalue. Hence the check for the presence
4186 // of "const" rather than checking for "const" being the only
4187 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004188 // This is also the point where rvalue references and lvalue inits no longer
4189 // go together.
Richard Smithce4f6082012-05-24 04:29:20 +00004190 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004191 return ICS;
4192
Douglas Gregorf143cd52011-01-24 16:14:37 +00004193 // -- If the initializer expression
4194 //
4195 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004196 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004197 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4198 (InitCategory.isXValue() ||
4199 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4200 (InitCategory.isLValue() && T2->isFunctionType()))) {
4201 ICS.setStandard();
4202 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004203 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004204 : ObjCConversion? ICK_Compatible_Conversion
4205 : ICK_Identity;
4206 ICS.Standard.Third = ICK_Identity;
4207 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4208 ICS.Standard.setToType(0, T2);
4209 ICS.Standard.setToType(1, T1);
4210 ICS.Standard.setToType(2, T1);
4211 ICS.Standard.ReferenceBinding = true;
4212 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4213 // binding unless we're binding to a class prvalue.
4214 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4215 // allow the use of rvalue references in C++98/03 for the benefit of
4216 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004217 ICS.Standard.DirectBinding =
David Blaikiebbafb8a2012-03-11 07:00:24 +00004218 S.getLangOpts().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004219 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004220 ICS.Standard.IsLvalueReference = !isRValRef;
4221 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004222 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004223 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004224 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004225 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004226 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004227 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004228
Douglas Gregorf143cd52011-01-24 16:14:37 +00004229 // -- has a class type (i.e., T2 is a class type), where T1 is not
4230 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004231 // an xvalue, class prvalue, or function lvalue of type
4232 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004233 // "cv3 T3",
4234 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004235 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004236 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004237 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004238 // class subobject).
4239 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004240 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004241 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4242 Init, T2, /*AllowRvalues=*/true,
4243 AllowExplicit)) {
4244 // In the second case, if the reference is an rvalue reference
4245 // and the second standard conversion sequence of the
4246 // user-defined conversion sequence includes an lvalue-to-rvalue
4247 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004248 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004249 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4250 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4251
Douglas Gregor95273c32011-01-21 16:36:05 +00004252 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004253 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004254
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004255 // -- Otherwise, a temporary of type "cv1 T1" is created and
4256 // initialized from the initializer expression using the
4257 // rules for a non-reference copy initialization (8.5). The
4258 // reference is then bound to the temporary. If T1 is
4259 // reference-related to T2, cv1 must be the same
4260 // cv-qualification as, or greater cv-qualification than,
4261 // cv2; otherwise, the program is ill-formed.
4262 if (RefRelationship == Sema::Ref_Related) {
4263 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4264 // we would be reference-compatible or reference-compatible with
4265 // added qualification. But that wasn't the case, so the reference
4266 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004267 //
4268 // Note that we only want to check address spaces and cvr-qualifiers here.
4269 // ObjC GC and lifetime qualifiers aren't important.
4270 Qualifiers T1Quals = T1.getQualifiers();
4271 Qualifiers T2Quals = T2.getQualifiers();
4272 T1Quals.removeObjCGCAttr();
4273 T1Quals.removeObjCLifetime();
4274 T2Quals.removeObjCGCAttr();
4275 T2Quals.removeObjCLifetime();
4276 if (!T1Quals.compatiblyIncludes(T2Quals))
4277 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004278 }
4279
4280 // If at least one of the types is a class type, the types are not
4281 // related, and we aren't allowed any user conversions, the
4282 // reference binding fails. This case is important for breaking
4283 // recursion, since TryImplicitConversion below will attempt to
4284 // create a temporary through the use of a copy constructor.
4285 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4286 (T1->isRecordType() || T2->isRecordType()))
4287 return ICS;
4288
Douglas Gregorcba72b12011-01-21 05:18:22 +00004289 // If T1 is reference-related to T2 and the reference is an rvalue
4290 // reference, the initializer expression shall not be an lvalue.
4291 if (RefRelationship >= Sema::Ref_Related &&
4292 isRValRef && Init->Classify(S.Context).isLValue())
4293 return ICS;
4294
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004295 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004296 // When a parameter of reference type is not bound directly to
4297 // an argument expression, the conversion sequence is the one
4298 // required to convert the argument expression to the
4299 // underlying type of the reference according to
4300 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4301 // to copy-initializing a temporary of the underlying type with
4302 // the argument expression. Any difference in top-level
4303 // cv-qualification is subsumed by the initialization itself
4304 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004305 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4306 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004307 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004308 /*CStyle=*/false,
4309 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004310
4311 // Of course, that's still a reference binding.
4312 if (ICS.isStandard()) {
4313 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004314 ICS.Standard.IsLvalueReference = !isRValRef;
4315 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4316 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004317 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004318 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004319 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004320 // Don't allow rvalue references to bind to lvalues.
4321 if (DeclType->isRValueReferenceType()) {
4322 if (const ReferenceType *RefType
4323 = ICS.UserDefined.ConversionFunction->getResultType()
4324 ->getAs<LValueReferenceType>()) {
4325 if (!RefType->getPointeeType()->isFunctionType()) {
4326 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4327 DeclType);
4328 return ICS;
4329 }
4330 }
4331 }
4332
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004333 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004334 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4335 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4336 ICS.UserDefined.After.BindsToRvalue = true;
4337 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4338 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004339 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004340
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004341 return ICS;
4342}
4343
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004344static ImplicitConversionSequence
4345TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4346 bool SuppressUserConversions,
4347 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004348 bool AllowObjCWritebackConversion,
4349 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004350
4351/// TryListConversion - Try to copy-initialize a value of type ToType from the
4352/// initializer list From.
4353static ImplicitConversionSequence
4354TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4355 bool SuppressUserConversions,
4356 bool InOverloadResolution,
4357 bool AllowObjCWritebackConversion) {
4358 // C++11 [over.ics.list]p1:
4359 // When an argument is an initializer list, it is not an expression and
4360 // special rules apply for converting it to a parameter type.
4361
4362 ImplicitConversionSequence Result;
4363 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004364 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004365
Sebastian Redl09edce02012-01-23 22:09:39 +00004366 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004367 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004368 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004369 return Result;
4370
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004371 // C++11 [over.ics.list]p2:
4372 // If the parameter type is std::initializer_list<X> or "array of X" and
4373 // all the elements can be implicitly converted to X, the implicit
4374 // conversion sequence is the worst conversion necessary to convert an
4375 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004376 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004377 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004378 if (ToType->isArrayType())
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004379 X = S.Context.getBaseElementType(ToType);
4380 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004381 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004382 if (!X.isNull()) {
4383 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4384 Expr *Init = From->getInit(i);
4385 ImplicitConversionSequence ICS =
4386 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4387 InOverloadResolution,
4388 AllowObjCWritebackConversion);
4389 // If a single element isn't convertible, fail.
4390 if (ICS.isBad()) {
4391 Result = ICS;
4392 break;
4393 }
4394 // Otherwise, look for the worst conversion.
4395 if (Result.isBad() ||
4396 CompareImplicitConversionSequences(S, ICS, Result) ==
4397 ImplicitConversionSequence::Worse)
4398 Result = ICS;
4399 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004400
4401 // For an empty list, we won't have computed any conversion sequence.
4402 // Introduce the identity conversion sequence.
4403 if (From->getNumInits() == 0) {
4404 Result.setStandard();
4405 Result.Standard.setAsIdentityConversion();
4406 Result.Standard.setFromType(ToType);
4407 Result.Standard.setAllToTypes(ToType);
4408 }
4409
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004410 Result.setListInitializationSequence();
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004411 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004412 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004413 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004414
4415 // C++11 [over.ics.list]p3:
4416 // Otherwise, if the parameter is a non-aggregate class X and overload
4417 // resolution chooses a single best constructor [...] the implicit
4418 // conversion sequence is a user-defined conversion sequence. If multiple
4419 // constructors are viable but none is better than the others, the
4420 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004421 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4422 // This function can deal with initializer lists.
4423 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4424 /*AllowExplicit=*/false,
4425 InOverloadResolution, /*CStyle=*/false,
4426 AllowObjCWritebackConversion);
4427 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004428 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004429 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004430
4431 // C++11 [over.ics.list]p4:
4432 // Otherwise, if the parameter has an aggregate type which can be
4433 // initialized from the initializer list [...] the implicit conversion
4434 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004435 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004436 // Type is an aggregate, argument is an init list. At this point it comes
4437 // down to checking whether the initialization works.
4438 // FIXME: Find out whether this parameter is consumed or not.
4439 InitializedEntity Entity =
4440 InitializedEntity::InitializeParameter(S.Context, ToType,
4441 /*Consumed=*/false);
4442 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4443 Result.setUserDefined();
4444 Result.UserDefined.Before.setAsIdentityConversion();
4445 // Initializer lists don't have a type.
4446 Result.UserDefined.Before.setFromType(QualType());
4447 Result.UserDefined.Before.setAllToTypes(QualType());
4448
4449 Result.UserDefined.After.setAsIdentityConversion();
4450 Result.UserDefined.After.setFromType(ToType);
4451 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004452 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004453 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004454 return Result;
4455 }
4456
4457 // C++11 [over.ics.list]p5:
4458 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004459 if (ToType->isReferenceType()) {
4460 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4461 // mention initializer lists in any way. So we go by what list-
4462 // initialization would do and try to extrapolate from that.
4463
4464 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4465
4466 // If the initializer list has a single element that is reference-related
4467 // to the parameter type, we initialize the reference from that.
4468 if (From->getNumInits() == 1) {
4469 Expr *Init = From->getInit(0);
4470
4471 QualType T2 = Init->getType();
4472
4473 // If the initializer is the address of an overloaded function, try
4474 // to resolve the overloaded function. If all goes well, T2 is the
4475 // type of the resulting function.
4476 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4477 DeclAccessPair Found;
4478 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4479 Init, ToType, false, Found))
4480 T2 = Fn->getType();
4481 }
4482
4483 // Compute some basic properties of the types and the initializer.
4484 bool dummy1 = false;
4485 bool dummy2 = false;
4486 bool dummy3 = false;
4487 Sema::ReferenceCompareResult RefRelationship
4488 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4489 dummy2, dummy3);
4490
4491 if (RefRelationship >= Sema::Ref_Related)
4492 return TryReferenceInit(S, Init, ToType,
4493 /*FIXME:*/From->getLocStart(),
4494 SuppressUserConversions,
4495 /*AllowExplicit=*/false);
4496 }
4497
4498 // Otherwise, we bind the reference to a temporary created from the
4499 // initializer list.
4500 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4501 InOverloadResolution,
4502 AllowObjCWritebackConversion);
4503 if (Result.isFailure())
4504 return Result;
4505 assert(!Result.isEllipsis() &&
4506 "Sub-initialization cannot result in ellipsis conversion.");
4507
4508 // Can we even bind to a temporary?
4509 if (ToType->isRValueReferenceType() ||
4510 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4511 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4512 Result.UserDefined.After;
4513 SCS.ReferenceBinding = true;
4514 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4515 SCS.BindsToRvalue = true;
4516 SCS.BindsToFunctionLvalue = false;
4517 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4518 SCS.ObjCLifetimeConversionBinding = false;
4519 } else
4520 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4521 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004522 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004523 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004524
4525 // C++11 [over.ics.list]p6:
4526 // Otherwise, if the parameter type is not a class:
4527 if (!ToType->isRecordType()) {
4528 // - if the initializer list has one element, the implicit conversion
4529 // sequence is the one required to convert the element to the
4530 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004531 unsigned NumInits = From->getNumInits();
4532 if (NumInits == 1)
4533 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4534 SuppressUserConversions,
4535 InOverloadResolution,
4536 AllowObjCWritebackConversion);
4537 // - if the initializer list has no elements, the implicit conversion
4538 // sequence is the identity conversion.
4539 else if (NumInits == 0) {
4540 Result.setStandard();
4541 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004542 Result.Standard.setFromType(ToType);
4543 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004544 }
Sebastian Redl12edeb02012-02-28 23:36:38 +00004545 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004546 return Result;
4547 }
4548
4549 // C++11 [over.ics.list]p7:
4550 // In all cases other than those enumerated above, no conversion is possible
4551 return Result;
4552}
4553
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004554/// TryCopyInitialization - Try to copy-initialize a value of type
4555/// ToType from the expression From. Return the implicit conversion
4556/// sequence required to pass this argument, which may be a bad
4557/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004558/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004559/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004560static ImplicitConversionSequence
4561TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004562 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004563 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004564 bool AllowObjCWritebackConversion,
4565 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004566 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4567 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4568 InOverloadResolution,AllowObjCWritebackConversion);
4569
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004570 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004571 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004572 /*FIXME:*/From->getLocStart(),
4573 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004574 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004575
John McCall5c32be02010-08-24 20:38:10 +00004576 return TryImplicitConversion(S, From, ToType,
4577 SuppressUserConversions,
4578 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004579 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004580 /*CStyle=*/false,
4581 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004582}
4583
Anna Zaks1b068122011-07-28 19:46:48 +00004584static bool TryCopyInitialization(const CanQualType FromQTy,
4585 const CanQualType ToQTy,
4586 Sema &S,
4587 SourceLocation Loc,
4588 ExprValueKind FromVK) {
4589 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4590 ImplicitConversionSequence ICS =
4591 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4592
4593 return !ICS.isBad();
4594}
4595
Douglas Gregor436424c2008-11-18 23:14:02 +00004596/// TryObjectArgumentInitialization - Try to initialize the object
4597/// parameter of the given member function (@c Method) from the
4598/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004599static ImplicitConversionSequence
4600TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004601 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004602 CXXMethodDecl *Method,
4603 CXXRecordDecl *ActingContext) {
4604 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004605 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4606 // const volatile object.
4607 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4608 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004609 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004610
4611 // Set up the conversion sequence as a "bad" conversion, to allow us
4612 // to exit early.
4613 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004614
4615 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004616 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004617 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004618 FromType = PT->getPointeeType();
4619
Douglas Gregor02824322011-01-26 19:30:28 +00004620 // When we had a pointer, it's implicitly dereferenced, so we
4621 // better have an lvalue.
4622 assert(FromClassification.isLValue());
4623 }
4624
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004625 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004626
Douglas Gregor02824322011-01-26 19:30:28 +00004627 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004628 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004629 // parameter is
4630 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004631 // - "lvalue reference to cv X" for functions declared without a
4632 // ref-qualifier or with the & ref-qualifier
4633 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004634 // ref-qualifier
4635 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004636 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004637 // cv-qualification on the member function declaration.
4638 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004639 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004640 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004641 // (C++ [over.match.funcs]p5). We perform a simplified version of
4642 // reference binding here, that allows class rvalues to bind to
4643 // non-constant references.
4644
Douglas Gregor02824322011-01-26 19:30:28 +00004645 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004646 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004647 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004648 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004649 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004650 ICS.setBad(BadConversionSequence::bad_qualifiers,
4651 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004652 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004653 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004654
4655 // Check that we have either the same type or a derived type. It
4656 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004657 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004658 ImplicitConversionKind SecondKind;
4659 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4660 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004661 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004662 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004663 else {
John McCall65eb8792010-02-25 01:37:24 +00004664 ICS.setBad(BadConversionSequence::unrelated_class,
4665 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004666 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004667 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004668
Douglas Gregor02824322011-01-26 19:30:28 +00004669 // Check the ref-qualifier.
4670 switch (Method->getRefQualifier()) {
4671 case RQ_None:
4672 // Do nothing; we don't care about lvalueness or rvalueness.
4673 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004674
Douglas Gregor02824322011-01-26 19:30:28 +00004675 case RQ_LValue:
4676 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4677 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004678 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004679 ImplicitParamType);
4680 return ICS;
4681 }
4682 break;
4683
4684 case RQ_RValue:
4685 if (!FromClassification.isRValue()) {
4686 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004687 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004688 ImplicitParamType);
4689 return ICS;
4690 }
4691 break;
4692 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004693
Douglas Gregor436424c2008-11-18 23:14:02 +00004694 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004695 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004696 ICS.Standard.setAsIdentityConversion();
4697 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004698 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004699 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004700 ICS.Standard.ReferenceBinding = true;
4701 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004702 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004703 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004704 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4705 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4706 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004707 return ICS;
4708}
4709
4710/// PerformObjectArgumentInitialization - Perform initialization of
4711/// the implicit object parameter for the given Method with the given
4712/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004713ExprResult
4714Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004715 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004716 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004717 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004718 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004719 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004720 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004721
Douglas Gregor02824322011-01-26 19:30:28 +00004722 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004723 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004724 FromRecordType = PT->getPointeeType();
4725 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004726 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004727 } else {
4728 FromRecordType = From->getType();
4729 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004730 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004731 }
4732
John McCall6e9f8f62009-12-03 04:06:58 +00004733 // Note that we always use the true parent context when performing
4734 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004735 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004736 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4737 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004738 if (ICS.isBad()) {
4739 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4740 Qualifiers FromQs = FromRecordType.getQualifiers();
4741 Qualifiers ToQs = DestType.getQualifiers();
4742 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4743 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004744 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004745 diag::err_member_function_call_bad_cvr)
4746 << Method->getDeclName() << FromRecordType << (CVR - 1)
4747 << From->getSourceRange();
4748 Diag(Method->getLocation(), diag::note_previous_decl)
4749 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004750 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004751 }
4752 }
4753
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004754 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004755 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004756 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004757 }
Mike Stump11289f42009-09-09 15:08:12 +00004758
John Wiegley01296292011-04-08 18:41:53 +00004759 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4760 ExprResult FromRes =
4761 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4762 if (FromRes.isInvalid())
4763 return ExprError();
4764 From = FromRes.take();
4765 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004766
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004767 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004768 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004769 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004770 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004771}
4772
Douglas Gregor5fb53972009-01-14 15:45:31 +00004773/// TryContextuallyConvertToBool - Attempt to contextually convert the
4774/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004775static ImplicitConversionSequence
4776TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004777 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004778 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004779 // FIXME: Are these flags correct?
4780 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004781 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004782 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004783 /*CStyle=*/false,
4784 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004785}
4786
4787/// PerformContextuallyConvertToBool - Perform a contextual conversion
4788/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004789ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004790 if (checkPlaceholderForOverload(*this, From))
4791 return ExprError();
4792
John McCall5c32be02010-08-24 20:38:10 +00004793 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004794 if (!ICS.isBad())
4795 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004796
Fariborz Jahanian76197412009-11-18 18:26:29 +00004797 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004798 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004799 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004800 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004801 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004802}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004803
Richard Smithf8379a02012-01-18 23:55:52 +00004804/// Check that the specified conversion is permitted in a converted constant
4805/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4806/// is acceptable.
4807static bool CheckConvertedConstantConversions(Sema &S,
4808 StandardConversionSequence &SCS) {
4809 // Since we know that the target type is an integral or unscoped enumeration
4810 // type, most conversion kinds are impossible. All possible First and Third
4811 // conversions are fine.
4812 switch (SCS.Second) {
4813 case ICK_Identity:
4814 case ICK_Integral_Promotion:
4815 case ICK_Integral_Conversion:
4816 return true;
4817
4818 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004819 // Conversion from an integral or unscoped enumeration type to bool is
4820 // classified as ICK_Boolean_Conversion, but it's also an integral
4821 // conversion, so it's permitted in a converted constant expression.
4822 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4823 SCS.getToType(2)->isBooleanType();
4824
Richard Smithf8379a02012-01-18 23:55:52 +00004825 case ICK_Floating_Integral:
4826 case ICK_Complex_Real:
4827 return false;
4828
4829 case ICK_Lvalue_To_Rvalue:
4830 case ICK_Array_To_Pointer:
4831 case ICK_Function_To_Pointer:
4832 case ICK_NoReturn_Adjustment:
4833 case ICK_Qualification:
4834 case ICK_Compatible_Conversion:
4835 case ICK_Vector_Conversion:
4836 case ICK_Vector_Splat:
4837 case ICK_Derived_To_Base:
4838 case ICK_Pointer_Conversion:
4839 case ICK_Pointer_Member:
4840 case ICK_Block_Pointer_Conversion:
4841 case ICK_Writeback_Conversion:
4842 case ICK_Floating_Promotion:
4843 case ICK_Complex_Promotion:
4844 case ICK_Complex_Conversion:
4845 case ICK_Floating_Conversion:
4846 case ICK_TransparentUnionConversion:
4847 llvm_unreachable("unexpected second conversion kind");
4848
4849 case ICK_Num_Conversion_Kinds:
4850 break;
4851 }
4852
4853 llvm_unreachable("unknown conversion kind");
4854}
4855
4856/// CheckConvertedConstantExpression - Check that the expression From is a
4857/// converted constant expression of type T, perform the conversion and produce
4858/// the converted expression, per C++11 [expr.const]p3.
4859ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4860 llvm::APSInt &Value,
4861 CCEKind CCE) {
4862 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4863 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4864
4865 if (checkPlaceholderForOverload(*this, From))
4866 return ExprError();
4867
4868 // C++11 [expr.const]p3 with proposed wording fixes:
4869 // A converted constant expression of type T is a core constant expression,
4870 // implicitly converted to a prvalue of type T, where the converted
4871 // expression is a literal constant expression and the implicit conversion
4872 // sequence contains only user-defined conversions, lvalue-to-rvalue
4873 // conversions, integral promotions, and integral conversions other than
4874 // narrowing conversions.
4875 ImplicitConversionSequence ICS =
4876 TryImplicitConversion(From, T,
4877 /*SuppressUserConversions=*/false,
4878 /*AllowExplicit=*/false,
4879 /*InOverloadResolution=*/false,
4880 /*CStyle=*/false,
4881 /*AllowObjcWritebackConversion=*/false);
4882 StandardConversionSequence *SCS = 0;
4883 switch (ICS.getKind()) {
4884 case ImplicitConversionSequence::StandardConversion:
4885 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004886 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004887 diag::err_typecheck_converted_constant_expression_disallowed)
4888 << From->getType() << From->getSourceRange() << T;
4889 SCS = &ICS.Standard;
4890 break;
4891 case ImplicitConversionSequence::UserDefinedConversion:
4892 // We are converting from class type to an integral or enumeration type, so
4893 // the Before sequence must be trivial.
4894 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004895 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004896 diag::err_typecheck_converted_constant_expression_disallowed)
4897 << From->getType() << From->getSourceRange() << T;
4898 SCS = &ICS.UserDefined.After;
4899 break;
4900 case ImplicitConversionSequence::AmbiguousConversion:
4901 case ImplicitConversionSequence::BadConversion:
4902 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004903 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004904 diag::err_typecheck_converted_constant_expression)
4905 << From->getType() << From->getSourceRange() << T;
4906 return ExprError();
4907
4908 case ImplicitConversionSequence::EllipsisConversion:
4909 llvm_unreachable("ellipsis conversion in converted constant expression");
4910 }
4911
4912 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4913 if (Result.isInvalid())
4914 return Result;
4915
4916 // Check for a narrowing implicit conversion.
4917 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00004918 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00004919 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4920 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00004921 case NK_Variable_Narrowing:
4922 // Implicit conversion to a narrower type, and the value is not a constant
4923 // expression. We'll diagnose this in a moment.
4924 case NK_Not_Narrowing:
4925 break;
4926
4927 case NK_Constant_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004928 Diag(From->getLocStart(),
4929 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4930 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004931 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00004932 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00004933 break;
4934
4935 case NK_Type_Narrowing:
Eli Friedman2b22a6e2012-03-29 23:39:39 +00004936 Diag(From->getLocStart(),
4937 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4938 diag::err_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00004939 << CCE << /*Constant*/0 << From->getType() << T;
4940 break;
4941 }
4942
4943 // Check the expression is a constant expression.
4944 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4945 Expr::EvalResult Eval;
4946 Eval.Diag = &Notes;
4947
4948 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4949 // The expression can't be folded, so we can't keep it at this position in
4950 // the AST.
4951 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00004952 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00004953 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00004954
4955 if (Notes.empty()) {
4956 // It's a constant expression.
4957 return Result;
4958 }
Richard Smithf8379a02012-01-18 23:55:52 +00004959 }
4960
4961 // It's not a constant expression. Produce an appropriate diagnostic.
4962 if (Notes.size() == 1 &&
4963 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4964 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4965 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004966 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00004967 << CCE << From->getSourceRange();
4968 for (unsigned I = 0; I < Notes.size(); ++I)
4969 Diag(Notes[I].first, Notes[I].second);
4970 }
Richard Smith911e1422012-01-30 22:27:01 +00004971 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00004972}
4973
John McCallfec112d2011-09-09 06:11:02 +00004974/// dropPointerConversions - If the given standard conversion sequence
4975/// involves any pointer conversions, remove them. This may change
4976/// the result type of the conversion sequence.
4977static void dropPointerConversion(StandardConversionSequence &SCS) {
4978 if (SCS.Second == ICK_Pointer_Conversion) {
4979 SCS.Second = ICK_Identity;
4980 SCS.Third = ICK_Identity;
4981 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4982 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004983}
John McCall5c32be02010-08-24 20:38:10 +00004984
John McCallfec112d2011-09-09 06:11:02 +00004985/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4986/// convert the expression From to an Objective-C pointer type.
4987static ImplicitConversionSequence
4988TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4989 // Do an implicit conversion to 'id'.
4990 QualType Ty = S.Context.getObjCIdType();
4991 ImplicitConversionSequence ICS
4992 = TryImplicitConversion(S, From, Ty,
4993 // FIXME: Are these flags correct?
4994 /*SuppressUserConversions=*/false,
4995 /*AllowExplicit=*/true,
4996 /*InOverloadResolution=*/false,
4997 /*CStyle=*/false,
4998 /*AllowObjCWritebackConversion=*/false);
4999
5000 // Strip off any final conversions to 'id'.
5001 switch (ICS.getKind()) {
5002 case ImplicitConversionSequence::BadConversion:
5003 case ImplicitConversionSequence::AmbiguousConversion:
5004 case ImplicitConversionSequence::EllipsisConversion:
5005 break;
5006
5007 case ImplicitConversionSequence::UserDefinedConversion:
5008 dropPointerConversion(ICS.UserDefined.After);
5009 break;
5010
5011 case ImplicitConversionSequence::StandardConversion:
5012 dropPointerConversion(ICS.Standard);
5013 break;
5014 }
5015
5016 return ICS;
5017}
5018
5019/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5020/// conversion of the expression From to an Objective-C pointer type.
5021ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005022 if (checkPlaceholderForOverload(*this, From))
5023 return ExprError();
5024
John McCall8b07ec22010-05-15 11:32:37 +00005025 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005026 ImplicitConversionSequence ICS =
5027 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005028 if (!ICS.isBad())
5029 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005030 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005031}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005032
Richard Smith8dd34252012-02-04 07:07:42 +00005033/// Determine whether the provided type is an integral type, or an enumeration
5034/// type of a permitted flavor.
5035static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5036 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5037 : T->isIntegralOrUnscopedEnumerationType();
5038}
5039
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005040/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005041/// enumeration type.
5042///
5043/// This routine will attempt to convert an expression of class type to an
5044/// integral or enumeration type, if that class type only has a single
5045/// conversion to an integral or enumeration type.
5046///
Douglas Gregor4799d032010-06-30 00:20:43 +00005047/// \param Loc The source location of the construct that requires the
5048/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005049///
James Dennett18348b62012-06-22 08:52:37 +00005050/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005051///
James Dennett18348b62012-06-22 08:52:37 +00005052/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor4799d032010-06-30 00:20:43 +00005053///
Richard Smith8dd34252012-02-04 07:07:42 +00005054/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5055/// enumerations should be considered.
5056///
Douglas Gregor4799d032010-06-30 00:20:43 +00005057/// \returns The expression, converted to an integral or enumeration type if
5058/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005059ExprResult
John McCallb268a282010-08-23 23:25:46 +00005060Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregore2b37442012-05-04 22:38:52 +00005061 ICEConvertDiagnoser &Diagnoser,
Richard Smith8dd34252012-02-04 07:07:42 +00005062 bool AllowScopedEnumerations) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005063 // We can't perform any more checking for type-dependent expressions.
5064 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00005065 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005066
Eli Friedman1da70392012-01-26 00:26:18 +00005067 // Process placeholders immediately.
5068 if (From->hasPlaceholderType()) {
5069 ExprResult result = CheckPlaceholderExpr(From);
5070 if (result.isInvalid()) return result;
5071 From = result.take();
5072 }
5073
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005074 // If the expression already has integral or enumeration type, we're golden.
5075 QualType T = From->getType();
Richard Smith8dd34252012-02-04 07:07:42 +00005076 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedman1da70392012-01-26 00:26:18 +00005077 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005078
5079 // FIXME: Check for missing '()' if T is a function type?
5080
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005081 // 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 +00005082 // expression of integral or enumeration type.
5083 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005084 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005085 if (!Diagnoser.Suppress)
5086 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00005087 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005089
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005090 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005091 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregore2b37442012-05-04 22:38:52 +00005092 ICEConvertDiagnoser &Diagnoser;
5093 Expr *From;
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005094
Douglas Gregore2b37442012-05-04 22:38:52 +00005095 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5096 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005097
5098 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005099 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005100 }
Douglas Gregore2b37442012-05-04 22:38:52 +00005101 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005102
5103 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCallb268a282010-08-23 23:25:46 +00005104 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005105
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005106 // Look for a conversion to an integral or enumeration type.
5107 UnresolvedSet<4> ViableConversions;
5108 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005109 std::pair<CXXRecordDecl::conversion_iterator,
5110 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005111 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005112
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005113 bool HadMultipleCandidates
5114 = (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005115
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005116 for (CXXRecordDecl::conversion_iterator
5117 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005118 if (CXXConversionDecl *Conversion
Richard Smith8dd34252012-02-04 07:07:42 +00005119 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5120 if (isIntegralOrEnumerationType(
5121 Conversion->getConversionType().getNonReferenceType(),
5122 AllowScopedEnumerations)) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005123 if (Conversion->isExplicit())
5124 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5125 else
5126 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5127 }
Richard Smith8dd34252012-02-04 07:07:42 +00005128 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005129 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005130
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005131 switch (ViableConversions.size()) {
5132 case 0:
Douglas Gregore2b37442012-05-04 22:38:52 +00005133 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005134 DeclAccessPair Found = ExplicitConversions[0];
5135 CXXConversionDecl *Conversion
5136 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005137
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005138 // The user probably meant to invoke the given explicit
5139 // conversion; use it.
5140 QualType ConvTy
5141 = Conversion->getConversionType().getNonReferenceType();
5142 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00005143 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005144
Douglas Gregore2b37442012-05-04 22:38:52 +00005145 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005146 << FixItHint::CreateInsertion(From->getLocStart(),
5147 "static_cast<" + TypeStr + ">(")
5148 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5149 ")");
Douglas Gregore2b37442012-05-04 22:38:52 +00005150 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005151
5152 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005153 // explicit conversion function.
5154 if (isSFINAEContext())
5155 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005156
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005157 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005158 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5159 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005160 if (Result.isInvalid())
5161 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005162 // Record usage of conversion in an implicit cast.
5163 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5164 CK_UserDefinedConversion,
5165 Result.get(), 0,
5166 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005167 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005168
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005169 // We'll complain below about a non-integral condition type.
5170 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005171
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005172 case 1: {
5173 // Apply this conversion.
5174 DeclAccessPair Found = ViableConversions[0];
5175 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005176
Douglas Gregor4799d032010-06-30 00:20:43 +00005177 CXXConversionDecl *Conversion
5178 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5179 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005180 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregore2b37442012-05-04 22:38:52 +00005181 if (!Diagnoser.SuppressConversion) {
Douglas Gregor4799d032010-06-30 00:20:43 +00005182 if (isSFINAEContext())
5183 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005184
Douglas Gregore2b37442012-05-04 22:38:52 +00005185 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5186 << From->getSourceRange();
Douglas Gregor4799d032010-06-30 00:20:43 +00005187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005188
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005189 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5190 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00005191 if (Result.isInvalid())
5192 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005193 // Record usage of conversion in an implicit cast.
5194 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5195 CK_UserDefinedConversion,
5196 Result.get(), 0,
5197 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005198 break;
5199 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005200
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005201 default:
Douglas Gregore2b37442012-05-04 22:38:52 +00005202 if (Diagnoser.Suppress)
5203 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005204
Douglas Gregore2b37442012-05-04 22:38:52 +00005205 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005206 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5207 CXXConversionDecl *Conv
5208 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5209 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregore2b37442012-05-04 22:38:52 +00005210 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005211 }
John McCallb268a282010-08-23 23:25:46 +00005212 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005213 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005214
Richard Smithf4c51d92012-02-04 09:53:13 +00005215 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregore2b37442012-05-04 22:38:52 +00005216 !Diagnoser.Suppress) {
5217 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5218 << From->getSourceRange();
5219 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005220
Eli Friedman1da70392012-01-26 00:26:18 +00005221 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005222}
5223
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005224/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005225/// candidate functions, using the given function call arguments. If
5226/// @p SuppressUserConversions, then don't allow user-defined
5227/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005228///
James Dennett2a4d13c2012-06-15 07:13:21 +00005229/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005230/// based on an incomplete set of function arguments. This feature is used by
5231/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005232void
5233Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005234 DeclAccessPair FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005235 llvm::ArrayRef<Expr *> Args,
Douglas Gregor2fe98832008-11-03 19:09:14 +00005236 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005237 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005238 bool PartialOverloading,
5239 bool AllowExplicit) {
Mike Stump11289f42009-09-09 15:08:12 +00005240 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005241 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005242 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005243 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005244 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005245
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005246 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005247 if (!isa<CXXConstructorDecl>(Method)) {
5248 // If we get here, it's because we're calling a member function
5249 // that is named without a member access expression (e.g.,
5250 // "this->f") that was either written explicitly or created
5251 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005252 // function, e.g., X::f(). We use an empty type for the implied
5253 // object argument (C++ [over.call.func]p3), and the acting context
5254 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005255 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005256 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005257 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005258 return;
5259 }
5260 // We treat a constructor like a non-member function, since its object
5261 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005262 }
5263
Douglas Gregorff7028a2009-11-13 23:59:09 +00005264 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005265 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005266
Douglas Gregor27381f32009-11-23 12:27:39 +00005267 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005268 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005269
Douglas Gregorffe14e32009-11-14 01:20:54 +00005270 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5271 // C++ [class.copy]p3:
5272 // A member function template is never instantiated to perform the copy
5273 // of a class object to an object of its class type.
5274 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005275 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005276 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005277 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5278 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005279 return;
5280 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005281
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005282 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005283 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005284 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005285 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005286 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005287 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005288 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005289 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005290
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005291 unsigned NumArgsInProto = Proto->getNumArgs();
5292
5293 // (C++ 13.3.2p2): A candidate function having fewer than m
5294 // parameters is viable only if it has an ellipsis in its parameter
5295 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005296 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005297 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005298 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005299 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005300 return;
5301 }
5302
5303 // (C++ 13.3.2p2): A candidate function having more than m parameters
5304 // is viable only if the (m+1)st parameter has a default argument
5305 // (8.3.6). For the purposes of overload resolution, the
5306 // parameter list is truncated on the right, so that there are
5307 // exactly m parameters.
5308 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005309 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005310 // Not enough arguments.
5311 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005312 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005313 return;
5314 }
5315
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005316 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005317 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005318 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5319 if (CheckCUDATarget(Caller, Function)) {
5320 Candidate.Viable = false;
5321 Candidate.FailureKind = ovl_fail_bad_target;
5322 return;
5323 }
5324
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005325 // Determine the implicit conversion sequences for each of the
5326 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005327 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005328 if (ArgIdx < NumArgsInProto) {
5329 // (C++ 13.3.2p3): for F to be a viable function, there shall
5330 // exist for each argument an implicit conversion sequence
5331 // (13.3.3.1) that converts that argument to the corresponding
5332 // parameter of F.
5333 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005334 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005335 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005336 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005337 /*InOverloadResolution=*/true,
5338 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005339 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005340 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005341 if (Candidate.Conversions[ArgIdx].isBad()) {
5342 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005343 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00005344 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00005345 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005346 } else {
5347 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5348 // argument for which there is no corresponding parameter is
5349 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005350 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005351 }
5352 }
5353}
5354
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005355/// \brief Add all of the function declarations in the given function set to
5356/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005357void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005358 llvm::ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005359 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005360 bool SuppressUserConversions,
5361 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005362 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005363 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5364 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005365 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005366 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005367 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005368 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005369 Args.slice(1), CandidateSet,
5370 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005371 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005372 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005373 SuppressUserConversions);
5374 } else {
John McCalla0296f72010-03-19 07:35:19 +00005375 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005376 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5377 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005378 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005379 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005380 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005381 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005382 Args[0]->Classify(Context), Args.slice(1),
5383 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005384 else
John McCalla0296f72010-03-19 07:35:19 +00005385 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005386 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005387 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005388 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005389 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005390}
5391
John McCallf0f1cf02009-11-17 07:50:12 +00005392/// AddMethodCandidate - Adds a named decl (which is some kind of
5393/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005394void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005395 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005396 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00005397 Expr **Args, unsigned NumArgs,
5398 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005399 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005400 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005401 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005402
5403 if (isa<UsingShadowDecl>(Decl))
5404 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005405
John McCallf0f1cf02009-11-17 07:50:12 +00005406 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5407 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5408 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005409 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5410 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005411 ObjectType, ObjectClassification,
5412 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005413 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005414 } else {
John McCalla0296f72010-03-19 07:35:19 +00005415 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005416 ObjectType, ObjectClassification,
5417 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorf1e46692010-04-16 17:33:27 +00005418 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005419 }
5420}
5421
Douglas Gregor436424c2008-11-18 23:14:02 +00005422/// AddMethodCandidate - Adds the given C++ member function to the set
5423/// of candidate functions, using the given function call arguments
5424/// and the object argument (@c Object). For example, in a call
5425/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5426/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5427/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005428/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005429void
John McCalla0296f72010-03-19 07:35:19 +00005430Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005431 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005432 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005433 llvm::ArrayRef<Expr *> Args,
Douglas Gregor436424c2008-11-18 23:14:02 +00005434 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005435 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00005436 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00005437 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005438 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005439 assert(!isa<CXXConstructorDecl>(Method) &&
5440 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005441
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005442 if (!CandidateSet.isNewCandidate(Method))
5443 return;
5444
Douglas Gregor27381f32009-11-23 12:27:39 +00005445 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005446 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005447
Douglas Gregor436424c2008-11-18 23:14:02 +00005448 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005449 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005450 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005451 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005452 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005453 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005454 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005455
5456 unsigned NumArgsInProto = Proto->getNumArgs();
5457
5458 // (C++ 13.3.2p2): A candidate function having fewer than m
5459 // parameters is viable only if it has an ellipsis in its parameter
5460 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005461 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005462 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005463 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005464 return;
5465 }
5466
5467 // (C++ 13.3.2p2): A candidate function having more than m parameters
5468 // is viable only if the (m+1)st parameter has a default argument
5469 // (8.3.6). For the purposes of overload resolution, the
5470 // parameter list is truncated on the right, so that there are
5471 // exactly m parameters.
5472 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005473 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005474 // Not enough arguments.
5475 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005476 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005477 return;
5478 }
5479
5480 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005481
John McCall6e9f8f62009-12-03 04:06:58 +00005482 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005483 // The implicit object argument is ignored.
5484 Candidate.IgnoreObjectArgument = true;
5485 else {
5486 // Determine the implicit conversion sequence for the object
5487 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005488 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005489 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5490 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005491 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005492 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005493 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005494 return;
5495 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005496 }
5497
5498 // Determine the implicit conversion sequences for each of the
5499 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005500 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005501 if (ArgIdx < NumArgsInProto) {
5502 // (C++ 13.3.2p3): for F to be a viable function, there shall
5503 // exist for each argument an implicit conversion sequence
5504 // (13.3.3.1) that converts that argument to the corresponding
5505 // parameter of F.
5506 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005507 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005508 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005509 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005510 /*InOverloadResolution=*/true,
5511 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005512 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005513 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005514 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005515 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005516 break;
5517 }
5518 } else {
5519 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5520 // argument for which there is no corresponding parameter is
5521 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005522 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005523 }
5524 }
5525}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005526
Douglas Gregor97628d62009-08-21 00:16:32 +00005527/// \brief Add a C++ member function template as a candidate to the candidate
5528/// set, using template argument deduction to produce an appropriate member
5529/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005530void
Douglas Gregor97628d62009-08-21 00:16:32 +00005531Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005532 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005533 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005534 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005535 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005536 Expr::Classification ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005537 llvm::ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005538 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005539 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005540 if (!CandidateSet.isNewCandidate(MethodTmpl))
5541 return;
5542
Douglas Gregor97628d62009-08-21 00:16:32 +00005543 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005544 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005545 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005546 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005547 // candidate functions in the usual way.113) A given name can refer to one
5548 // or more function templates and also to a set of overloaded non-template
5549 // functions. In such a case, the candidate functions generated from each
5550 // function template are combined with the set of non-template candidate
5551 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005552 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005553 FunctionDecl *Specialization = 0;
5554 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005555 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5556 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005557 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005558 Candidate.FoundDecl = FoundDecl;
5559 Candidate.Function = MethodTmpl->getTemplatedDecl();
5560 Candidate.Viable = false;
5561 Candidate.FailureKind = ovl_fail_bad_deduction;
5562 Candidate.IsSurrogate = false;
5563 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005564 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005565 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005566 Info);
5567 return;
5568 }
Mike Stump11289f42009-09-09 15:08:12 +00005569
Douglas Gregor97628d62009-08-21 00:16:32 +00005570 // Add the function template specialization produced by template argument
5571 // deduction as a candidate.
5572 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005573 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005574 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005575 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005576 ActingContext, ObjectType, ObjectClassification, Args,
5577 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005578}
5579
Douglas Gregor05155d82009-08-21 23:19:43 +00005580/// \brief Add a C++ function template specialization as a candidate
5581/// in the candidate set, using template argument deduction to produce
5582/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005583void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005584Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005585 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005586 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005587 llvm::ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005588 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005589 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005590 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5591 return;
5592
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005593 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005594 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005595 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005596 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005597 // candidate functions in the usual way.113) A given name can refer to one
5598 // or more function templates and also to a set of overloaded non-template
5599 // functions. In such a case, the candidate functions generated from each
5600 // function template are combined with the set of non-template candidate
5601 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005602 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005603 FunctionDecl *Specialization = 0;
5604 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005605 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5606 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005607 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005608 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005609 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5610 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005611 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005612 Candidate.IsSurrogate = false;
5613 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005614 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005615 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005616 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005617 return;
5618 }
Mike Stump11289f42009-09-09 15:08:12 +00005619
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005620 // Add the function template specialization produced by template argument
5621 // deduction as a candidate.
5622 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005623 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005624 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005625}
Mike Stump11289f42009-09-09 15:08:12 +00005626
Douglas Gregora1f013e2008-11-07 22:36:19 +00005627/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005628/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005629/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005630/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005631/// (which may or may not be the same type as the type that the
5632/// conversion function produces).
5633void
5634Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005635 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005636 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005637 Expr *From, QualType ToType,
5638 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005639 assert(!Conversion->getDescribedFunctionTemplate() &&
5640 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005641 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005642 if (!CandidateSet.isNewCandidate(Conversion))
5643 return;
5644
Douglas Gregor27381f32009-11-23 12:27:39 +00005645 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005646 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005647
Douglas Gregora1f013e2008-11-07 22:36:19 +00005648 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005649 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005650 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005651 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005652 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005653 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005654 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005655 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005656 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005657 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005658 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005659
Douglas Gregor6affc782010-08-19 15:37:02 +00005660 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005661 // For conversion functions, the function is considered to be a member of
5662 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005663 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005664 //
5665 // Determine the implicit conversion sequence for the implicit
5666 // object parameter.
5667 QualType ImplicitParamType = From->getType();
5668 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5669 ImplicitParamType = FromPtrType->getPointeeType();
5670 CXXRecordDecl *ConversionContext
5671 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005672
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005673 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005674 = TryObjectArgumentInitialization(*this, From->getType(),
5675 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005676 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005677
John McCall0d1da222010-01-12 00:44:57 +00005678 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005679 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005680 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005681 return;
5682 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005683
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005684 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005685 // derived to base as such conversions are given Conversion Rank. They only
5686 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5687 QualType FromCanon
5688 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5689 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5690 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5691 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005692 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005693 return;
5694 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005695
Douglas Gregora1f013e2008-11-07 22:36:19 +00005696 // To determine what the conversion from the result of calling the
5697 // conversion function to the type we're eventually trying to
5698 // convert to (ToType), we need to synthesize a call to the
5699 // conversion function and attempt copy initialization from it. This
5700 // makes sure that we get the right semantics with respect to
5701 // lvalues/rvalues and the type. Fortunately, we can allocate this
5702 // call on the stack and we don't need its arguments to be
5703 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00005704 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005705 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005706 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5707 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005708 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005709 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005710
Richard Smith48d24642011-07-13 22:53:21 +00005711 QualType ConversionType = Conversion->getConversionType();
5712 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005713 Candidate.Viable = false;
5714 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5715 return;
5716 }
5717
Richard Smith48d24642011-07-13 22:53:21 +00005718 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005719
Mike Stump11289f42009-09-09 15:08:12 +00005720 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005721 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5722 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005723 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Benjamin Kramerc215e762012-08-24 11:54:20 +00005724 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005725 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005726 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005727 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005728 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005729 /*InOverloadResolution=*/false,
5730 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005731
John McCall0d1da222010-01-12 00:44:57 +00005732 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005733 case ImplicitConversionSequence::StandardConversion:
5734 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005735
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005736 // C++ [over.ics.user]p3:
5737 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005738 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005739 // shall have exact match rank.
5740 if (Conversion->getPrimaryTemplate() &&
5741 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5742 Candidate.Viable = false;
5743 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005745
Douglas Gregorcba72b12011-01-21 05:18:22 +00005746 // C++0x [dcl.init.ref]p5:
5747 // In the second case, if the reference is an rvalue reference and
5748 // the second standard conversion sequence of the user-defined
5749 // conversion sequence includes an lvalue-to-rvalue conversion, the
5750 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005751 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005752 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5753 Candidate.Viable = false;
5754 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5755 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005756 break;
5757
5758 case ImplicitConversionSequence::BadConversion:
5759 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005760 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005761 break;
5762
5763 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005764 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005765 "Can only end up with a standard conversion sequence or failure");
5766 }
5767}
5768
Douglas Gregor05155d82009-08-21 23:19:43 +00005769/// \brief Adds a conversion function template specialization
5770/// candidate to the overload set, using template argument deduction
5771/// to deduce the template arguments of the conversion function
5772/// template from the type that we are converting to (C++
5773/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005774void
Douglas Gregor05155d82009-08-21 23:19:43 +00005775Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005776 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005777 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005778 Expr *From, QualType ToType,
5779 OverloadCandidateSet &CandidateSet) {
5780 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5781 "Only conversion function templates permitted here");
5782
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005783 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5784 return;
5785
Craig Toppere6706e42012-09-19 02:26:47 +00005786 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005787 CXXConversionDecl *Specialization = 0;
5788 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005789 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005790 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005791 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005792 Candidate.FoundDecl = FoundDecl;
5793 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5794 Candidate.Viable = false;
5795 Candidate.FailureKind = ovl_fail_bad_deduction;
5796 Candidate.IsSurrogate = false;
5797 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005798 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005799 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005800 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005801 return;
5802 }
Mike Stump11289f42009-09-09 15:08:12 +00005803
Douglas Gregor05155d82009-08-21 23:19:43 +00005804 // Add the conversion function template specialization produced by
5805 // template argument deduction as a candidate.
5806 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005807 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005808 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005809}
5810
Douglas Gregorab7897a2008-11-19 22:57:39 +00005811/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5812/// converts the given @c Object to a function pointer via the
5813/// conversion function @c Conversion, and then attempts to call it
5814/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5815/// the type of function that we'll eventually be calling.
5816void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005817 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005818 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005819 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005820 Expr *Object,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005821 llvm::ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005822 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005823 if (!CandidateSet.isNewCandidate(Conversion))
5824 return;
5825
Douglas Gregor27381f32009-11-23 12:27:39 +00005826 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005827 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005828
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005829 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005830 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005831 Candidate.Function = 0;
5832 Candidate.Surrogate = Conversion;
5833 Candidate.Viable = true;
5834 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005835 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005836 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005837
5838 // Determine the implicit conversion sequence for the implicit
5839 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005840 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005841 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005842 Object->Classify(Context),
5843 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005844 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005845 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005846 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005847 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005848 return;
5849 }
5850
5851 // The first conversion is actually a user-defined conversion whose
5852 // first conversion is ObjectInit's standard conversion (which is
5853 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005854 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005855 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005856 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005857 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005858 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005859 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005860 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005861 = Candidate.Conversions[0].UserDefined.Before;
5862 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5863
Mike Stump11289f42009-09-09 15:08:12 +00005864 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005865 unsigned NumArgsInProto = Proto->getNumArgs();
5866
5867 // (C++ 13.3.2p2): A candidate function having fewer than m
5868 // parameters is viable only if it has an ellipsis in its parameter
5869 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005870 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005871 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005872 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005873 return;
5874 }
5875
5876 // Function types don't have any default arguments, so just check if
5877 // we have enough arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005878 if (Args.size() < NumArgsInProto) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005879 // Not enough arguments.
5880 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005881 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005882 return;
5883 }
5884
5885 // Determine the implicit conversion sequences for each of the
5886 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005887 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005888 if (ArgIdx < NumArgsInProto) {
5889 // (C++ 13.3.2p3): for F to be a viable function, there shall
5890 // exist for each argument an implicit conversion sequence
5891 // (13.3.3.1) that converts that argument to the corresponding
5892 // parameter of F.
5893 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005894 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005895 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005896 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005897 /*InOverloadResolution=*/false,
5898 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005899 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005900 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005901 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005902 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005903 break;
5904 }
5905 } else {
5906 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5907 // argument for which there is no corresponding parameter is
5908 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005909 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005910 }
5911 }
5912}
5913
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005914/// \brief Add overload candidates for overloaded operators that are
5915/// member functions.
5916///
5917/// Add the overloaded operator candidates that are member functions
5918/// for the operator Op that was used in an operator expression such
5919/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5920/// CandidateSet will store the added overload candidates. (C++
5921/// [over.match.oper]).
5922void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5923 SourceLocation OpLoc,
5924 Expr **Args, unsigned NumArgs,
5925 OverloadCandidateSet& CandidateSet,
5926 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005927 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5928
5929 // C++ [over.match.oper]p3:
5930 // For a unary operator @ with an operand of a type whose
5931 // cv-unqualified version is T1, and for a binary operator @ with
5932 // a left operand of a type whose cv-unqualified version is T1 and
5933 // a right operand of a type whose cv-unqualified version is T2,
5934 // three sets of candidate functions, designated member
5935 // candidates, non-member candidates and built-in candidates, are
5936 // constructed as follows:
5937 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005938
5939 // -- If T1 is a class type, the set of member candidates is the
5940 // result of the qualified lookup of T1::operator@
5941 // (13.3.1.1.1); otherwise, the set of member candidates is
5942 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005943 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005944 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005945 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005946 return;
Mike Stump11289f42009-09-09 15:08:12 +00005947
John McCall27b18f82009-11-17 02:14:36 +00005948 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5949 LookupQualifiedName(Operators, T1Rec->getDecl());
5950 Operators.suppressDiagnostics();
5951
Mike Stump11289f42009-09-09 15:08:12 +00005952 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005953 OperEnd = Operators.end();
5954 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005955 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005956 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005957 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005958 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005959 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005960 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005961}
5962
Douglas Gregora11693b2008-11-12 17:17:38 +00005963/// AddBuiltinCandidate - Add a candidate for a built-in
5964/// operator. ResultTy and ParamTys are the result and parameter types
5965/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005966/// arguments being passed to the candidate. IsAssignmentOperator
5967/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005968/// operator. NumContextualBoolArguments is the number of arguments
5969/// (at the beginning of the argument list) that will be contextually
5970/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005971void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005972 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005973 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005974 bool IsAssignmentOperator,
5975 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005976 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005977 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005978
Douglas Gregora11693b2008-11-12 17:17:38 +00005979 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005980 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005981 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005982 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005983 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005984 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005985 Candidate.BuiltinTypes.ResultTy = ResultTy;
5986 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5987 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5988
5989 // Determine the implicit conversion sequences for each of the
5990 // arguments.
5991 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005992 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005993 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005994 // C++ [over.match.oper]p4:
5995 // For the built-in assignment operators, conversions of the
5996 // left operand are restricted as follows:
5997 // -- no temporaries are introduced to hold the left operand, and
5998 // -- no user-defined conversions are applied to the left
5999 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006000 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006001 //
6002 // We block these conversions by turning off user-defined
6003 // conversions, since that is the only way that initialization of
6004 // a reference to a non-class type can occur from something that
6005 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006006 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006007 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006008 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006009 Candidate.Conversions[ArgIdx]
6010 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006011 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006012 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006013 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006014 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006015 /*InOverloadResolution=*/false,
6016 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006017 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006018 }
John McCall0d1da222010-01-12 00:44:57 +00006019 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006020 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006021 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006022 break;
6023 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006024 }
6025}
6026
6027/// BuiltinCandidateTypeSet - A set of types that will be used for the
6028/// candidate operator functions for built-in operators (C++
6029/// [over.built]). The types are separated into pointer types and
6030/// enumeration types.
6031class BuiltinCandidateTypeSet {
6032 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006033 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006034
6035 /// PointerTypes - The set of pointer types that will be used in the
6036 /// built-in candidates.
6037 TypeSet PointerTypes;
6038
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006039 /// MemberPointerTypes - The set of member pointer types that will be
6040 /// used in the built-in candidates.
6041 TypeSet MemberPointerTypes;
6042
Douglas Gregora11693b2008-11-12 17:17:38 +00006043 /// EnumerationTypes - The set of enumeration types that will be
6044 /// used in the built-in candidates.
6045 TypeSet EnumerationTypes;
6046
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006047 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006048 /// candidates.
6049 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006050
6051 /// \brief A flag indicating non-record types are viable candidates
6052 bool HasNonRecordTypes;
6053
6054 /// \brief A flag indicating whether either arithmetic or enumeration types
6055 /// were present in the candidate set.
6056 bool HasArithmeticOrEnumeralTypes;
6057
Douglas Gregor80af3132011-05-21 23:15:46 +00006058 /// \brief A flag indicating whether the nullptr type was present in the
6059 /// candidate set.
6060 bool HasNullPtrType;
6061
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006062 /// Sema - The semantic analysis instance where we are building the
6063 /// candidate type set.
6064 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006065
Douglas Gregora11693b2008-11-12 17:17:38 +00006066 /// Context - The AST context in which we will build the type sets.
6067 ASTContext &Context;
6068
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006069 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6070 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006071 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006072
6073public:
6074 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006075 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006076
Mike Stump11289f42009-09-09 15:08:12 +00006077 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006078 : HasNonRecordTypes(false),
6079 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006080 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006081 SemaRef(SemaRef),
6082 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006083
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006084 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006085 SourceLocation Loc,
6086 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006087 bool AllowExplicitConversions,
6088 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006089
6090 /// pointer_begin - First pointer type found;
6091 iterator pointer_begin() { return PointerTypes.begin(); }
6092
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006093 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006094 iterator pointer_end() { return PointerTypes.end(); }
6095
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006096 /// member_pointer_begin - First member pointer type found;
6097 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6098
6099 /// member_pointer_end - Past the last member pointer type found;
6100 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6101
Douglas Gregora11693b2008-11-12 17:17:38 +00006102 /// enumeration_begin - First enumeration type found;
6103 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6104
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006105 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006106 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006107
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006108 iterator vector_begin() { return VectorTypes.begin(); }
6109 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006110
6111 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6112 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006113 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006114};
6115
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006116/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006117/// the set of pointer types along with any more-qualified variants of
6118/// that type. For example, if @p Ty is "int const *", this routine
6119/// will add "int const *", "int const volatile *", "int const
6120/// restrict *", and "int const volatile restrict *" to the set of
6121/// pointer types. Returns true if the add of @p Ty itself succeeded,
6122/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006123///
6124/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006125bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006126BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6127 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006128
Douglas Gregora11693b2008-11-12 17:17:38 +00006129 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006130 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006131 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006132
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006133 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006134 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006135 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006136 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006137 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6138 PointeeTy = PTy->getPointeeType();
6139 buildObjCPtr = true;
6140 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006141 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006142 }
6143
Sebastian Redl4990a632009-11-18 20:39:26 +00006144 // Don't add qualified variants of arrays. For one, they're not allowed
6145 // (the qualifier would sink to the element type), and for another, the
6146 // only overload situation where it matters is subscript or pointer +- int,
6147 // and those shouldn't have qualifier variants anyway.
6148 if (PointeeTy->isArrayType())
6149 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006150
John McCall8ccfcb52009-09-24 19:53:00 +00006151 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006152 bool hasVolatile = VisibleQuals.hasVolatile();
6153 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006154
John McCall8ccfcb52009-09-24 19:53:00 +00006155 // Iterate through all strict supersets of BaseCVR.
6156 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6157 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006158 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006159 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006160
6161 // Skip over restrict if no restrict found anywhere in the types, or if
6162 // the type cannot be restrict-qualified.
6163 if ((CVR & Qualifiers::Restrict) &&
6164 (!hasRestrict ||
6165 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6166 continue;
6167
6168 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006169 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006170
6171 // Build qualified pointer type.
6172 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006173 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006174 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006175 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006176 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6177
6178 // Insert qualified pointer type.
6179 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006180 }
6181
6182 return true;
6183}
6184
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006185/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6186/// to the set of pointer types along with any more-qualified variants of
6187/// that type. For example, if @p Ty is "int const *", this routine
6188/// will add "int const *", "int const volatile *", "int const
6189/// restrict *", and "int const volatile restrict *" to the set of
6190/// pointer types. Returns true if the add of @p Ty itself succeeded,
6191/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006192///
6193/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006194bool
6195BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6196 QualType Ty) {
6197 // Insert this type.
6198 if (!MemberPointerTypes.insert(Ty))
6199 return false;
6200
John McCall8ccfcb52009-09-24 19:53:00 +00006201 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6202 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006203
John McCall8ccfcb52009-09-24 19:53:00 +00006204 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006205 // Don't add qualified variants of arrays. For one, they're not allowed
6206 // (the qualifier would sink to the element type), and for another, the
6207 // only overload situation where it matters is subscript or pointer +- int,
6208 // and those shouldn't have qualifier variants anyway.
6209 if (PointeeTy->isArrayType())
6210 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006211 const Type *ClassTy = PointerTy->getClass();
6212
6213 // Iterate through all strict supersets of the pointee type's CVR
6214 // qualifiers.
6215 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6216 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6217 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006218
John McCall8ccfcb52009-09-24 19:53:00 +00006219 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006220 MemberPointerTypes.insert(
6221 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006222 }
6223
6224 return true;
6225}
6226
Douglas Gregora11693b2008-11-12 17:17:38 +00006227/// AddTypesConvertedFrom - Add each of the types to which the type @p
6228/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006229/// primarily interested in pointer types and enumeration types. We also
6230/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006231/// AllowUserConversions is true if we should look at the conversion
6232/// functions of a class type, and AllowExplicitConversions if we
6233/// should also include the explicit conversion functions of a class
6234/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006235void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006236BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006237 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006238 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006239 bool AllowExplicitConversions,
6240 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006241 // Only deal with canonical types.
6242 Ty = Context.getCanonicalType(Ty);
6243
6244 // Look through reference types; they aren't part of the type of an
6245 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006246 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006247 Ty = RefTy->getPointeeType();
6248
John McCall33ddac02011-01-19 10:06:00 +00006249 // If we're dealing with an array type, decay to the pointer.
6250 if (Ty->isArrayType())
6251 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6252
6253 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006254 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006255
Chandler Carruth00a38332010-12-13 01:44:01 +00006256 // Flag if we ever add a non-record type.
6257 const RecordType *TyRec = Ty->getAs<RecordType>();
6258 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6259
Chandler Carruth00a38332010-12-13 01:44:01 +00006260 // Flag if we encounter an arithmetic type.
6261 HasArithmeticOrEnumeralTypes =
6262 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6263
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006264 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6265 PointerTypes.insert(Ty);
6266 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006267 // Insert our type, and its more-qualified variants, into the set
6268 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006269 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006270 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006271 } else if (Ty->isMemberPointerType()) {
6272 // Member pointers are far easier, since the pointee can't be converted.
6273 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6274 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006275 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006276 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006277 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006278 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006279 // We treat vector types as arithmetic types in many contexts as an
6280 // extension.
6281 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006282 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006283 } else if (Ty->isNullPtrType()) {
6284 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006285 } else if (AllowUserConversions && TyRec) {
6286 // No conversion functions in incomplete types.
6287 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6288 return;
Mike Stump11289f42009-09-09 15:08:12 +00006289
Chandler Carruth00a38332010-12-13 01:44:01 +00006290 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006291 std::pair<CXXRecordDecl::conversion_iterator,
6292 CXXRecordDecl::conversion_iterator>
6293 Conversions = ClassDecl->getVisibleConversionFunctions();
6294 for (CXXRecordDecl::conversion_iterator
6295 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006296 NamedDecl *D = I.getDecl();
6297 if (isa<UsingShadowDecl>(D))
6298 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006299
Chandler Carruth00a38332010-12-13 01:44:01 +00006300 // Skip conversion function templates; they don't tell us anything
6301 // about which builtin types we can convert to.
6302 if (isa<FunctionTemplateDecl>(D))
6303 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006304
Chandler Carruth00a38332010-12-13 01:44:01 +00006305 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6306 if (AllowExplicitConversions || !Conv->isExplicit()) {
6307 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6308 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006309 }
6310 }
6311 }
6312}
6313
Douglas Gregor84605ae2009-08-24 13:43:27 +00006314/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6315/// the volatile- and non-volatile-qualified assignment operators for the
6316/// given type to the candidate set.
6317static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6318 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00006319 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006320 unsigned NumArgs,
6321 OverloadCandidateSet &CandidateSet) {
6322 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006323
Douglas Gregor84605ae2009-08-24 13:43:27 +00006324 // T& operator=(T&, T)
6325 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6326 ParamTypes[1] = T;
6327 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6328 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006329
Douglas Gregor84605ae2009-08-24 13:43:27 +00006330 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6331 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006332 ParamTypes[0]
6333 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006334 ParamTypes[1] = T;
6335 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006336 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006337 }
6338}
Mike Stump11289f42009-09-09 15:08:12 +00006339
Sebastian Redl1054fae2009-10-25 17:03:50 +00006340/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6341/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006342static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6343 Qualifiers VRQuals;
6344 const RecordType *TyRec;
6345 if (const MemberPointerType *RHSMPType =
6346 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006347 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006348 else
6349 TyRec = ArgExpr->getType()->getAs<RecordType>();
6350 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006351 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006352 VRQuals.addVolatile();
6353 VRQuals.addRestrict();
6354 return VRQuals;
6355 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006356
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006357 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006358 if (!ClassDecl->hasDefinition())
6359 return VRQuals;
6360
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006361 std::pair<CXXRecordDecl::conversion_iterator,
6362 CXXRecordDecl::conversion_iterator>
6363 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006364
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006365 for (CXXRecordDecl::conversion_iterator
6366 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006367 NamedDecl *D = I.getDecl();
6368 if (isa<UsingShadowDecl>(D))
6369 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6370 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006371 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6372 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6373 CanTy = ResTypeRef->getPointeeType();
6374 // Need to go down the pointer/mempointer chain and add qualifiers
6375 // as see them.
6376 bool done = false;
6377 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006378 if (CanTy.isRestrictQualified())
6379 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006380 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6381 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006382 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006383 CanTy->getAs<MemberPointerType>())
6384 CanTy = ResTypeMPtr->getPointeeType();
6385 else
6386 done = true;
6387 if (CanTy.isVolatileQualified())
6388 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006389 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6390 return VRQuals;
6391 }
6392 }
6393 }
6394 return VRQuals;
6395}
John McCall52872982010-11-13 05:51:15 +00006396
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006397namespace {
John McCall52872982010-11-13 05:51:15 +00006398
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006399/// \brief Helper class to manage the addition of builtin operator overload
6400/// candidates. It provides shared state and utility methods used throughout
6401/// the process, as well as a helper method to add each group of builtin
6402/// operator overloads from the standard to a candidate set.
6403class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006404 // Common instance state available to all overload candidate addition methods.
6405 Sema &S;
6406 Expr **Args;
6407 unsigned NumArgs;
6408 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006409 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006410 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006411 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006412
Chandler Carruthc6586e52010-12-12 10:35:00 +00006413 // Define some constants used to index and iterate over the arithemetic types
6414 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006415 // The "promoted arithmetic types" are the arithmetic
6416 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006417 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00006418 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00006419 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00006420 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00006421 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00006422 LastPromotedArithmeticType = 11;
6423 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00006424
Chandler Carruthc6586e52010-12-12 10:35:00 +00006425 /// \brief Get the canonical type for a given arithmetic type index.
6426 CanQualType getArithmeticType(unsigned index) {
6427 assert(index < NumArithmeticTypes);
6428 static CanQualType ASTContext::* const
6429 ArithmeticTypes[NumArithmeticTypes] = {
6430 // Start of promoted types.
6431 &ASTContext::FloatTy,
6432 &ASTContext::DoubleTy,
6433 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006434
Chandler Carruthc6586e52010-12-12 10:35:00 +00006435 // Start of integral types.
6436 &ASTContext::IntTy,
6437 &ASTContext::LongTy,
6438 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006439 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006440 &ASTContext::UnsignedIntTy,
6441 &ASTContext::UnsignedLongTy,
6442 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006443 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006444 // End of promoted types.
6445
6446 &ASTContext::BoolTy,
6447 &ASTContext::CharTy,
6448 &ASTContext::WCharTy,
6449 &ASTContext::Char16Ty,
6450 &ASTContext::Char32Ty,
6451 &ASTContext::SignedCharTy,
6452 &ASTContext::ShortTy,
6453 &ASTContext::UnsignedCharTy,
6454 &ASTContext::UnsignedShortTy,
6455 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00006456 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00006457 };
6458 return S.Context.*ArithmeticTypes[index];
6459 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006460
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006461 /// \brief Gets the canonical type resulting from the usual arithemetic
6462 /// converions for the given arithmetic types.
6463 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6464 // Accelerator table for performing the usual arithmetic conversions.
6465 // The rules are basically:
6466 // - if either is floating-point, use the wider floating-point
6467 // - if same signedness, use the higher rank
6468 // - if same size, use unsigned of the higher rank
6469 // - use the larger type
6470 // These rules, together with the axiom that higher ranks are
6471 // never smaller, are sufficient to precompute all of these results
6472 // *except* when dealing with signed types of higher rank.
6473 // (we could precompute SLL x UI for all known platforms, but it's
6474 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00006475 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006476 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00006477 Dep=-1,
6478 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006479 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00006480 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006481 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00006482/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6483/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6484/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6485/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6486/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6487/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6488/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6489/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6490/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6491/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6492/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006493 };
6494
6495 assert(L < LastPromotedArithmeticType);
6496 assert(R < LastPromotedArithmeticType);
6497 int Idx = ConversionsTable[L][R];
6498
6499 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006500 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006501
6502 // Slow path: we need to compare widths.
6503 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006504 CanQualType LT = getArithmeticType(L),
6505 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006506 unsigned LW = S.Context.getIntWidth(LT),
6507 RW = S.Context.getIntWidth(RT);
6508
6509 // If they're different widths, use the signed type.
6510 if (LW > RW) return LT;
6511 else if (LW < RW) return RT;
6512
6513 // Otherwise, use the unsigned type of the signed type's rank.
6514 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6515 assert(L == SLL || R == SLL);
6516 return S.Context.UnsignedLongLongTy;
6517 }
6518
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006519 /// \brief Helper method to factor out the common pattern of adding overloads
6520 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006521 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006522 bool HasVolatile,
6523 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006524 QualType ParamTypes[2] = {
6525 S.Context.getLValueReferenceType(CandidateTy),
6526 S.Context.IntTy
6527 };
6528
6529 // Non-volatile version.
6530 if (NumArgs == 1)
6531 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6532 else
6533 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6534
6535 // Use a heuristic to reduce number of builtin candidates in the set:
6536 // add volatile version only if there are conversions to a volatile type.
6537 if (HasVolatile) {
6538 ParamTypes[0] =
6539 S.Context.getLValueReferenceType(
6540 S.Context.getVolatileType(CandidateTy));
6541 if (NumArgs == 1)
6542 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6543 else
6544 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6545 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00006546
6547 // Add restrict version only if there are conversions to a restrict type
6548 // and our candidate type is a non-restrict-qualified pointer.
6549 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6550 !CandidateTy.isRestrictQualified()) {
6551 ParamTypes[0]
6552 = S.Context.getLValueReferenceType(
6553 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6554 if (NumArgs == 1)
6555 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6556 else
6557 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6558
6559 if (HasVolatile) {
6560 ParamTypes[0]
6561 = S.Context.getLValueReferenceType(
6562 S.Context.getCVRQualifiedType(CandidateTy,
6563 (Qualifiers::Volatile |
6564 Qualifiers::Restrict)));
6565 if (NumArgs == 1)
6566 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6567 CandidateSet);
6568 else
6569 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6570 }
6571 }
6572
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006573 }
6574
6575public:
6576 BuiltinOperatorOverloadBuilder(
6577 Sema &S, Expr **Args, unsigned NumArgs,
6578 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006579 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006580 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006581 OverloadCandidateSet &CandidateSet)
6582 : S(S), Args(Args), NumArgs(NumArgs),
6583 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006584 HasArithmeticOrEnumeralCandidateType(
6585 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006586 CandidateTypes(CandidateTypes),
6587 CandidateSet(CandidateSet) {
6588 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006589 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006590 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006591 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00006592 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006593 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006594 assert(getArithmeticType(FirstPromotedArithmeticType)
6595 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006596 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006597 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00006598 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006599 "Invalid last promoted arithmetic type");
6600 }
6601
6602 // C++ [over.built]p3:
6603 //
6604 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6605 // is either volatile or empty, there exist candidate operator
6606 // functions of the form
6607 //
6608 // VQ T& operator++(VQ T&);
6609 // T operator++(VQ T&, int);
6610 //
6611 // C++ [over.built]p4:
6612 //
6613 // For every pair (T, VQ), where T is an arithmetic type other
6614 // than bool, and VQ is either volatile or empty, there exist
6615 // candidate operator functions of the form
6616 //
6617 // VQ T& operator--(VQ T&);
6618 // T operator--(VQ T&, int);
6619 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006620 if (!HasArithmeticOrEnumeralCandidateType)
6621 return;
6622
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006623 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6624 Arith < NumArithmeticTypes; ++Arith) {
6625 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00006626 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00006627 VisibleTypeConversionsQuals.hasVolatile(),
6628 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006629 }
6630 }
6631
6632 // C++ [over.built]p5:
6633 //
6634 // For every pair (T, VQ), where T is a cv-qualified or
6635 // cv-unqualified object type, and VQ is either volatile or
6636 // empty, there exist candidate operator functions of the form
6637 //
6638 // T*VQ& operator++(T*VQ&);
6639 // T*VQ& operator--(T*VQ&);
6640 // T* operator++(T*VQ&, int);
6641 // T* operator--(T*VQ&, int);
6642 void addPlusPlusMinusMinusPointerOverloads() {
6643 for (BuiltinCandidateTypeSet::iterator
6644 Ptr = CandidateTypes[0].pointer_begin(),
6645 PtrEnd = CandidateTypes[0].pointer_end();
6646 Ptr != PtrEnd; ++Ptr) {
6647 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00006648 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006649 continue;
6650
6651 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006652 (!(*Ptr).isVolatileQualified() &&
6653 VisibleTypeConversionsQuals.hasVolatile()),
6654 (!(*Ptr).isRestrictQualified() &&
6655 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006656 }
6657 }
6658
6659 // C++ [over.built]p6:
6660 // For every cv-qualified or cv-unqualified object type T, there
6661 // exist candidate operator functions of the form
6662 //
6663 // T& operator*(T*);
6664 //
6665 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006666 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00006667 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006668 // T& operator*(T*);
6669 void addUnaryStarPointerOverloads() {
6670 for (BuiltinCandidateTypeSet::iterator
6671 Ptr = CandidateTypes[0].pointer_begin(),
6672 PtrEnd = CandidateTypes[0].pointer_end();
6673 Ptr != PtrEnd; ++Ptr) {
6674 QualType ParamTy = *Ptr;
6675 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006676 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6677 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006678
Douglas Gregor02824322011-01-26 19:30:28 +00006679 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6680 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6681 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006682
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006683 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6684 &ParamTy, Args, 1, CandidateSet);
6685 }
6686 }
6687
6688 // C++ [over.built]p9:
6689 // For every promoted arithmetic type T, there exist candidate
6690 // operator functions of the form
6691 //
6692 // T operator+(T);
6693 // T operator-(T);
6694 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006695 if (!HasArithmeticOrEnumeralCandidateType)
6696 return;
6697
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006698 for (unsigned Arith = FirstPromotedArithmeticType;
6699 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006700 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006701 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6702 }
6703
6704 // Extension: We also add these operators for vector types.
6705 for (BuiltinCandidateTypeSet::iterator
6706 Vec = CandidateTypes[0].vector_begin(),
6707 VecEnd = CandidateTypes[0].vector_end();
6708 Vec != VecEnd; ++Vec) {
6709 QualType VecTy = *Vec;
6710 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6711 }
6712 }
6713
6714 // C++ [over.built]p8:
6715 // For every type T, there exist candidate operator functions of
6716 // the form
6717 //
6718 // T* operator+(T*);
6719 void addUnaryPlusPointerOverloads() {
6720 for (BuiltinCandidateTypeSet::iterator
6721 Ptr = CandidateTypes[0].pointer_begin(),
6722 PtrEnd = CandidateTypes[0].pointer_end();
6723 Ptr != PtrEnd; ++Ptr) {
6724 QualType ParamTy = *Ptr;
6725 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6726 }
6727 }
6728
6729 // C++ [over.built]p10:
6730 // For every promoted integral type T, there exist candidate
6731 // operator functions of the form
6732 //
6733 // T operator~(T);
6734 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006735 if (!HasArithmeticOrEnumeralCandidateType)
6736 return;
6737
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006738 for (unsigned Int = FirstPromotedIntegralType;
6739 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006740 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006741 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6742 }
6743
6744 // Extension: We also add this operator for vector types.
6745 for (BuiltinCandidateTypeSet::iterator
6746 Vec = CandidateTypes[0].vector_begin(),
6747 VecEnd = CandidateTypes[0].vector_end();
6748 Vec != VecEnd; ++Vec) {
6749 QualType VecTy = *Vec;
6750 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6751 }
6752 }
6753
6754 // C++ [over.match.oper]p16:
6755 // For every pointer to member type T, there exist candidate operator
6756 // functions of the form
6757 //
6758 // bool operator==(T,T);
6759 // bool operator!=(T,T);
6760 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6761 /// Set of (canonical) types that we've already handled.
6762 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6763
6764 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6765 for (BuiltinCandidateTypeSet::iterator
6766 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6767 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6768 MemPtr != MemPtrEnd;
6769 ++MemPtr) {
6770 // Don't add the same builtin candidate twice.
6771 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6772 continue;
6773
6774 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6775 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6776 CandidateSet);
6777 }
6778 }
6779 }
6780
6781 // C++ [over.built]p15:
6782 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006783 // For every T, where T is an enumeration type, a pointer type, or
6784 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006785 //
6786 // bool operator<(T, T);
6787 // bool operator>(T, T);
6788 // bool operator<=(T, T);
6789 // bool operator>=(T, T);
6790 // bool operator==(T, T);
6791 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006792 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00006793 // C++ [over.match.oper]p3:
6794 // [...]the built-in candidates include all of the candidate operator
6795 // functions defined in 13.6 that, compared to the given operator, [...]
6796 // do not have the same parameter-type-list as any non-template non-member
6797 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006798 //
Eli Friedman14f082b2012-09-18 21:52:24 +00006799 // Note that in practice, this only affects enumeration types because there
6800 // aren't any built-in candidates of record type, and a user-defined operator
6801 // must have an operand of record or enumeration type. Also, the only other
6802 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006803 // cannot be overloaded for enumeration types, so this is the only place
6804 // where we must suppress candidates like this.
6805 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6806 UserDefinedBinaryOperators;
6807
6808 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6809 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6810 CandidateTypes[ArgIdx].enumeration_end()) {
6811 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6812 CEnd = CandidateSet.end();
6813 C != CEnd; ++C) {
6814 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6815 continue;
6816
Eli Friedman14f082b2012-09-18 21:52:24 +00006817 if (C->Function->isFunctionTemplateSpecialization())
6818 continue;
6819
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006820 QualType FirstParamType =
6821 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6822 QualType SecondParamType =
6823 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6824
6825 // Skip if either parameter isn't of enumeral type.
6826 if (!FirstParamType->isEnumeralType() ||
6827 !SecondParamType->isEnumeralType())
6828 continue;
6829
6830 // Add this operator to the set of known user-defined operators.
6831 UserDefinedBinaryOperators.insert(
6832 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6833 S.Context.getCanonicalType(SecondParamType)));
6834 }
6835 }
6836 }
6837
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006838 /// Set of (canonical) types that we've already handled.
6839 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6840
6841 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6842 for (BuiltinCandidateTypeSet::iterator
6843 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6844 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6845 Ptr != PtrEnd; ++Ptr) {
6846 // Don't add the same builtin candidate twice.
6847 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6848 continue;
6849
6850 QualType ParamTypes[2] = { *Ptr, *Ptr };
6851 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6852 CandidateSet);
6853 }
6854 for (BuiltinCandidateTypeSet::iterator
6855 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6856 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6857 Enum != EnumEnd; ++Enum) {
6858 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6859
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006860 // Don't add the same builtin candidate twice, or if a user defined
6861 // candidate exists.
6862 if (!AddedTypes.insert(CanonType) ||
6863 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6864 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006865 continue;
6866
6867 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006868 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6869 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006870 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006871
6872 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6873 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6874 if (AddedTypes.insert(NullPtrTy) &&
6875 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6876 NullPtrTy))) {
6877 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6878 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6879 CandidateSet);
6880 }
6881 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006882 }
6883 }
6884
6885 // C++ [over.built]p13:
6886 //
6887 // For every cv-qualified or cv-unqualified object type T
6888 // there exist candidate operator functions of the form
6889 //
6890 // T* operator+(T*, ptrdiff_t);
6891 // T& operator[](T*, ptrdiff_t); [BELOW]
6892 // T* operator-(T*, ptrdiff_t);
6893 // T* operator+(ptrdiff_t, T*);
6894 // T& operator[](ptrdiff_t, T*); [BELOW]
6895 //
6896 // C++ [over.built]p14:
6897 //
6898 // For every T, where T is a pointer to object type, there
6899 // exist candidate operator functions of the form
6900 //
6901 // ptrdiff_t operator-(T, T);
6902 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6903 /// Set of (canonical) types that we've already handled.
6904 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6905
6906 for (int Arg = 0; Arg < 2; ++Arg) {
6907 QualType AsymetricParamTypes[2] = {
6908 S.Context.getPointerDiffType(),
6909 S.Context.getPointerDiffType(),
6910 };
6911 for (BuiltinCandidateTypeSet::iterator
6912 Ptr = CandidateTypes[Arg].pointer_begin(),
6913 PtrEnd = CandidateTypes[Arg].pointer_end();
6914 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006915 QualType PointeeTy = (*Ptr)->getPointeeType();
6916 if (!PointeeTy->isObjectType())
6917 continue;
6918
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006919 AsymetricParamTypes[Arg] = *Ptr;
6920 if (Arg == 0 || Op == OO_Plus) {
6921 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6922 // T* operator+(ptrdiff_t, T*);
6923 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6924 CandidateSet);
6925 }
6926 if (Op == OO_Minus) {
6927 // ptrdiff_t operator-(T, T);
6928 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6929 continue;
6930
6931 QualType ParamTypes[2] = { *Ptr, *Ptr };
6932 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6933 Args, 2, CandidateSet);
6934 }
6935 }
6936 }
6937 }
6938
6939 // C++ [over.built]p12:
6940 //
6941 // For every pair of promoted arithmetic types L and R, there
6942 // exist candidate operator functions of the form
6943 //
6944 // LR operator*(L, R);
6945 // LR operator/(L, R);
6946 // LR operator+(L, R);
6947 // LR operator-(L, R);
6948 // bool operator<(L, R);
6949 // bool operator>(L, R);
6950 // bool operator<=(L, R);
6951 // bool operator>=(L, R);
6952 // bool operator==(L, R);
6953 // bool operator!=(L, R);
6954 //
6955 // where LR is the result of the usual arithmetic conversions
6956 // between types L and R.
6957 //
6958 // C++ [over.built]p24:
6959 //
6960 // For every pair of promoted arithmetic types L and R, there exist
6961 // candidate operator functions of the form
6962 //
6963 // LR operator?(bool, L, R);
6964 //
6965 // where LR is the result of the usual arithmetic conversions
6966 // between types L and R.
6967 // Our candidates ignore the first parameter.
6968 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006969 if (!HasArithmeticOrEnumeralCandidateType)
6970 return;
6971
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006972 for (unsigned Left = FirstPromotedArithmeticType;
6973 Left < LastPromotedArithmeticType; ++Left) {
6974 for (unsigned Right = FirstPromotedArithmeticType;
6975 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006976 QualType LandR[2] = { getArithmeticType(Left),
6977 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006978 QualType Result =
6979 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006980 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006981 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6982 }
6983 }
6984
6985 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6986 // conditional operator for vector types.
6987 for (BuiltinCandidateTypeSet::iterator
6988 Vec1 = CandidateTypes[0].vector_begin(),
6989 Vec1End = CandidateTypes[0].vector_end();
6990 Vec1 != Vec1End; ++Vec1) {
6991 for (BuiltinCandidateTypeSet::iterator
6992 Vec2 = CandidateTypes[1].vector_begin(),
6993 Vec2End = CandidateTypes[1].vector_end();
6994 Vec2 != Vec2End; ++Vec2) {
6995 QualType LandR[2] = { *Vec1, *Vec2 };
6996 QualType Result = S.Context.BoolTy;
6997 if (!isComparison) {
6998 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6999 Result = *Vec1;
7000 else
7001 Result = *Vec2;
7002 }
7003
7004 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7005 }
7006 }
7007 }
7008
7009 // C++ [over.built]p17:
7010 //
7011 // For every pair of promoted integral types L and R, there
7012 // exist candidate operator functions of the form
7013 //
7014 // LR operator%(L, R);
7015 // LR operator&(L, R);
7016 // LR operator^(L, R);
7017 // LR operator|(L, R);
7018 // L operator<<(L, R);
7019 // L operator>>(L, R);
7020 //
7021 // where LR is the result of the usual arithmetic conversions
7022 // between types L and R.
7023 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007024 if (!HasArithmeticOrEnumeralCandidateType)
7025 return;
7026
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007027 for (unsigned Left = FirstPromotedIntegralType;
7028 Left < LastPromotedIntegralType; ++Left) {
7029 for (unsigned Right = FirstPromotedIntegralType;
7030 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007031 QualType LandR[2] = { getArithmeticType(Left),
7032 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007033 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7034 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007035 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007036 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7037 }
7038 }
7039 }
7040
7041 // C++ [over.built]p20:
7042 //
7043 // For every pair (T, VQ), where T is an enumeration or
7044 // pointer to member type and VQ is either volatile or
7045 // empty, there exist candidate operator functions of the form
7046 //
7047 // VQ T& operator=(VQ T&, T);
7048 void addAssignmentMemberPointerOrEnumeralOverloads() {
7049 /// Set of (canonical) types that we've already handled.
7050 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7051
7052 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7053 for (BuiltinCandidateTypeSet::iterator
7054 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7055 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7056 Enum != EnumEnd; ++Enum) {
7057 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7058 continue;
7059
7060 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7061 CandidateSet);
7062 }
7063
7064 for (BuiltinCandidateTypeSet::iterator
7065 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7066 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7067 MemPtr != MemPtrEnd; ++MemPtr) {
7068 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7069 continue;
7070
7071 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7072 CandidateSet);
7073 }
7074 }
7075 }
7076
7077 // C++ [over.built]p19:
7078 //
7079 // For every pair (T, VQ), where T is any type and VQ is either
7080 // volatile or empty, there exist candidate operator functions
7081 // of the form
7082 //
7083 // T*VQ& operator=(T*VQ&, T*);
7084 //
7085 // C++ [over.built]p21:
7086 //
7087 // For every pair (T, VQ), where T is a cv-qualified or
7088 // cv-unqualified object type and VQ is either volatile or
7089 // empty, there exist candidate operator functions of the form
7090 //
7091 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7092 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7093 void addAssignmentPointerOverloads(bool isEqualOp) {
7094 /// Set of (canonical) types that we've already handled.
7095 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7096
7097 for (BuiltinCandidateTypeSet::iterator
7098 Ptr = CandidateTypes[0].pointer_begin(),
7099 PtrEnd = CandidateTypes[0].pointer_end();
7100 Ptr != PtrEnd; ++Ptr) {
7101 // If this is operator=, keep track of the builtin candidates we added.
7102 if (isEqualOp)
7103 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007104 else if (!(*Ptr)->getPointeeType()->isObjectType())
7105 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007106
7107 // non-volatile version
7108 QualType ParamTypes[2] = {
7109 S.Context.getLValueReferenceType(*Ptr),
7110 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7111 };
7112 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7113 /*IsAssigmentOperator=*/ isEqualOp);
7114
Douglas Gregor5bee2582012-06-04 00:15:09 +00007115 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7116 VisibleTypeConversionsQuals.hasVolatile();
7117 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007118 // volatile version
7119 ParamTypes[0] =
7120 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7121 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7122 /*IsAssigmentOperator=*/isEqualOp);
7123 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007124
7125 if (!(*Ptr).isRestrictQualified() &&
7126 VisibleTypeConversionsQuals.hasRestrict()) {
7127 // restrict version
7128 ParamTypes[0]
7129 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7130 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7131 /*IsAssigmentOperator=*/isEqualOp);
7132
7133 if (NeedVolatile) {
7134 // volatile restrict version
7135 ParamTypes[0]
7136 = S.Context.getLValueReferenceType(
7137 S.Context.getCVRQualifiedType(*Ptr,
7138 (Qualifiers::Volatile |
7139 Qualifiers::Restrict)));
7140 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7141 CandidateSet,
7142 /*IsAssigmentOperator=*/isEqualOp);
7143 }
7144 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007145 }
7146
7147 if (isEqualOp) {
7148 for (BuiltinCandidateTypeSet::iterator
7149 Ptr = CandidateTypes[1].pointer_begin(),
7150 PtrEnd = CandidateTypes[1].pointer_end();
7151 Ptr != PtrEnd; ++Ptr) {
7152 // Make sure we don't add the same candidate twice.
7153 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7154 continue;
7155
Chandler Carruth8e543b32010-12-12 08:17:55 +00007156 QualType ParamTypes[2] = {
7157 S.Context.getLValueReferenceType(*Ptr),
7158 *Ptr,
7159 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007160
7161 // non-volatile version
7162 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7163 /*IsAssigmentOperator=*/true);
7164
Douglas Gregor5bee2582012-06-04 00:15:09 +00007165 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7166 VisibleTypeConversionsQuals.hasVolatile();
7167 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007168 // volatile version
7169 ParamTypes[0] =
7170 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00007171 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7172 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007173 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007174
7175 if (!(*Ptr).isRestrictQualified() &&
7176 VisibleTypeConversionsQuals.hasRestrict()) {
7177 // restrict version
7178 ParamTypes[0]
7179 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7180 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7181 CandidateSet, /*IsAssigmentOperator=*/true);
7182
7183 if (NeedVolatile) {
7184 // volatile restrict version
7185 ParamTypes[0]
7186 = S.Context.getLValueReferenceType(
7187 S.Context.getCVRQualifiedType(*Ptr,
7188 (Qualifiers::Volatile |
7189 Qualifiers::Restrict)));
7190 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7191 CandidateSet, /*IsAssigmentOperator=*/true);
7192
7193 }
7194 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007195 }
7196 }
7197 }
7198
7199 // C++ [over.built]p18:
7200 //
7201 // For every triple (L, VQ, R), where L is an arithmetic type,
7202 // VQ is either volatile or empty, and R is a promoted
7203 // arithmetic type, there exist candidate operator functions of
7204 // the form
7205 //
7206 // VQ L& operator=(VQ L&, R);
7207 // VQ L& operator*=(VQ L&, R);
7208 // VQ L& operator/=(VQ L&, R);
7209 // VQ L& operator+=(VQ L&, R);
7210 // VQ L& operator-=(VQ L&, R);
7211 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007212 if (!HasArithmeticOrEnumeralCandidateType)
7213 return;
7214
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007215 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7216 for (unsigned Right = FirstPromotedArithmeticType;
7217 Right < LastPromotedArithmeticType; ++Right) {
7218 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007219 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007220
7221 // Add this built-in operator as a candidate (VQ is empty).
7222 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007223 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007224 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7225 /*IsAssigmentOperator=*/isEqualOp);
7226
7227 // Add this built-in operator as a candidate (VQ is 'volatile').
7228 if (VisibleTypeConversionsQuals.hasVolatile()) {
7229 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007230 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007231 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007232 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7233 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007234 /*IsAssigmentOperator=*/isEqualOp);
7235 }
7236 }
7237 }
7238
7239 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7240 for (BuiltinCandidateTypeSet::iterator
7241 Vec1 = CandidateTypes[0].vector_begin(),
7242 Vec1End = CandidateTypes[0].vector_end();
7243 Vec1 != Vec1End; ++Vec1) {
7244 for (BuiltinCandidateTypeSet::iterator
7245 Vec2 = CandidateTypes[1].vector_begin(),
7246 Vec2End = CandidateTypes[1].vector_end();
7247 Vec2 != Vec2End; ++Vec2) {
7248 QualType ParamTypes[2];
7249 ParamTypes[1] = *Vec2;
7250 // Add this built-in operator as a candidate (VQ is empty).
7251 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7252 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7253 /*IsAssigmentOperator=*/isEqualOp);
7254
7255 // Add this built-in operator as a candidate (VQ is 'volatile').
7256 if (VisibleTypeConversionsQuals.hasVolatile()) {
7257 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7258 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007259 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7260 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007261 /*IsAssigmentOperator=*/isEqualOp);
7262 }
7263 }
7264 }
7265 }
7266
7267 // C++ [over.built]p22:
7268 //
7269 // For every triple (L, VQ, R), where L is an integral type, VQ
7270 // is either volatile or empty, and R is a promoted integral
7271 // type, there exist candidate operator functions of the form
7272 //
7273 // VQ L& operator%=(VQ L&, R);
7274 // VQ L& operator<<=(VQ L&, R);
7275 // VQ L& operator>>=(VQ L&, R);
7276 // VQ L& operator&=(VQ L&, R);
7277 // VQ L& operator^=(VQ L&, R);
7278 // VQ L& operator|=(VQ L&, R);
7279 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007280 if (!HasArithmeticOrEnumeralCandidateType)
7281 return;
7282
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007283 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7284 for (unsigned Right = FirstPromotedIntegralType;
7285 Right < LastPromotedIntegralType; ++Right) {
7286 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007287 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007288
7289 // Add this built-in operator as a candidate (VQ is empty).
7290 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007291 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007292 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7293 if (VisibleTypeConversionsQuals.hasVolatile()) {
7294 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007295 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007296 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7297 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7298 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7299 CandidateSet);
7300 }
7301 }
7302 }
7303 }
7304
7305 // C++ [over.operator]p23:
7306 //
7307 // There also exist candidate operator functions of the form
7308 //
7309 // bool operator!(bool);
7310 // bool operator&&(bool, bool);
7311 // bool operator||(bool, bool);
7312 void addExclaimOverload() {
7313 QualType ParamTy = S.Context.BoolTy;
7314 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7315 /*IsAssignmentOperator=*/false,
7316 /*NumContextualBoolArguments=*/1);
7317 }
7318 void addAmpAmpOrPipePipeOverload() {
7319 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7320 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7321 /*IsAssignmentOperator=*/false,
7322 /*NumContextualBoolArguments=*/2);
7323 }
7324
7325 // C++ [over.built]p13:
7326 //
7327 // For every cv-qualified or cv-unqualified object type T there
7328 // exist candidate operator functions of the form
7329 //
7330 // T* operator+(T*, ptrdiff_t); [ABOVE]
7331 // T& operator[](T*, ptrdiff_t);
7332 // T* operator-(T*, ptrdiff_t); [ABOVE]
7333 // T* operator+(ptrdiff_t, T*); [ABOVE]
7334 // T& operator[](ptrdiff_t, T*);
7335 void addSubscriptOverloads() {
7336 for (BuiltinCandidateTypeSet::iterator
7337 Ptr = CandidateTypes[0].pointer_begin(),
7338 PtrEnd = CandidateTypes[0].pointer_end();
7339 Ptr != PtrEnd; ++Ptr) {
7340 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7341 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007342 if (!PointeeType->isObjectType())
7343 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007344
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007345 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7346
7347 // T& operator[](T*, ptrdiff_t)
7348 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7349 }
7350
7351 for (BuiltinCandidateTypeSet::iterator
7352 Ptr = CandidateTypes[1].pointer_begin(),
7353 PtrEnd = CandidateTypes[1].pointer_end();
7354 Ptr != PtrEnd; ++Ptr) {
7355 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7356 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007357 if (!PointeeType->isObjectType())
7358 continue;
7359
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007360 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7361
7362 // T& operator[](ptrdiff_t, T*)
7363 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7364 }
7365 }
7366
7367 // C++ [over.built]p11:
7368 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7369 // C1 is the same type as C2 or is a derived class of C2, T is an object
7370 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7371 // there exist candidate operator functions of the form
7372 //
7373 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7374 //
7375 // where CV12 is the union of CV1 and CV2.
7376 void addArrowStarOverloads() {
7377 for (BuiltinCandidateTypeSet::iterator
7378 Ptr = CandidateTypes[0].pointer_begin(),
7379 PtrEnd = CandidateTypes[0].pointer_end();
7380 Ptr != PtrEnd; ++Ptr) {
7381 QualType C1Ty = (*Ptr);
7382 QualType C1;
7383 QualifierCollector Q1;
7384 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7385 if (!isa<RecordType>(C1))
7386 continue;
7387 // heuristic to reduce number of builtin candidates in the set.
7388 // Add volatile/restrict version only if there are conversions to a
7389 // volatile/restrict type.
7390 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7391 continue;
7392 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7393 continue;
7394 for (BuiltinCandidateTypeSet::iterator
7395 MemPtr = CandidateTypes[1].member_pointer_begin(),
7396 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7397 MemPtr != MemPtrEnd; ++MemPtr) {
7398 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7399 QualType C2 = QualType(mptr->getClass(), 0);
7400 C2 = C2.getUnqualifiedType();
7401 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7402 break;
7403 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7404 // build CV12 T&
7405 QualType T = mptr->getPointeeType();
7406 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7407 T.isVolatileQualified())
7408 continue;
7409 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7410 T.isRestrictQualified())
7411 continue;
7412 T = Q1.apply(S.Context, T);
7413 QualType ResultTy = S.Context.getLValueReferenceType(T);
7414 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7415 }
7416 }
7417 }
7418
7419 // Note that we don't consider the first argument, since it has been
7420 // contextually converted to bool long ago. The candidates below are
7421 // therefore added as binary.
7422 //
7423 // C++ [over.built]p25:
7424 // For every type T, where T is a pointer, pointer-to-member, or scoped
7425 // enumeration type, there exist candidate operator functions of the form
7426 //
7427 // T operator?(bool, T, T);
7428 //
7429 void addConditionalOperatorOverloads() {
7430 /// Set of (canonical) types that we've already handled.
7431 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7432
7433 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7434 for (BuiltinCandidateTypeSet::iterator
7435 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7436 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7437 Ptr != PtrEnd; ++Ptr) {
7438 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7439 continue;
7440
7441 QualType ParamTypes[2] = { *Ptr, *Ptr };
7442 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7443 }
7444
7445 for (BuiltinCandidateTypeSet::iterator
7446 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7447 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7448 MemPtr != MemPtrEnd; ++MemPtr) {
7449 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7450 continue;
7451
7452 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7453 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7454 }
7455
David Blaikiebbafb8a2012-03-11 07:00:24 +00007456 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007457 for (BuiltinCandidateTypeSet::iterator
7458 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7459 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7460 Enum != EnumEnd; ++Enum) {
7461 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7462 continue;
7463
7464 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7465 continue;
7466
7467 QualType ParamTypes[2] = { *Enum, *Enum };
7468 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7469 }
7470 }
7471 }
7472 }
7473};
7474
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007475} // end anonymous namespace
7476
7477/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7478/// operator overloads to the candidate set (C++ [over.built]), based
7479/// on the operator @p Op and the arguments given. For example, if the
7480/// operator is a binary '+', this routine might add "int
7481/// operator+(int, int)" to cover integer addition.
7482void
7483Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7484 SourceLocation OpLoc,
7485 Expr **Args, unsigned NumArgs,
7486 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007487 // Find all of the types that the arguments can convert to, but only
7488 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007489 // that make use of these types. Also record whether we encounter non-record
7490 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007491 Qualifiers VisibleTypeConversionsQuals;
7492 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007493 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7494 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007495
7496 bool HasNonRecordCandidateType = false;
7497 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007498 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007499 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7500 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7501 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7502 OpLoc,
7503 true,
7504 (Op == OO_Exclaim ||
7505 Op == OO_AmpAmp ||
7506 Op == OO_PipePipe),
7507 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007508 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7509 CandidateTypes[ArgIdx].hasNonRecordTypes();
7510 HasArithmeticOrEnumeralCandidateType =
7511 HasArithmeticOrEnumeralCandidateType ||
7512 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007513 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007514
Chandler Carruth00a38332010-12-13 01:44:01 +00007515 // Exit early when no non-record types have been added to the candidate set
7516 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007517 //
7518 // We can't exit early for !, ||, or &&, since there we have always have
7519 // 'bool' overloads.
7520 if (!HasNonRecordCandidateType &&
7521 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007522 return;
7523
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007524 // Setup an object to manage the common state for building overloads.
7525 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7526 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007527 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007528 CandidateTypes, CandidateSet);
7529
7530 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007531 switch (Op) {
7532 case OO_None:
7533 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007534 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007535
Chandler Carruth5184de02010-12-12 08:51:33 +00007536 case OO_New:
7537 case OO_Delete:
7538 case OO_Array_New:
7539 case OO_Array_Delete:
7540 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007541 llvm_unreachable(
7542 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007543
7544 case OO_Comma:
7545 case OO_Arrow:
7546 // C++ [over.match.oper]p3:
7547 // -- For the operator ',', the unary operator '&', or the
7548 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007549 break;
7550
7551 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007552 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007553 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007554 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007555
7556 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00007557 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007558 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007559 } else {
7560 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7561 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7562 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007563 break;
7564
Chandler Carruth5184de02010-12-12 08:51:33 +00007565 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00007566 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007567 OpBuilder.addUnaryStarPointerOverloads();
7568 else
7569 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7570 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007571
Chandler Carruth5184de02010-12-12 08:51:33 +00007572 case OO_Slash:
7573 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007574 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007575
7576 case OO_PlusPlus:
7577 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007578 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7579 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007580 break;
7581
Douglas Gregor84605ae2009-08-24 13:43:27 +00007582 case OO_EqualEqual:
7583 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007584 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007585 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007586
Douglas Gregora11693b2008-11-12 17:17:38 +00007587 case OO_Less:
7588 case OO_Greater:
7589 case OO_LessEqual:
7590 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007591 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007592 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7593 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007594
Douglas Gregora11693b2008-11-12 17:17:38 +00007595 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007596 case OO_Caret:
7597 case OO_Pipe:
7598 case OO_LessLess:
7599 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007600 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007601 break;
7602
Chandler Carruth5184de02010-12-12 08:51:33 +00007603 case OO_Amp: // '&' is either unary or binary
7604 if (NumArgs == 1)
7605 // C++ [over.match.oper]p3:
7606 // -- For the operator ',', the unary operator '&', or the
7607 // operator '->', the built-in candidates set is empty.
7608 break;
7609
7610 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7611 break;
7612
7613 case OO_Tilde:
7614 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7615 break;
7616
Douglas Gregora11693b2008-11-12 17:17:38 +00007617 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007618 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007619 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00007620
7621 case OO_PlusEqual:
7622 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007623 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007624 // Fall through.
7625
7626 case OO_StarEqual:
7627 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007628 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00007629 break;
7630
7631 case OO_PercentEqual:
7632 case OO_LessLessEqual:
7633 case OO_GreaterGreaterEqual:
7634 case OO_AmpEqual:
7635 case OO_CaretEqual:
7636 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007637 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007638 break;
7639
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007640 case OO_Exclaim:
7641 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00007642 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007643
Douglas Gregora11693b2008-11-12 17:17:38 +00007644 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007645 case OO_PipePipe:
7646 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00007647 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007648
7649 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007650 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007651 break;
7652
7653 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007654 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00007655 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00007656
7657 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007658 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007659 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7660 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007661 }
7662}
7663
Douglas Gregore254f902009-02-04 00:32:51 +00007664/// \brief Add function candidates found via argument-dependent lookup
7665/// to the set of overloading candidates.
7666///
7667/// This routine performs argument-dependent name lookup based on the
7668/// given function name (which may also be an operator name) and adds
7669/// all of the overload candidates found by ADL to the overload
7670/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00007671void
Douglas Gregore254f902009-02-04 00:32:51 +00007672Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00007673 bool Operator, SourceLocation Loc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007674 llvm::ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007675 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007676 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00007677 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00007678 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00007679
John McCall91f61fc2010-01-26 06:04:06 +00007680 // FIXME: This approach for uniquing ADL results (and removing
7681 // redundant candidates from the set) relies on pointer-equality,
7682 // which means we need to key off the canonical decl. However,
7683 // always going back to the canonical decl might not get us the
7684 // right set of default arguments. What default arguments are
7685 // we supposed to consider on ADL candidates, anyway?
7686
Douglas Gregorcabea402009-09-22 15:41:20 +00007687 // FIXME: Pass in the explicit template arguments?
Richard Smithb6626742012-10-18 17:56:02 +00007688 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00007689
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007690 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007691 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7692 CandEnd = CandidateSet.end();
7693 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00007694 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00007695 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00007696 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00007697 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00007698 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00007699
7700 // For each of the ADL candidates we found, add it to the overload
7701 // set.
John McCall8fe68082010-01-26 07:16:45 +00007702 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00007703 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00007704 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00007705 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00007706 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007707
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007708 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7709 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007710 } else
John McCall4c4c1df2010-01-26 03:27:55 +00007711 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00007712 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007713 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00007714 }
Douglas Gregore254f902009-02-04 00:32:51 +00007715}
7716
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007717/// isBetterOverloadCandidate - Determines whether the first overload
7718/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00007719bool
John McCall5c32be02010-08-24 20:38:10 +00007720isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007721 const OverloadCandidate &Cand1,
7722 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007723 SourceLocation Loc,
7724 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007725 // Define viable functions to be better candidates than non-viable
7726 // functions.
7727 if (!Cand2.Viable)
7728 return Cand1.Viable;
7729 else if (!Cand1.Viable)
7730 return false;
7731
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007732 // C++ [over.match.best]p1:
7733 //
7734 // -- if F is a static member function, ICS1(F) is defined such
7735 // that ICS1(F) is neither better nor worse than ICS1(G) for
7736 // any function G, and, symmetrically, ICS1(G) is neither
7737 // better nor worse than ICS1(F).
7738 unsigned StartArg = 0;
7739 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7740 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007741
Douglas Gregord3cb3562009-07-07 23:38:56 +00007742 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007743 // A viable function F1 is defined to be a better function than another
7744 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007745 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007746 unsigned NumArgs = Cand1.NumConversions;
7747 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007748 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007749 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007750 switch (CompareImplicitConversionSequences(S,
7751 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007752 Cand2.Conversions[ArgIdx])) {
7753 case ImplicitConversionSequence::Better:
7754 // Cand1 has a better conversion sequence.
7755 HasBetterConversion = true;
7756 break;
7757
7758 case ImplicitConversionSequence::Worse:
7759 // Cand1 can't be better than Cand2.
7760 return false;
7761
7762 case ImplicitConversionSequence::Indistinguishable:
7763 // Do nothing.
7764 break;
7765 }
7766 }
7767
Mike Stump11289f42009-09-09 15:08:12 +00007768 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007769 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007770 if (HasBetterConversion)
7771 return true;
7772
Mike Stump11289f42009-09-09 15:08:12 +00007773 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007774 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007775 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007776 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7777 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007778
7779 // -- F1 and F2 are function template specializations, and the function
7780 // template for F1 is more specialized than the template for F2
7781 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007782 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007783 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007784 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007785 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007786 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7787 Cand2.Function->getPrimaryTemplate(),
7788 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007789 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007790 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007791 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007792 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007793 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007794
Douglas Gregora1f013e2008-11-07 22:36:19 +00007795 // -- the context is an initialization by user-defined conversion
7796 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7797 // from the return type of F1 to the destination type (i.e.,
7798 // the type of the entity being initialized) is a better
7799 // conversion sequence than the standard conversion sequence
7800 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007801 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007802 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007803 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00007804 // First check whether we prefer one of the conversion functions over the
7805 // other. This only distinguishes the results in non-standard, extension
7806 // cases such as the conversion from a lambda closure type to a function
7807 // pointer or block.
7808 ImplicitConversionSequence::CompareKind FuncResult
7809 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7810 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7811 return FuncResult;
7812
John McCall5c32be02010-08-24 20:38:10 +00007813 switch (CompareStandardConversionSequences(S,
7814 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007815 Cand2.FinalConversion)) {
7816 case ImplicitConversionSequence::Better:
7817 // Cand1 has a better conversion sequence.
7818 return true;
7819
7820 case ImplicitConversionSequence::Worse:
7821 // Cand1 can't be better than Cand2.
7822 return false;
7823
7824 case ImplicitConversionSequence::Indistinguishable:
7825 // Do nothing
7826 break;
7827 }
7828 }
7829
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007830 return false;
7831}
7832
Mike Stump11289f42009-09-09 15:08:12 +00007833/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007834/// within an overload candidate set.
7835///
James Dennettffad8b72012-06-22 08:10:18 +00007836/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007837/// which overload resolution occurs.
7838///
James Dennettffad8b72012-06-22 08:10:18 +00007839/// \param Best If overload resolution was successful or found a deleted
7840/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007841///
7842/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007843OverloadingResult
7844OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007845 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007846 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007847 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007848 Best = end();
7849 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7850 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007851 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007852 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007853 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007854 }
7855
7856 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007857 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007858 return OR_No_Viable_Function;
7859
7860 // Make sure that this function is better than every other viable
7861 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007862 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007863 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007864 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007865 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007866 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007867 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007868 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007869 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007870 }
Mike Stump11289f42009-09-09 15:08:12 +00007871
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007872 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007873 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007874 (Best->Function->isDeleted() ||
7875 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007876 return OR_Deleted;
7877
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007878 return OR_Success;
7879}
7880
John McCall53262c92010-01-12 02:15:36 +00007881namespace {
7882
7883enum OverloadCandidateKind {
7884 oc_function,
7885 oc_method,
7886 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007887 oc_function_template,
7888 oc_method_template,
7889 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007890 oc_implicit_default_constructor,
7891 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007892 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007893 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007894 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007895 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007896};
7897
John McCalle1ac8d12010-01-13 00:25:19 +00007898OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7899 FunctionDecl *Fn,
7900 std::string &Description) {
7901 bool isTemplate = false;
7902
7903 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7904 isTemplate = true;
7905 Description = S.getTemplateArgumentBindingsText(
7906 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7907 }
John McCallfd0b2f82010-01-06 09:43:14 +00007908
7909 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007910 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007911 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007912
Sebastian Redl08905022011-02-05 19:23:19 +00007913 if (Ctor->getInheritedConstructor())
7914 return oc_implicit_inherited_constructor;
7915
Alexis Hunt119c10e2011-05-25 23:16:36 +00007916 if (Ctor->isDefaultConstructor())
7917 return oc_implicit_default_constructor;
7918
7919 if (Ctor->isMoveConstructor())
7920 return oc_implicit_move_constructor;
7921
7922 assert(Ctor->isCopyConstructor() &&
7923 "unexpected sort of implicit constructor");
7924 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007925 }
7926
7927 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7928 // This actually gets spelled 'candidate function' for now, but
7929 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007930 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007931 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007932
Alexis Hunt119c10e2011-05-25 23:16:36 +00007933 if (Meth->isMoveAssignmentOperator())
7934 return oc_implicit_move_assignment;
7935
Douglas Gregor12695102012-02-10 08:36:38 +00007936 if (Meth->isCopyAssignmentOperator())
7937 return oc_implicit_copy_assignment;
7938
7939 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7940 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00007941 }
7942
John McCalle1ac8d12010-01-13 00:25:19 +00007943 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007944}
7945
Sebastian Redl08905022011-02-05 19:23:19 +00007946void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7947 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7948 if (!Ctor) return;
7949
7950 Ctor = Ctor->getInheritedConstructor();
7951 if (!Ctor) return;
7952
7953 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7954}
7955
John McCall53262c92010-01-12 02:15:36 +00007956} // end anonymous namespace
7957
7958// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007959void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007960 std::string FnDesc;
7961 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007962 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7963 << (unsigned) K << FnDesc;
7964 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7965 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007966 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007967}
7968
Douglas Gregorb491ed32011-02-19 21:32:49 +00007969//Notes the location of all overload candidates designated through
7970// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007971void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007972 assert(OverloadedExpr->getType() == Context.OverloadTy);
7973
7974 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7975 OverloadExpr *OvlExpr = Ovl.Expression;
7976
7977 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7978 IEnd = OvlExpr->decls_end();
7979 I != IEnd; ++I) {
7980 if (FunctionTemplateDecl *FunTmpl =
7981 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007982 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007983 } else if (FunctionDecl *Fun
7984 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007985 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007986 }
7987 }
7988}
7989
John McCall0d1da222010-01-12 00:44:57 +00007990/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7991/// "lead" diagnostic; it will be given two arguments, the source and
7992/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007993void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7994 Sema &S,
7995 SourceLocation CaretLoc,
7996 const PartialDiagnostic &PDiag) const {
7997 S.Diag(CaretLoc, PDiag)
7998 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00007999 // FIXME: The note limiting machinery is borrowed from
8000 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8001 // refactoring here.
8002 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8003 unsigned CandsShown = 0;
8004 AmbiguousConversionSequence::const_iterator I, E;
8005 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8006 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8007 break;
8008 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008009 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008010 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008011 if (I != E)
8012 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008013}
8014
John McCall0d1da222010-01-12 00:44:57 +00008015namespace {
8016
John McCall6a61b522010-01-13 09:16:55 +00008017void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8018 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8019 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008020 assert(Cand->Function && "for now, candidate must be a function");
8021 FunctionDecl *Fn = Cand->Function;
8022
8023 // There's a conversion slot for the object argument if this is a
8024 // non-constructor method. Note that 'I' corresponds the
8025 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008026 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008027 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008028 if (I == 0)
8029 isObjectArgument = true;
8030 else
8031 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008032 }
8033
John McCalle1ac8d12010-01-13 00:25:19 +00008034 std::string FnDesc;
8035 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8036
John McCall6a61b522010-01-13 09:16:55 +00008037 Expr *FromExpr = Conv.Bad.FromExpr;
8038 QualType FromTy = Conv.Bad.getFromType();
8039 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008040
John McCallfb7ad0f2010-02-02 02:42:52 +00008041 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008042 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008043 Expr *E = FromExpr->IgnoreParens();
8044 if (isa<UnaryOperator>(E))
8045 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008046 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008047
8048 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8049 << (unsigned) FnKind << FnDesc
8050 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8051 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008052 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008053 return;
8054 }
8055
John McCall6d174642010-01-23 08:10:49 +00008056 // Do some hand-waving analysis to see if the non-viability is due
8057 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008058 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8059 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8060 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8061 CToTy = RT->getPointeeType();
8062 else {
8063 // TODO: detect and diagnose the full richness of const mismatches.
8064 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8065 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8066 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8067 }
8068
8069 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8070 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008071 Qualifiers FromQs = CFromTy.getQualifiers();
8072 Qualifiers ToQs = CToTy.getQualifiers();
8073
8074 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8075 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8076 << (unsigned) FnKind << FnDesc
8077 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8078 << FromTy
8079 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8080 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008081 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008082 return;
8083 }
8084
John McCall31168b02011-06-15 23:02:42 +00008085 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008086 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008087 << (unsigned) FnKind << FnDesc
8088 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8089 << FromTy
8090 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8091 << (unsigned) isObjectArgument << I+1;
8092 MaybeEmitInheritedConstructorNote(S, Fn);
8093 return;
8094 }
8095
Douglas Gregoraec25842011-04-26 23:16:46 +00008096 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8097 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8098 << (unsigned) FnKind << FnDesc
8099 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8100 << FromTy
8101 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8102 << (unsigned) isObjectArgument << I+1;
8103 MaybeEmitInheritedConstructorNote(S, Fn);
8104 return;
8105 }
8106
John McCall47000992010-01-14 03:28:57 +00008107 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8108 assert(CVR && "unexpected qualifiers mismatch");
8109
8110 if (isObjectArgument) {
8111 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8112 << (unsigned) FnKind << FnDesc
8113 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8114 << FromTy << (CVR - 1);
8115 } else {
8116 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8117 << (unsigned) FnKind << FnDesc
8118 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8119 << FromTy << (CVR - 1) << I+1;
8120 }
Sebastian Redl08905022011-02-05 19:23:19 +00008121 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008122 return;
8123 }
8124
Sebastian Redla72462c2011-09-24 17:48:32 +00008125 // Special diagnostic for failure to convert an initializer list, since
8126 // telling the user that it has type void is not useful.
8127 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8128 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8129 << (unsigned) FnKind << FnDesc
8130 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8131 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8132 MaybeEmitInheritedConstructorNote(S, Fn);
8133 return;
8134 }
8135
John McCall6d174642010-01-23 08:10:49 +00008136 // Diagnose references or pointers to incomplete types differently,
8137 // since it's far from impossible that the incompleteness triggered
8138 // the failure.
8139 QualType TempFromTy = FromTy.getNonReferenceType();
8140 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8141 TempFromTy = PTy->getPointeeType();
8142 if (TempFromTy->isIncompleteType()) {
8143 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8144 << (unsigned) FnKind << FnDesc
8145 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8146 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008147 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008148 return;
8149 }
8150
Douglas Gregor56f2e342010-06-30 23:01:39 +00008151 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008152 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008153 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8154 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8155 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8156 FromPtrTy->getPointeeType()) &&
8157 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8158 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008159 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008160 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008161 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008162 }
8163 } else if (const ObjCObjectPointerType *FromPtrTy
8164 = FromTy->getAs<ObjCObjectPointerType>()) {
8165 if (const ObjCObjectPointerType *ToPtrTy
8166 = ToTy->getAs<ObjCObjectPointerType>())
8167 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8168 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8169 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8170 FromPtrTy->getPointeeType()) &&
8171 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008172 BaseToDerivedConversion = 2;
8173 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008174 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8175 !FromTy->isIncompleteType() &&
8176 !ToRefTy->getPointeeType()->isIncompleteType() &&
8177 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8178 BaseToDerivedConversion = 3;
8179 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8180 ToTy.getNonReferenceType().getCanonicalType() ==
8181 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008182 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8183 << (unsigned) FnKind << FnDesc
8184 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8185 << (unsigned) isObjectArgument << I + 1;
8186 MaybeEmitInheritedConstructorNote(S, Fn);
8187 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008188 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008189 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008190
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008191 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008192 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008193 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008194 << (unsigned) FnKind << FnDesc
8195 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008196 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008197 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008198 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008199 return;
8200 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008201
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008202 if (isa<ObjCObjectPointerType>(CFromTy) &&
8203 isa<PointerType>(CToTy)) {
8204 Qualifiers FromQs = CFromTy.getQualifiers();
8205 Qualifiers ToQs = CToTy.getQualifiers();
8206 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8207 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8208 << (unsigned) FnKind << FnDesc
8209 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8210 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8211 MaybeEmitInheritedConstructorNote(S, Fn);
8212 return;
8213 }
8214 }
8215
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008216 // Emit the generic diagnostic and, optionally, add the hints to it.
8217 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8218 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008219 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008220 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8221 << (unsigned) (Cand->Fix.Kind);
8222
8223 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008224 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8225 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008226 FDiag << *HI;
8227 S.Diag(Fn->getLocation(), FDiag);
8228
Sebastian Redl08905022011-02-05 19:23:19 +00008229 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008230}
8231
8232void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8233 unsigned NumFormalArgs) {
8234 // TODO: treat calls to a missing default constructor as a special case
8235
8236 FunctionDecl *Fn = Cand->Function;
8237 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8238
8239 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008240
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008241 // With invalid overloaded operators, it's possible that we think we
8242 // have an arity mismatch when it fact it looks like we have the
8243 // right number of arguments, because only overloaded operators have
8244 // the weird behavior of overloading member and non-member functions.
8245 // Just don't report anything.
8246 if (Fn->isInvalidDecl() &&
8247 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8248 return;
8249
John McCall6a61b522010-01-13 09:16:55 +00008250 // at least / at most / exactly
8251 unsigned mode, modeCount;
8252 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008253 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8254 (Cand->FailureKind == ovl_fail_bad_deduction &&
8255 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008256 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00008257 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008258 mode = 0; // "at least"
8259 else
8260 mode = 2; // "exactly"
8261 modeCount = MinParams;
8262 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00008263 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8264 (Cand->FailureKind == ovl_fail_bad_deduction &&
8265 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00008266 if (MinParams != FnTy->getNumArgs())
8267 mode = 1; // "at most"
8268 else
8269 mode = 2; // "exactly"
8270 modeCount = FnTy->getNumArgs();
8271 }
8272
8273 std::string Description;
8274 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8275
Richard Smith10ff50d2012-05-11 05:16:41 +00008276 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8277 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8278 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8279 << Fn->getParamDecl(0) << NumFormalArgs;
8280 else
8281 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8282 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8283 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008284 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008285}
8286
John McCall8b9ed552010-02-01 18:53:26 +00008287/// Diagnose a failed template-argument deduction.
8288void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008289 unsigned NumArgs) {
John McCall8b9ed552010-02-01 18:53:26 +00008290 FunctionDecl *Fn = Cand->Function; // pattern
8291
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008292 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008293 NamedDecl *ParamD;
8294 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8295 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8296 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00008297 switch (Cand->DeductionFailure.Result) {
8298 case Sema::TDK_Success:
8299 llvm_unreachable("TDK_success while diagnosing bad deduction");
8300
8301 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008302 assert(ParamD && "no parameter found for incomplete deduction result");
8303 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8304 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00008305 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008306 return;
8307 }
8308
John McCall42d7d192010-08-05 09:05:08 +00008309 case Sema::TDK_Underqualified: {
8310 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8311 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8312
8313 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8314
8315 // Param will have been canonicalized, but it should just be a
8316 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008317 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008318 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008319 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008320 assert(S.Context.hasSameType(Param, NonCanonParam));
8321
8322 // Arg has also been canonicalized, but there's nothing we can do
8323 // about that. It also doesn't matter as much, because it won't
8324 // have any template parameters in it (because deduction isn't
8325 // done on dependent types).
8326 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8327
8328 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8329 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00008330 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00008331 return;
8332 }
8333
8334 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008335 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008336 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008337 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008338 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008339 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008340 which = 1;
8341 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008342 which = 2;
8343 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008344
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008345 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008346 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008347 << *Cand->DeductionFailure.getFirstArg()
8348 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00008349 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008350 return;
8351 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008352
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008353 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008354 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008355 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008356 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008357 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8358 << ParamD->getDeclName();
8359 else {
8360 int index = 0;
8361 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8362 index = TTP->getIndex();
8363 else if (NonTypeTemplateParmDecl *NTTP
8364 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8365 index = NTTP->getIndex();
8366 else
8367 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008368 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008369 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8370 << (index + 1);
8371 }
Sebastian Redl08905022011-02-05 19:23:19 +00008372 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008373 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008374
Douglas Gregor02eb4832010-05-08 18:13:28 +00008375 case Sema::TDK_TooManyArguments:
8376 case Sema::TDK_TooFewArguments:
8377 DiagnoseArityMismatch(S, Cand, NumArgs);
8378 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008379
8380 case Sema::TDK_InstantiationDepth:
8381 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00008382 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008383 return;
8384
8385 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00008386 // Format the template argument list into the argument string.
8387 llvm::SmallString<128> TemplateArgString;
8388 if (TemplateArgumentList *Args =
8389 Cand->DeductionFailure.getTemplateArgumentList()) {
8390 TemplateArgString = " ";
8391 TemplateArgString += S.getTemplateArgumentBindingsText(
8392 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8393 }
8394
Richard Smith6f8d2c62012-05-09 05:17:00 +00008395 // If this candidate was disabled by enable_if, say so.
8396 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8397 if (PDiag && PDiag->second.getDiagID() ==
8398 diag::err_typename_nested_not_found_enable_if) {
8399 // FIXME: Use the source range of the condition, and the fully-qualified
8400 // name of the enable_if template. These are both present in PDiag.
8401 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8402 << "'enable_if'" << TemplateArgString;
8403 return;
8404 }
8405
Richard Smith9ca64612012-05-07 09:03:25 +00008406 // Format the SFINAE diagnostic into the argument string.
8407 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8408 // formatted message in another diagnostic.
8409 llvm::SmallString<128> SFINAEArgString;
8410 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008411 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00008412 SFINAEArgString = ": ";
8413 R = SourceRange(PDiag->first, PDiag->first);
8414 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8415 }
8416
Douglas Gregord09efd42010-05-08 20:07:26 +00008417 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smith9ca64612012-05-07 09:03:25 +00008418 << TemplateArgString << SFINAEArgString << R;
Sebastian Redl08905022011-02-05 19:23:19 +00008419 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00008420 return;
8421 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008422
John McCall8b9ed552010-02-01 18:53:26 +00008423 // TODO: diagnose these individually, then kill off
8424 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00008425 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00008426 case Sema::TDK_FailedOverloadResolution:
8427 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00008428 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00008429 return;
8430 }
8431}
8432
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008433/// CUDA: diagnose an invalid call across targets.
8434void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8435 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8436 FunctionDecl *Callee = Cand->Function;
8437
8438 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8439 CalleeTarget = S.IdentifyCUDATarget(Callee);
8440
8441 std::string FnDesc;
8442 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8443
8444 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8445 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8446}
8447
John McCall8b9ed552010-02-01 18:53:26 +00008448/// Generates a 'note' diagnostic for an overload candidate. We've
8449/// already generated a primary error at the call site.
8450///
8451/// It really does need to be a single diagnostic with its caret
8452/// pointed at the candidate declaration. Yes, this creates some
8453/// major challenges of technical writing. Yes, this makes pointing
8454/// out problems with specific arguments quite awkward. It's still
8455/// better than generating twenty screens of text for every failed
8456/// overload.
8457///
8458/// It would be great to be able to express per-candidate problems
8459/// more richly for those diagnostic clients that cared, but we'd
8460/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00008461void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008462 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00008463 FunctionDecl *Fn = Cand->Function;
8464
John McCall12f97bc2010-01-08 04:41:39 +00008465 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008466 if (Cand->Viable && (Fn->isDeleted() ||
8467 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00008468 std::string FnDesc;
8469 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00008470
8471 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00008472 << FnKind << FnDesc
8473 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00008474 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00008475 return;
John McCall12f97bc2010-01-08 04:41:39 +00008476 }
8477
John McCalle1ac8d12010-01-13 00:25:19 +00008478 // We don't really have anything else to say about viable candidates.
8479 if (Cand->Viable) {
8480 S.NoteOverloadCandidate(Fn);
8481 return;
8482 }
John McCall0d1da222010-01-12 00:44:57 +00008483
John McCall6a61b522010-01-13 09:16:55 +00008484 switch (Cand->FailureKind) {
8485 case ovl_fail_too_many_arguments:
8486 case ovl_fail_too_few_arguments:
8487 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00008488
John McCall6a61b522010-01-13 09:16:55 +00008489 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008490 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00008491
John McCallfe796dd2010-01-23 05:17:32 +00008492 case ovl_fail_trivial_conversion:
8493 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00008494 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00008495 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008496
John McCall65eb8792010-02-25 01:37:24 +00008497 case ovl_fail_bad_conversion: {
8498 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008499 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00008500 if (Cand->Conversions[I].isBad())
8501 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008502
John McCall6a61b522010-01-13 09:16:55 +00008503 // FIXME: this currently happens when we're called from SemaInit
8504 // when user-conversion overload fails. Figure out how to handle
8505 // those conditions and diagnose them well.
8506 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008507 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008508
8509 case ovl_fail_bad_target:
8510 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00008511 }
John McCalld3224162010-01-08 00:58:21 +00008512}
8513
8514void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8515 // Desugar the type of the surrogate down to a function type,
8516 // retaining as many typedefs as possible while still showing
8517 // the function type (and, therefore, its parameter types).
8518 QualType FnType = Cand->Surrogate->getConversionType();
8519 bool isLValueReference = false;
8520 bool isRValueReference = false;
8521 bool isPointer = false;
8522 if (const LValueReferenceType *FnTypeRef =
8523 FnType->getAs<LValueReferenceType>()) {
8524 FnType = FnTypeRef->getPointeeType();
8525 isLValueReference = true;
8526 } else if (const RValueReferenceType *FnTypeRef =
8527 FnType->getAs<RValueReferenceType>()) {
8528 FnType = FnTypeRef->getPointeeType();
8529 isRValueReference = true;
8530 }
8531 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8532 FnType = FnTypePtr->getPointeeType();
8533 isPointer = true;
8534 }
8535 // Desugar down to a function type.
8536 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8537 // Reconstruct the pointer/reference as appropriate.
8538 if (isPointer) FnType = S.Context.getPointerType(FnType);
8539 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8540 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8541
8542 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8543 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00008544 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00008545}
8546
8547void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie1d202a62012-10-08 01:11:04 +00008548 StringRef Opc,
John McCalld3224162010-01-08 00:58:21 +00008549 SourceLocation OpLoc,
8550 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008551 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00008552 std::string TypeStr("operator");
8553 TypeStr += Opc;
8554 TypeStr += "(";
8555 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00008556 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00008557 TypeStr += ")";
8558 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8559 } else {
8560 TypeStr += ", ";
8561 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8562 TypeStr += ")";
8563 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8564 }
8565}
8566
8567void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8568 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00008569 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00008570 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8571 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00008572 if (ICS.isBad()) break; // all meaningless after first invalid
8573 if (!ICS.isAmbiguous()) continue;
8574
John McCall5c32be02010-08-24 20:38:10 +00008575 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008576 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00008577 }
8578}
8579
John McCall3712d9e2010-01-15 23:32:50 +00008580SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8581 if (Cand->Function)
8582 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00008583 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00008584 return Cand->Surrogate->getLocation();
8585 return SourceLocation();
8586}
8587
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008588static unsigned
8589RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00008590 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008591 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00008592 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008593
Douglas Gregorc5c01a62012-09-13 21:01:57 +00008594 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008595 case Sema::TDK_Incomplete:
8596 return 1;
8597
8598 case Sema::TDK_Underqualified:
8599 case Sema::TDK_Inconsistent:
8600 return 2;
8601
8602 case Sema::TDK_SubstitutionFailure:
8603 case Sema::TDK_NonDeducedMismatch:
8604 return 3;
8605
8606 case Sema::TDK_InstantiationDepth:
8607 case Sema::TDK_FailedOverloadResolution:
8608 return 4;
8609
8610 case Sema::TDK_InvalidExplicitArguments:
8611 return 5;
8612
8613 case Sema::TDK_TooManyArguments:
8614 case Sema::TDK_TooFewArguments:
8615 return 6;
8616 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00008617 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008618}
8619
John McCallad2587a2010-01-12 00:48:53 +00008620struct CompareOverloadCandidatesForDisplay {
8621 Sema &S;
8622 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00008623
8624 bool operator()(const OverloadCandidate *L,
8625 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00008626 // Fast-path this check.
8627 if (L == R) return false;
8628
John McCall12f97bc2010-01-08 04:41:39 +00008629 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00008630 if (L->Viable) {
8631 if (!R->Viable) return true;
8632
8633 // TODO: introduce a tri-valued comparison for overload
8634 // candidates. Would be more worthwhile if we had a sort
8635 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00008636 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8637 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00008638 } else if (R->Viable)
8639 return false;
John McCall12f97bc2010-01-08 04:41:39 +00008640
John McCall3712d9e2010-01-15 23:32:50 +00008641 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00008642
John McCall3712d9e2010-01-15 23:32:50 +00008643 // Criteria by which we can sort non-viable candidates:
8644 if (!L->Viable) {
8645 // 1. Arity mismatches come after other candidates.
8646 if (L->FailureKind == ovl_fail_too_many_arguments ||
8647 L->FailureKind == ovl_fail_too_few_arguments)
8648 return false;
8649 if (R->FailureKind == ovl_fail_too_many_arguments ||
8650 R->FailureKind == ovl_fail_too_few_arguments)
8651 return true;
John McCall12f97bc2010-01-08 04:41:39 +00008652
John McCallfe796dd2010-01-23 05:17:32 +00008653 // 2. Bad conversions come first and are ordered by the number
8654 // of bad conversions and quality of good conversions.
8655 if (L->FailureKind == ovl_fail_bad_conversion) {
8656 if (R->FailureKind != ovl_fail_bad_conversion)
8657 return true;
8658
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008659 // The conversion that can be fixed with a smaller number of changes,
8660 // comes first.
8661 unsigned numLFixes = L->Fix.NumConversionsFixed;
8662 unsigned numRFixes = R->Fix.NumConversionsFixed;
8663 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8664 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008665 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008666 if (numLFixes < numRFixes)
8667 return true;
8668 else
8669 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00008670 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008671
John McCallfe796dd2010-01-23 05:17:32 +00008672 // If there's any ordering between the defined conversions...
8673 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00008674 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00008675
8676 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00008677 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008678 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00008679 switch (CompareImplicitConversionSequences(S,
8680 L->Conversions[I],
8681 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00008682 case ImplicitConversionSequence::Better:
8683 leftBetter++;
8684 break;
8685
8686 case ImplicitConversionSequence::Worse:
8687 leftBetter--;
8688 break;
8689
8690 case ImplicitConversionSequence::Indistinguishable:
8691 break;
8692 }
8693 }
8694 if (leftBetter > 0) return true;
8695 if (leftBetter < 0) return false;
8696
8697 } else if (R->FailureKind == ovl_fail_bad_conversion)
8698 return false;
8699
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008700 if (L->FailureKind == ovl_fail_bad_deduction) {
8701 if (R->FailureKind != ovl_fail_bad_deduction)
8702 return true;
8703
8704 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8705 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00008706 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00008707 } else if (R->FailureKind == ovl_fail_bad_deduction)
8708 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00008709
John McCall3712d9e2010-01-15 23:32:50 +00008710 // TODO: others?
8711 }
8712
8713 // Sort everything else by location.
8714 SourceLocation LLoc = GetLocationForCandidate(L);
8715 SourceLocation RLoc = GetLocationForCandidate(R);
8716
8717 // Put candidates without locations (e.g. builtins) at the end.
8718 if (LLoc.isInvalid()) return false;
8719 if (RLoc.isInvalid()) return true;
8720
8721 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00008722 }
8723};
8724
John McCallfe796dd2010-01-23 05:17:32 +00008725/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008726/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00008727void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008728 llvm::ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00008729 assert(!Cand->Viable);
8730
8731 // Don't do anything on failures other than bad conversion.
8732 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8733
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008734 // We only want the FixIts if all the arguments can be corrected.
8735 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00008736 // Use a implicit copy initialization to check conversion fixes.
8737 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008738
John McCallfe796dd2010-01-23 05:17:32 +00008739 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00008740 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00008741 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00008742 while (true) {
8743 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8744 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008745 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00008746 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00008747 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008748 }
John McCallfe796dd2010-01-23 05:17:32 +00008749 }
8750
8751 if (ConvIdx == ConvCount)
8752 return;
8753
John McCall65eb8792010-02-25 01:37:24 +00008754 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8755 "remaining conversion is initialized?");
8756
Douglas Gregoradc7a702010-04-16 17:45:54 +00008757 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00008758 // operation somehow.
8759 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00008760
8761 const FunctionProtoType* Proto;
8762 unsigned ArgIdx = ConvIdx;
8763
8764 if (Cand->IsSurrogate) {
8765 QualType ConvType
8766 = Cand->Surrogate->getConversionType().getNonReferenceType();
8767 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8768 ConvType = ConvPtrType->getPointeeType();
8769 Proto = ConvType->getAs<FunctionProtoType>();
8770 ArgIdx--;
8771 } else if (Cand->Function) {
8772 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8773 if (isa<CXXMethodDecl>(Cand->Function) &&
8774 !isa<CXXConstructorDecl>(Cand->Function))
8775 ArgIdx--;
8776 } else {
8777 // Builtin binary operator with a bad first conversion.
8778 assert(ConvCount <= 3);
8779 for (; ConvIdx != ConvCount; ++ConvIdx)
8780 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008781 = TryCopyInitialization(S, Args[ConvIdx],
8782 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008783 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008784 /*InOverloadResolution*/ true,
8785 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008786 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008787 return;
8788 }
8789
8790 // Fill in the rest of the conversions.
8791 unsigned NumArgsInProto = Proto->getNumArgs();
8792 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008793 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008794 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008795 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008796 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008797 /*InOverloadResolution=*/true,
8798 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00008799 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008800 // Store the FixIt in the candidate if it exists.
8801 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008802 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008803 }
John McCallfe796dd2010-01-23 05:17:32 +00008804 else
8805 Cand->Conversions[ConvIdx].setEllipsis();
8806 }
8807}
8808
John McCalld3224162010-01-08 00:58:21 +00008809} // end anonymous namespace
8810
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008811/// PrintOverloadCandidates - When overload resolution fails, prints
8812/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008813/// set.
John McCall5c32be02010-08-24 20:38:10 +00008814void OverloadCandidateSet::NoteCandidates(Sema &S,
8815 OverloadCandidateDisplayKind OCD,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008816 llvm::ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00008817 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00008818 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008819 // Sort the candidates by viability and position. Sorting directly would
8820 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008821 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008822 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8823 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008824 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008825 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008826 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008827 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008828 if (Cand->Function || Cand->IsSurrogate)
8829 Cands.push_back(Cand);
8830 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8831 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008832 }
8833 }
8834
John McCallad2587a2010-01-12 00:48:53 +00008835 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008836 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008837
John McCall0d1da222010-01-12 00:44:57 +00008838 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008839
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008840 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00008841 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008842 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008843 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8844 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008845
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008846 // Set an arbitrary limit on the number of candidate functions we'll spam
8847 // the user with. FIXME: This limit should depend on details of the
8848 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00008849 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008850 break;
8851 }
8852 ++CandsShown;
8853
John McCalld3224162010-01-08 00:58:21 +00008854 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008855 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00008856 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008857 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008858 else {
8859 assert(Cand->Viable &&
8860 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008861 // Generally we only see ambiguities including viable builtin
8862 // operators if overload resolution got screwed up by an
8863 // ambiguous user-defined conversion.
8864 //
8865 // FIXME: It's quite possible for different conversions to see
8866 // different ambiguities, though.
8867 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008868 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008869 ReportedAmbiguousConversions = true;
8870 }
John McCalld3224162010-01-08 00:58:21 +00008871
John McCall0d1da222010-01-12 00:44:57 +00008872 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008873 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008874 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008875 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008876
8877 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008878 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008879}
8880
Douglas Gregorb491ed32011-02-19 21:32:49 +00008881// [PossiblyAFunctionType] --> [Return]
8882// NonFunctionType --> NonFunctionType
8883// R (A) --> R(A)
8884// R (*)(A) --> R (A)
8885// R (&)(A) --> R (A)
8886// R (S::*)(A) --> R (A)
8887QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8888 QualType Ret = PossiblyAFunctionType;
8889 if (const PointerType *ToTypePtr =
8890 PossiblyAFunctionType->getAs<PointerType>())
8891 Ret = ToTypePtr->getPointeeType();
8892 else if (const ReferenceType *ToTypeRef =
8893 PossiblyAFunctionType->getAs<ReferenceType>())
8894 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008895 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008896 PossiblyAFunctionType->getAs<MemberPointerType>())
8897 Ret = MemTypePtr->getPointeeType();
8898 Ret =
8899 Context.getCanonicalType(Ret).getUnqualifiedType();
8900 return Ret;
8901}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008902
Douglas Gregorb491ed32011-02-19 21:32:49 +00008903// A helper class to help with address of function resolution
8904// - allows us to avoid passing around all those ugly parameters
8905class AddressOfFunctionResolver
8906{
8907 Sema& S;
8908 Expr* SourceExpr;
8909 const QualType& TargetType;
8910 QualType TargetFunctionType; // Extracted function type from target type
8911
8912 bool Complain;
8913 //DeclAccessPair& ResultFunctionAccessPair;
8914 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008915
Douglas Gregorb491ed32011-02-19 21:32:49 +00008916 bool TargetTypeIsNonStaticMemberFunction;
8917 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008918
Douglas Gregorb491ed32011-02-19 21:32:49 +00008919 OverloadExpr::FindResult OvlExprInfo;
8920 OverloadExpr *OvlExpr;
8921 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008922 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008923
Douglas Gregorb491ed32011-02-19 21:32:49 +00008924public:
8925 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8926 const QualType& TargetType, bool Complain)
8927 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8928 Complain(Complain), Context(S.getASTContext()),
8929 TargetTypeIsNonStaticMemberFunction(
8930 !!TargetType->getAs<MemberPointerType>()),
8931 FoundNonTemplateFunction(false),
8932 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8933 OvlExpr(OvlExprInfo.Expression)
8934 {
8935 ExtractUnqualifiedFunctionTypeFromTargetType();
8936
8937 if (!TargetFunctionType->isFunctionType()) {
8938 if (OvlExpr->hasExplicitTemplateArgs()) {
8939 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008940 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008941 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008942
8943 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8944 if (!Method->isStatic()) {
8945 // If the target type is a non-function type and the function
8946 // found is a non-static member function, pretend as if that was
8947 // the target, it's the only possible type to end up with.
8948 TargetTypeIsNonStaticMemberFunction = true;
8949
8950 // And skip adding the function if its not in the proper form.
8951 // We'll diagnose this due to an empty set of functions.
8952 if (!OvlExprInfo.HasFormOfMemberPointer)
8953 return;
8954 }
8955 }
8956
Douglas Gregorb491ed32011-02-19 21:32:49 +00008957 Matches.push_back(std::make_pair(dap,Fn));
8958 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008959 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008960 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008961 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008962
8963 if (OvlExpr->hasExplicitTemplateArgs())
8964 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008965
Douglas Gregorb491ed32011-02-19 21:32:49 +00008966 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8967 // C++ [over.over]p4:
8968 // If more than one function is selected, [...]
8969 if (Matches.size() > 1) {
8970 if (FoundNonTemplateFunction)
8971 EliminateAllTemplateMatches();
8972 else
8973 EliminateAllExceptMostSpecializedTemplate();
8974 }
8975 }
8976 }
8977
8978private:
8979 bool isTargetTypeAFunction() const {
8980 return TargetFunctionType->isFunctionType();
8981 }
8982
8983 // [ToType] [Return]
8984
8985 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8986 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8987 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8988 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8989 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8990 }
8991
8992 // return true if any matching specializations were found
8993 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8994 const DeclAccessPair& CurAccessFunPair) {
8995 if (CXXMethodDecl *Method
8996 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8997 // Skip non-static function templates when converting to pointer, and
8998 // static when converting to member pointer.
8999 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9000 return false;
9001 }
9002 else if (TargetTypeIsNonStaticMemberFunction)
9003 return false;
9004
9005 // C++ [over.over]p2:
9006 // If the name is a function template, template argument deduction is
9007 // done (14.8.2.2), and if the argument deduction succeeds, the
9008 // resulting template argument list is used to generate a single
9009 // function template specialization, which is added to the set of
9010 // overloaded functions considered.
9011 FunctionDecl *Specialization = 0;
Craig Toppere6706e42012-09-19 02:26:47 +00009012 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009013 if (Sema::TemplateDeductionResult Result
9014 = S.DeduceTemplateArguments(FunctionTemplate,
9015 &OvlExplicitTemplateArgs,
9016 TargetFunctionType, Specialization,
9017 Info)) {
9018 // FIXME: make a note of the failed deduction for diagnostics.
9019 (void)Result;
9020 return false;
9021 }
9022
9023 // Template argument deduction ensures that we have an exact match.
9024 // This function template specicalization works.
9025 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9026 assert(TargetFunctionType
9027 == Context.getCanonicalType(Specialization->getType()));
9028 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9029 return true;
9030 }
9031
9032 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9033 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009034 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009035 // Skip non-static functions when converting to pointer, and static
9036 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009037 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9038 return false;
9039 }
9040 else if (TargetTypeIsNonStaticMemberFunction)
9041 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009042
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009043 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009044 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009045 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9046 if (S.CheckCUDATarget(Caller, FunDecl))
9047 return false;
9048
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009049 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009050 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9051 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009052 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9053 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009054 Matches.push_back(std::make_pair(CurAccessFunPair,
9055 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009056 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009057 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009058 }
Mike Stump11289f42009-09-09 15:08:12 +00009059 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009060
9061 return false;
9062 }
9063
9064 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9065 bool Ret = false;
9066
9067 // If the overload expression doesn't have the form of a pointer to
9068 // member, don't try to convert it to a pointer-to-member type.
9069 if (IsInvalidFormOfPointerToMemberFunction())
9070 return false;
9071
9072 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9073 E = OvlExpr->decls_end();
9074 I != E; ++I) {
9075 // Look through any using declarations to find the underlying function.
9076 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9077
9078 // C++ [over.over]p3:
9079 // Non-member functions and static member functions match
9080 // targets of type "pointer-to-function" or "reference-to-function."
9081 // Nonstatic member functions match targets of
9082 // type "pointer-to-member-function."
9083 // Note that according to DR 247, the containing class does not matter.
9084 if (FunctionTemplateDecl *FunctionTemplate
9085 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9086 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9087 Ret = true;
9088 }
9089 // If we have explicit template arguments supplied, skip non-templates.
9090 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9091 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9092 Ret = true;
9093 }
9094 assert(Ret || Matches.empty());
9095 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009096 }
9097
Douglas Gregorb491ed32011-02-19 21:32:49 +00009098 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00009099 // [...] and any given function template specialization F1 is
9100 // eliminated if the set contains a second function template
9101 // specialization whose function template is more specialized
9102 // than the function template of F1 according to the partial
9103 // ordering rules of 14.5.5.2.
9104
9105 // The algorithm specified above is quadratic. We instead use a
9106 // two-pass algorithm (similar to the one used to identify the
9107 // best viable function in an overload set) that identifies the
9108 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00009109
9110 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9111 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9112 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009113
John McCall58cc69d2010-01-27 01:50:18 +00009114 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009115 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9116 TPOC_Other, 0, SourceExpr->getLocStart(),
9117 S.PDiag(),
9118 S.PDiag(diag::err_addr_ovl_ambiguous)
9119 << Matches[0].second->getDeclName(),
9120 S.PDiag(diag::note_ovl_candidate)
9121 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00009122 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009123
Douglas Gregorb491ed32011-02-19 21:32:49 +00009124 if (Result != MatchesCopy.end()) {
9125 // Make it the first and only element
9126 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9127 Matches[0].second = cast<FunctionDecl>(*Result);
9128 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00009129 }
9130 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009131
Douglas Gregorb491ed32011-02-19 21:32:49 +00009132 void EliminateAllTemplateMatches() {
9133 // [...] any function template specializations in the set are
9134 // eliminated if the set also contains a non-template function, [...]
9135 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9136 if (Matches[I].second->getPrimaryTemplate() == 0)
9137 ++I;
9138 else {
9139 Matches[I] = Matches[--N];
9140 Matches.set_size(N);
9141 }
9142 }
9143 }
9144
9145public:
9146 void ComplainNoMatchesFound() const {
9147 assert(Matches.empty());
9148 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9149 << OvlExpr->getName() << TargetFunctionType
9150 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009151 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009152 }
9153
9154 bool IsInvalidFormOfPointerToMemberFunction() const {
9155 return TargetTypeIsNonStaticMemberFunction &&
9156 !OvlExprInfo.HasFormOfMemberPointer;
9157 }
9158
9159 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9160 // TODO: Should we condition this on whether any functions might
9161 // have matched, or is it more appropriate to do that in callers?
9162 // TODO: a fixit wouldn't hurt.
9163 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9164 << TargetType << OvlExpr->getSourceRange();
9165 }
9166
9167 void ComplainOfInvalidConversion() const {
9168 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9169 << OvlExpr->getName() << TargetType;
9170 }
9171
9172 void ComplainMultipleMatchesFound() const {
9173 assert(Matches.size() > 1);
9174 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9175 << OvlExpr->getName()
9176 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009177 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009178 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009179
9180 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9181
Douglas Gregorb491ed32011-02-19 21:32:49 +00009182 int getNumMatches() const { return Matches.size(); }
9183
9184 FunctionDecl* getMatchingFunctionDecl() const {
9185 if (Matches.size() != 1) return 0;
9186 return Matches[0].second;
9187 }
9188
9189 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9190 if (Matches.size() != 1) return 0;
9191 return &Matches[0].first;
9192 }
9193};
9194
9195/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9196/// an overloaded function (C++ [over.over]), where @p From is an
9197/// expression with overloaded function type and @p ToType is the type
9198/// we're trying to resolve to. For example:
9199///
9200/// @code
9201/// int f(double);
9202/// int f(int);
9203///
9204/// int (*pfd)(double) = f; // selects f(double)
9205/// @endcode
9206///
9207/// This routine returns the resulting FunctionDecl if it could be
9208/// resolved, and NULL otherwise. When @p Complain is true, this
9209/// routine will emit diagnostics if there is an error.
9210FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009211Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9212 QualType TargetType,
9213 bool Complain,
9214 DeclAccessPair &FoundResult,
9215 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009216 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009217
9218 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9219 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009220 int NumMatches = Resolver.getNumMatches();
9221 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009222 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009223 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9224 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9225 else
9226 Resolver.ComplainNoMatchesFound();
9227 }
9228 else if (NumMatches > 1 && Complain)
9229 Resolver.ComplainMultipleMatchesFound();
9230 else if (NumMatches == 1) {
9231 Fn = Resolver.getMatchingFunctionDecl();
9232 assert(Fn);
9233 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00009234 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00009235 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00009236 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009237
9238 if (pHadMultipleCandidates)
9239 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009240 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009241}
9242
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009243/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009244/// resolve that overloaded function expression down to a single function.
9245///
9246/// This routine can only resolve template-ids that refer to a single function
9247/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009248/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009249/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00009250FunctionDecl *
9251Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9252 bool Complain,
9253 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009254 // C++ [over.over]p1:
9255 // [...] [Note: any redundant set of parentheses surrounding the
9256 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009257 // C++ [over.over]p1:
9258 // [...] The overloaded function name can be preceded by the &
9259 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009260
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009261 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009262 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009263 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009264
9265 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009266 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009267
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009268 // Look through all of the overloaded functions, searching for one
9269 // whose type matches exactly.
9270 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009271 for (UnresolvedSetIterator I = ovl->decls_begin(),
9272 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009273 // C++0x [temp.arg.explicit]p3:
9274 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009275 // where deduction is not done, if a template argument list is
9276 // specified and it, along with any default template arguments,
9277 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009278 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009279 FunctionTemplateDecl *FunctionTemplate
9280 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009281
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009282 // C++ [over.over]p2:
9283 // If the name is a function template, template argument deduction is
9284 // done (14.8.2.2), and if the argument deduction succeeds, the
9285 // resulting template argument list is used to generate a single
9286 // function template specialization, which is added to the set of
9287 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009288 FunctionDecl *Specialization = 0;
Craig Toppere6706e42012-09-19 02:26:47 +00009289 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009290 if (TemplateDeductionResult Result
9291 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9292 Specialization, Info)) {
9293 // FIXME: make a note of the failed deduction for diagnostics.
9294 (void)Result;
9295 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009296 }
9297
John McCall0009fcc2011-04-26 20:42:42 +00009298 assert(Specialization && "no specialization and no error?");
9299
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009300 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009301 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009302 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00009303 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9304 << ovl->getName();
9305 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009306 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009307 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00009308 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009309
John McCall0009fcc2011-04-26 20:42:42 +00009310 Matched = Specialization;
9311 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009313
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009314 return Matched;
9315}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009316
Douglas Gregor1beec452011-03-12 01:48:56 +00009317
9318
9319
John McCall50a2c2c2011-10-11 23:14:30 +00009320// Resolve and fix an overloaded expression that can be resolved
9321// because it identifies a single function template specialization.
9322//
Douglas Gregor1beec452011-03-12 01:48:56 +00009323// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00009324//
9325// Return true if it was logically possible to so resolve the
9326// expression, regardless of whether or not it succeeded. Always
9327// returns true if 'complain' is set.
9328bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9329 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9330 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00009331 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00009332 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00009333 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00009334
John McCall50a2c2c2011-10-11 23:14:30 +00009335 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00009336
John McCall0009fcc2011-04-26 20:42:42 +00009337 DeclAccessPair found;
9338 ExprResult SingleFunctionExpression;
9339 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9340 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009341 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +00009342 SrcExpr = ExprError();
9343 return true;
9344 }
John McCall0009fcc2011-04-26 20:42:42 +00009345
9346 // It is only correct to resolve to an instance method if we're
9347 // resolving a form that's permitted to be a pointer to member.
9348 // Otherwise we'll end up making a bound member expression, which
9349 // is illegal in all the contexts we resolve like this.
9350 if (!ovl.HasFormOfMemberPointer &&
9351 isa<CXXMethodDecl>(fn) &&
9352 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00009353 if (!complain) return false;
9354
9355 Diag(ovl.Expression->getExprLoc(),
9356 diag::err_bound_member_function)
9357 << 0 << ovl.Expression->getSourceRange();
9358
9359 // TODO: I believe we only end up here if there's a mix of
9360 // static and non-static candidates (otherwise the expression
9361 // would have 'bound member' type, not 'overload' type).
9362 // Ideally we would note which candidate was chosen and why
9363 // the static candidates were rejected.
9364 SrcExpr = ExprError();
9365 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009366 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009367
Sylvestre Ledrua5202662012-07-31 06:56:50 +00009368 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +00009369 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00009370 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00009371
9372 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00009373 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00009374 SingleFunctionExpression =
9375 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00009376 if (SingleFunctionExpression.isInvalid()) {
9377 SrcExpr = ExprError();
9378 return true;
9379 }
9380 }
John McCall0009fcc2011-04-26 20:42:42 +00009381 }
9382
9383 if (!SingleFunctionExpression.isUsable()) {
9384 if (complain) {
9385 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9386 << ovl.Expression->getName()
9387 << DestTypeForComplaining
9388 << OpRangeForComplaining
9389 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00009390 NoteAllOverloadCandidates(SrcExpr.get());
9391
9392 SrcExpr = ExprError();
9393 return true;
9394 }
9395
9396 return false;
John McCall0009fcc2011-04-26 20:42:42 +00009397 }
9398
John McCall50a2c2c2011-10-11 23:14:30 +00009399 SrcExpr = SingleFunctionExpression;
9400 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00009401}
9402
Douglas Gregorcabea402009-09-22 15:41:20 +00009403/// \brief Add a single candidate to the overload set.
9404static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00009405 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00009406 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009407 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009408 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00009409 bool PartialOverloading,
9410 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00009411 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00009412 if (isa<UsingShadowDecl>(Callee))
9413 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9414
Douglas Gregorcabea402009-09-22 15:41:20 +00009415 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00009416 if (ExplicitTemplateArgs) {
9417 assert(!KnownValid && "Explicit template arguments?");
9418 return;
9419 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009420 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9421 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009422 return;
John McCalld14a8642009-11-21 08:51:07 +00009423 }
9424
9425 if (FunctionTemplateDecl *FuncTemplate
9426 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00009427 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009428 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00009429 return;
9430 }
9431
Richard Smith95ce4f62011-06-26 22:19:54 +00009432 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00009433}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009434
Douglas Gregorcabea402009-09-22 15:41:20 +00009435/// \brief Add the overload candidates named by callee and/or found by argument
9436/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00009437void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009438 llvm::ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +00009439 OverloadCandidateSet &CandidateSet,
9440 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00009441
9442#ifndef NDEBUG
9443 // Verify that ArgumentDependentLookup is consistent with the rules
9444 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00009445 //
Douglas Gregorcabea402009-09-22 15:41:20 +00009446 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9447 // and let Y be the lookup set produced by argument dependent
9448 // lookup (defined as follows). If X contains
9449 //
9450 // -- a declaration of a class member, or
9451 //
9452 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00009453 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00009454 //
9455 // -- a declaration that is neither a function or a function
9456 // template
9457 //
9458 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00009459
John McCall57500772009-12-16 12:17:52 +00009460 if (ULE->requiresADL()) {
9461 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9462 E = ULE->decls_end(); I != E; ++I) {
9463 assert(!(*I)->getDeclContext()->isRecord());
9464 assert(isa<UsingShadowDecl>(*I) ||
9465 !(*I)->getDeclContext()->isFunctionOrMethod());
9466 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00009467 }
9468 }
9469#endif
9470
John McCall57500772009-12-16 12:17:52 +00009471 // It would be nice to avoid this copy.
9472 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00009473 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009474 if (ULE->hasExplicitTemplateArgs()) {
9475 ULE->copyTemplateArgumentsInto(TABuffer);
9476 ExplicitTemplateArgs = &TABuffer;
9477 }
9478
9479 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9480 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009481 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9482 CandidateSet, PartialOverloading,
9483 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00009484
John McCall57500772009-12-16 12:17:52 +00009485 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00009486 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +00009487 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009488 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +00009489 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00009490}
John McCalld681c392009-12-16 08:11:27 +00009491
Richard Smith998a5912011-06-05 22:42:48 +00009492/// Attempt to recover from an ill-formed use of a non-dependent name in a
9493/// template, where the non-dependent name was declared after the template
9494/// was defined. This is common in code written for a compilers which do not
9495/// correctly implement two-stage name lookup.
9496///
9497/// Returns true if a viable candidate was found and a diagnostic was issued.
9498static bool
9499DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9500 const CXXScopeSpec &SS, LookupResult &R,
9501 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009502 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009503 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9504 return false;
9505
9506 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +00009507 if (DC->isTransparentContext())
9508 continue;
9509
Richard Smith998a5912011-06-05 22:42:48 +00009510 SemaRef.LookupQualifiedName(R, DC);
9511
9512 if (!R.empty()) {
9513 R.suppressDiagnostics();
9514
9515 if (isa<CXXRecordDecl>(DC)) {
9516 // Don't diagnose names we find in classes; we get much better
9517 // diagnostics for these from DiagnoseEmptyLookup.
9518 R.clear();
9519 return false;
9520 }
9521
9522 OverloadCandidateSet Candidates(FnLoc);
9523 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9524 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009525 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +00009526 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00009527
9528 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00009529 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00009530 // No viable functions. Don't bother the user with notes for functions
9531 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00009532 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00009533 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00009534 }
Richard Smith998a5912011-06-05 22:42:48 +00009535
9536 // Find the namespaces where ADL would have looked, and suggest
9537 // declaring the function there instead.
9538 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9539 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +00009540 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +00009541 AssociatedNamespaces,
9542 AssociatedClasses);
Nick Lewyckya21719d2012-11-13 00:08:34 +00009543 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00009544 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Nick Lewyckya21719d2012-11-13 00:08:34 +00009545 DeclContext *Std = SemaRef.getStdNamespace();
9546 for (Sema::AssociatedNamespaceSet::iterator
9547 it = AssociatedNamespaces.begin(),
9548 end = AssociatedNamespaces.end(); it != end; ++it) {
9549 NamespaceDecl *Assoc = cast<NamespaceDecl>(*it);
9550 if ((!Std || !Std->Encloses(Assoc)) &&
9551 Assoc->getQualifiedNameAsString().find("__") == std::string::npos)
9552 SuggestedNamespaces.insert(Assoc);
Richard Smith998a5912011-06-05 22:42:48 +00009553 }
9554
9555 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9556 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00009557 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00009558 SemaRef.Diag(Best->Function->getLocation(),
9559 diag::note_not_found_by_two_phase_lookup)
9560 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00009561 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00009562 SemaRef.Diag(Best->Function->getLocation(),
9563 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00009564 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00009565 } else {
9566 // FIXME: It would be useful to list the associated namespaces here,
9567 // but the diagnostics infrastructure doesn't provide a way to produce
9568 // a localized representation of a list of items.
9569 SemaRef.Diag(Best->Function->getLocation(),
9570 diag::note_not_found_by_two_phase_lookup)
9571 << R.getLookupName() << 2;
9572 }
9573
9574 // Try to recover by calling this function.
9575 return true;
9576 }
9577
9578 R.clear();
9579 }
9580
9581 return false;
9582}
9583
9584/// Attempt to recover from ill-formed use of a non-dependent operator in a
9585/// template, where the non-dependent operator was declared after the template
9586/// was defined.
9587///
9588/// Returns true if a viable candidate was found and a diagnostic was issued.
9589static bool
9590DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9591 SourceLocation OpLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009592 llvm::ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +00009593 DeclarationName OpName =
9594 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9595 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9596 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009597 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +00009598}
9599
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009600namespace {
9601// Callback to limit the allowed keywords and to only accept typo corrections
9602// that are keywords or whose decls refer to functions (or template functions)
9603// that accept the given number of arguments.
9604class RecoveryCallCCC : public CorrectionCandidateCallback {
9605 public:
9606 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9607 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009608 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009609 WantRemainingKeywords = false;
9610 }
9611
9612 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9613 if (!candidate.getCorrectionDecl())
9614 return candidate.isKeyword();
9615
9616 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9617 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9618 FunctionDecl *FD = 0;
9619 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9620 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9621 FD = FTD->getTemplatedDecl();
9622 if (!HasExplicitTemplateArgs && !FD) {
9623 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9624 // If the Decl is neither a function nor a template function,
9625 // determine if it is a pointer or reference to a function. If so,
9626 // check against the number of arguments expected for the pointee.
9627 QualType ValType = cast<ValueDecl>(ND)->getType();
9628 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9629 ValType = ValType->getPointeeType();
9630 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9631 if (FPT->getNumArgs() == NumArgs)
9632 return true;
9633 }
9634 }
9635 if (FD && FD->getNumParams() >= NumArgs &&
9636 FD->getMinRequiredArguments() <= NumArgs)
9637 return true;
9638 }
9639 return false;
9640 }
9641
9642 private:
9643 unsigned NumArgs;
9644 bool HasExplicitTemplateArgs;
9645};
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009646
9647// Callback that effectively disabled typo correction
9648class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9649 public:
9650 NoTypoCorrectionCCC() {
9651 WantTypeSpecifiers = false;
9652 WantExpressionKeywords = false;
9653 WantCXXNamedCasts = false;
9654 WantRemainingKeywords = false;
9655 }
9656
9657 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9658 return false;
9659 }
9660};
Richard Smith88d67f32012-09-25 04:46:05 +00009661
9662class BuildRecoveryCallExprRAII {
9663 Sema &SemaRef;
9664public:
9665 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9666 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9667 SemaRef.IsBuildingRecoveryCallExpr = true;
9668 }
9669
9670 ~BuildRecoveryCallExprRAII() {
9671 SemaRef.IsBuildingRecoveryCallExpr = false;
9672 }
9673};
9674
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +00009675}
9676
John McCalld681c392009-12-16 08:11:27 +00009677/// Attempts to recover from a call where no functions were found.
9678///
9679/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00009680static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00009681BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00009682 UnresolvedLookupExpr *ULE,
9683 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009684 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +00009685 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009686 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +00009687 // Do not try to recover if it is already building a recovery call.
9688 // This stops infinite loops for template instantiations like
9689 //
9690 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9691 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9692 //
9693 if (SemaRef.IsBuildingRecoveryCallExpr)
9694 return ExprError();
9695 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +00009696
9697 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00009698 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00009699 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +00009700
John McCall57500772009-12-16 12:17:52 +00009701 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00009702 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00009703 if (ULE->hasExplicitTemplateArgs()) {
9704 ULE->copyTemplateArgumentsInto(TABuffer);
9705 ExplicitTemplateArgs = &TABuffer;
9706 }
9707
John McCalld681c392009-12-16 08:11:27 +00009708 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9709 Sema::LookupOrdinaryName);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009710 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009711 NoTypoCorrectionCCC RejectAll;
9712 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9713 (CorrectionCandidateCallback*)&Validator :
9714 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +00009715 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009716 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +00009717 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009718 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009719 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +00009720 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00009721
John McCall57500772009-12-16 12:17:52 +00009722 assert(!R.empty() && "lookup results empty despite recovery");
9723
9724 // Build an implicit member call if appropriate. Just drop the
9725 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00009726 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00009727 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009728 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9729 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009730 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +00009731 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00009732 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00009733 else
9734 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9735
9736 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009737 return ExprError();
John McCall57500772009-12-16 12:17:52 +00009738
9739 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00009740 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00009741 // end up here.
John McCallb268a282010-08-23 23:25:46 +00009742 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009743 MultiExprArg(Args.data(), Args.size()),
9744 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00009745}
Douglas Gregor4038cf42010-06-08 17:35:15 +00009746
Sam Panzer0f384432012-08-21 00:52:01 +00009747/// \brief Constructs and populates an OverloadedCandidateSet from
9748/// the given function.
9749/// \returns true when an the ExprResult output parameter has been set.
9750bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9751 UnresolvedLookupExpr *ULE,
9752 Expr **Args, unsigned NumArgs,
9753 SourceLocation RParenLoc,
9754 OverloadCandidateSet *CandidateSet,
9755 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +00009756#ifndef NDEBUG
9757 if (ULE->requiresADL()) {
9758 // To do ADL, we must have found an unqualified name.
9759 assert(!ULE->getQualifier() && "qualified name with ADL");
9760
9761 // We don't perform ADL for implicit declarations of builtins.
9762 // Verify that this was correctly set up.
9763 FunctionDecl *F;
9764 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9765 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9766 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00009767 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009768
John McCall57500772009-12-16 12:17:52 +00009769 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009770 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +00009771 }
John McCall57500772009-12-16 12:17:52 +00009772#endif
9773
John McCall4124c492011-10-17 18:40:02 +00009774 UnbridgedCastsSet UnbridgedCasts;
Sam Panzer0f384432012-08-21 00:52:01 +00009775 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9776 *Result = ExprError();
9777 return true;
9778 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00009779
John McCall57500772009-12-16 12:17:52 +00009780 // Add the functions denoted by the callee to the set of candidate
9781 // functions, including those from argument-dependent lookup.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009782 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
Sam Panzer0f384432012-08-21 00:52:01 +00009783 *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00009784
9785 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00009786 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9787 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +00009788 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009789 // In Microsoft mode, if we are inside a template class member function then
9790 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00009791 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009792 // classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009793 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00009794 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00009795 CallExpr *CE = new (Context) CallExpr(Context, Fn,
9796 llvm::makeArrayRef(Args, NumArgs),
9797 Context.DependentTy, VK_RValue,
9798 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009799 CE->setTypeDependent(true);
Sam Panzer0f384432012-08-21 00:52:01 +00009800 *Result = Owned(CE);
9801 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00009802 }
Sam Panzer0f384432012-08-21 00:52:01 +00009803 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +00009804 }
John McCalld681c392009-12-16 08:11:27 +00009805
John McCall4124c492011-10-17 18:40:02 +00009806 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +00009807 return false;
9808}
John McCall4124c492011-10-17 18:40:02 +00009809
Sam Panzer0f384432012-08-21 00:52:01 +00009810/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9811/// the completed call expression. If overload resolution fails, emits
9812/// diagnostics and returns ExprError()
9813static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9814 UnresolvedLookupExpr *ULE,
9815 SourceLocation LParenLoc,
9816 Expr **Args, unsigned NumArgs,
9817 SourceLocation RParenLoc,
9818 Expr *ExecConfig,
9819 OverloadCandidateSet *CandidateSet,
9820 OverloadCandidateSet::iterator *Best,
9821 OverloadingResult OverloadResult,
9822 bool AllowTypoCorrection) {
9823 if (CandidateSet->empty())
9824 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9825 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9826 RParenLoc, /*EmptyLookup=*/true,
9827 AllowTypoCorrection);
9828
9829 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +00009830 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +00009831 FunctionDecl *FDecl = (*Best)->Function;
9832 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9833 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9834 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9835 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9836 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9837 RParenLoc, ExecConfig);
John McCall57500772009-12-16 12:17:52 +00009838 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009839
Richard Smith998a5912011-06-05 22:42:48 +00009840 case OR_No_Viable_Function: {
9841 // Try to recover by looking for viable functions which the user might
9842 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +00009843 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009844 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9845 RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00009846 /*EmptyLookup=*/false,
9847 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +00009848 if (!Recovery.isInvalid())
9849 return Recovery;
9850
Sam Panzer0f384432012-08-21 00:52:01 +00009851 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009852 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00009853 << ULE->getName() << Fn->getSourceRange();
Sam Panzer0f384432012-08-21 00:52:01 +00009854 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9855 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009856 break;
Richard Smith998a5912011-06-05 22:42:48 +00009857 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009858
9859 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +00009860 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00009861 << ULE->getName() << Fn->getSourceRange();
Sam Panzer0f384432012-08-21 00:52:01 +00009862 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9863 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009864 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009865
Sam Panzer0f384432012-08-21 00:52:01 +00009866 case OR_Deleted: {
9867 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9868 << (*Best)->Function->isDeleted()
9869 << ULE->getName()
9870 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9871 << Fn->getSourceRange();
9872 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9873 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00009874
Sam Panzer0f384432012-08-21 00:52:01 +00009875 // We emitted an error for the unvailable/deleted function call but keep
9876 // the call in the AST.
9877 FunctionDecl *FDecl = (*Best)->Function;
9878 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9879 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9880 RParenLoc, ExecConfig);
9881 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009882 }
9883
Douglas Gregorb412e172010-07-25 18:17:45 +00009884 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009885 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009886}
9887
Sam Panzer0f384432012-08-21 00:52:01 +00009888/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9889/// (which eventually refers to the declaration Func) and the call
9890/// arguments Args/NumArgs, attempt to resolve the function call down
9891/// to a specific function. If overload resolution succeeds, returns
9892/// the call expression produced by overload resolution.
9893/// Otherwise, emits diagnostics and returns ExprError.
9894ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9895 UnresolvedLookupExpr *ULE,
9896 SourceLocation LParenLoc,
9897 Expr **Args, unsigned NumArgs,
9898 SourceLocation RParenLoc,
9899 Expr *ExecConfig,
9900 bool AllowTypoCorrection) {
9901 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9902 ExprResult result;
9903
9904 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9905 &CandidateSet, &result))
9906 return result;
9907
9908 OverloadCandidateSet::iterator Best;
9909 OverloadingResult OverloadResult =
9910 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
9911
9912 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9913 RParenLoc, ExecConfig, &CandidateSet,
9914 &Best, OverloadResult,
9915 AllowTypoCorrection);
9916}
9917
John McCall4c4c1df2010-01-26 03:27:55 +00009918static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009919 return Functions.size() > 1 ||
9920 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9921}
9922
Douglas Gregor084d8552009-03-13 23:49:33 +00009923/// \brief Create a unary operation that may resolve to an overloaded
9924/// operator.
9925///
9926/// \param OpLoc The location of the operator itself (e.g., '*').
9927///
9928/// \param OpcIn The UnaryOperator::Opcode that describes this
9929/// operator.
9930///
James Dennett18348b62012-06-22 08:52:37 +00009931/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +00009932/// considered by overload resolution. The caller needs to build this
9933/// set based on the context using, e.g.,
9934/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9935/// set should not contain any member functions; those will be added
9936/// by CreateOverloadedUnaryOp().
9937///
James Dennett91738ff2012-06-22 10:32:46 +00009938/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009939ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009940Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9941 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009942 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009943 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009944
9945 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9946 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9947 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009948 // TODO: provide better source location info.
9949 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009950
John McCall4124c492011-10-17 18:40:02 +00009951 if (checkPlaceholderForOverload(*this, Input))
9952 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009953
Douglas Gregor084d8552009-03-13 23:49:33 +00009954 Expr *Args[2] = { Input, 0 };
9955 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009956
Douglas Gregor084d8552009-03-13 23:49:33 +00009957 // For post-increment and post-decrement, add the implicit '0' as
9958 // the second argument, so that we know this is a post-increment or
9959 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009960 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009961 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009962 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9963 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009964 NumArgs = 2;
9965 }
9966
9967 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009968 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009969 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009970 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009971 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009972 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009973 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009974
John McCall58cc69d2010-01-27 01:50:18 +00009975 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009976 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009977 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009978 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009979 /*ADL*/ true, IsOverloaded(Fns),
9980 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009981 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +00009982 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor084d8552009-03-13 23:49:33 +00009983 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009984 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +00009985 OpLoc, false));
Douglas Gregor084d8552009-03-13 23:49:33 +00009986 }
9987
9988 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009989 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009990
9991 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009992 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9993 false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009994
9995 // Add operator candidates that are member functions.
9996 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9997
John McCall4c4c1df2010-01-26 03:27:55 +00009998 // Add candidates from ADL.
9999 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010000 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall4c4c1df2010-01-26 03:27:55 +000010001 /*ExplicitTemplateArgs*/ 0,
10002 CandidateSet);
10003
Douglas Gregor084d8552009-03-13 23:49:33 +000010004 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +000010005 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010006
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010007 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10008
Douglas Gregor084d8552009-03-13 23:49:33 +000010009 // Perform overload resolution.
10010 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010011 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010012 case OR_Success: {
10013 // We found a built-in operator or an overloaded operator.
10014 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010015
Douglas Gregor084d8552009-03-13 23:49:33 +000010016 if (FnDecl) {
10017 // We matched an overloaded operator. Build a call to that
10018 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010019
Eli Friedmanfa0df832012-02-02 03:46:19 +000010020 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010021
Douglas Gregor084d8552009-03-13 23:49:33 +000010022 // Convert the arguments.
10023 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +000010024 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010025
John Wiegley01296292011-04-08 18:41:53 +000010026 ExprResult InputRes =
10027 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10028 Best->FoundDecl, Method);
10029 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010030 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010031 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010032 } else {
10033 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010034 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010035 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010036 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010037 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010038 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010039 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010040 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010041 return ExprError();
John McCallb268a282010-08-23 23:25:46 +000010042 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010043 }
10044
John McCall4fa0d5f2010-05-06 18:15:07 +000010045 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10046
John McCall7decc9e2010-11-18 06:31:45 +000010047 // Determine the result type.
10048 QualType ResultTy = FnDecl->getResultType();
10049 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10050 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +000010051
Douglas Gregor084d8552009-03-13 23:49:33 +000010052 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010053 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010054 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010055 if (FnExpr.isInvalid())
10056 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000010057
Eli Friedman030eee42009-11-18 03:58:17 +000010058 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000010059 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010060 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000010061 llvm::makeArrayRef(Args, NumArgs),
Lang Hames5de91cc2012-10-02 04:45:10 +000010062 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000010063
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010064 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +000010065 FnDecl))
10066 return ExprError();
10067
John McCallb268a282010-08-23 23:25:46 +000010068 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000010069 } else {
10070 // We matched a built-in operator. Convert the arguments, then
10071 // break out so that we will build the appropriate built-in
10072 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010073 ExprResult InputRes =
10074 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10075 Best->Conversions[0], AA_Passing);
10076 if (InputRes.isInvalid())
10077 return ExprError();
10078 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010079 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000010080 }
John Wiegley01296292011-04-08 18:41:53 +000010081 }
10082
10083 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000010084 // This is an erroneous use of an operator which can be overloaded by
10085 // a non-member function. Check for non-member operators which were
10086 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010087 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10088 llvm::makeArrayRef(Args, NumArgs)))
Richard Smith998a5912011-06-05 22:42:48 +000010089 // FIXME: Recover by calling the found function.
10090 return ExprError();
10091
John Wiegley01296292011-04-08 18:41:53 +000010092 // No viable function; fall through to handling this as a
10093 // built-in operator, which will produce an error message for us.
10094 break;
10095
10096 case OR_Ambiguous:
10097 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10098 << UnaryOperator::getOpcodeStr(Opc)
10099 << Input->getType()
10100 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010101 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10102 llvm::makeArrayRef(Args, NumArgs),
John Wiegley01296292011-04-08 18:41:53 +000010103 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10104 return ExprError();
10105
10106 case OR_Deleted:
10107 Diag(OpLoc, diag::err_ovl_deleted_oper)
10108 << Best->Function->isDeleted()
10109 << UnaryOperator::getOpcodeStr(Opc)
10110 << getDeletedOrUnavailableSuffix(Best->Function)
10111 << Input->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010112 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10113 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010114 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010115 return ExprError();
10116 }
Douglas Gregor084d8552009-03-13 23:49:33 +000010117
10118 // Either we found no viable overloaded operator or we matched a
10119 // built-in operator. In either case, fall through to trying to
10120 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000010121 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000010122}
10123
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010124/// \brief Create a binary operation that may resolve to an overloaded
10125/// operator.
10126///
10127/// \param OpLoc The location of the operator itself (e.g., '+').
10128///
10129/// \param OpcIn The BinaryOperator::Opcode that describes this
10130/// operator.
10131///
James Dennett18348b62012-06-22 08:52:37 +000010132/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010133/// considered by overload resolution. The caller needs to build this
10134/// set based on the context using, e.g.,
10135/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10136/// set should not contain any member functions; those will be added
10137/// by CreateOverloadedBinOp().
10138///
10139/// \param LHS Left-hand argument.
10140/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000010141ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010142Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000010143 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000010144 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010145 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010146 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +000010147 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010148
10149 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10150 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10151 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10152
10153 // If either side is type-dependent, create an appropriate dependent
10154 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000010155 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000010156 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010157 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000010158 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000010159 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +000010160 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +000010161 Context.DependentTy,
10162 VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +000010163 OpLoc,
10164 FPFeatures.fp_contract));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010165
Douglas Gregor5287f092009-11-05 00:51:44 +000010166 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10167 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010168 VK_LValue,
10169 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +000010170 Context.DependentTy,
10171 Context.DependentTy,
Lang Hames5de91cc2012-10-02 04:45:10 +000010172 OpLoc,
10173 FPFeatures.fp_contract));
Douglas Gregor5287f092009-11-05 00:51:44 +000010174 }
John McCall4c4c1df2010-01-26 03:27:55 +000010175
10176 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +000010177 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010178 // TODO: provide better source location info in DNLoc component.
10179 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000010180 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000010181 = UnresolvedLookupExpr::Create(Context, NamingClass,
10182 NestedNameSpecifierLoc(), OpNameInfo,
10183 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010184 Fns.begin(), Fns.end());
Lang Hames5de91cc2012-10-02 04:45:10 +000010185 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10186 Context.DependentTy, VK_RValue,
10187 OpLoc, FPFeatures.fp_contract));
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010188 }
10189
John McCall4124c492011-10-17 18:40:02 +000010190 // Always do placeholder-like conversions on the RHS.
10191 if (checkPlaceholderForOverload(*this, Args[1]))
10192 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010193
John McCall526ab472011-10-25 17:37:35 +000010194 // Do placeholder-like conversion on the LHS; note that we should
10195 // not get here with a PseudoObject LHS.
10196 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000010197 if (checkPlaceholderForOverload(*this, Args[0]))
10198 return ExprError();
10199
Sebastian Redl6a96bf72009-11-18 23:10:33 +000010200 // If this is the assignment operator, we only perform overload resolution
10201 // if the left-hand side is a class or enumeration type. This is actually
10202 // a hack. The standard requires that we do overload resolution between the
10203 // various built-in candidates, but as DR507 points out, this can lead to
10204 // problems. So we do it this way, which pretty much follows what GCC does.
10205 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000010206 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000010207 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010208
John McCalle26a8722010-12-04 08:14:53 +000010209 // If this is the .* operator, which is not overloadable, just
10210 // create a built-in binary operator.
10211 if (Opc == BO_PtrMemD)
10212 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10213
Douglas Gregor084d8552009-03-13 23:49:33 +000010214 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010215 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010216
10217 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010218 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010219
10220 // Add operator candidates that are member functions.
10221 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10222
John McCall4c4c1df2010-01-26 03:27:55 +000010223 // Add candidates from ADL.
10224 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010225 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +000010226 /*ExplicitTemplateArgs*/ 0,
10227 CandidateSet);
10228
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010229 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +000010230 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010231
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010232 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10233
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010234 // Perform overload resolution.
10235 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010236 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000010237 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010238 // We found a built-in operator or an overloaded operator.
10239 FunctionDecl *FnDecl = Best->Function;
10240
10241 if (FnDecl) {
10242 // We matched an overloaded operator. Build a call to that
10243 // operator.
10244
Eli Friedmanfa0df832012-02-02 03:46:19 +000010245 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010246
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010247 // Convert the arguments.
10248 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000010249 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000010250 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010251
Chandler Carruth8e543b32010-12-12 08:17:55 +000010252 ExprResult Arg1 =
10253 PerformCopyInitialization(
10254 InitializedEntity::InitializeParameter(Context,
10255 FnDecl->getParamDecl(0)),
10256 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010257 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010258 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010259
John Wiegley01296292011-04-08 18:41:53 +000010260 ExprResult Arg0 =
10261 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10262 Best->FoundDecl, Method);
10263 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010264 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010265 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010266 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010267 } else {
10268 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000010269 ExprResult Arg0 = PerformCopyInitialization(
10270 InitializedEntity::InitializeParameter(Context,
10271 FnDecl->getParamDecl(0)),
10272 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010273 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010274 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010275
Chandler Carruth8e543b32010-12-12 08:17:55 +000010276 ExprResult Arg1 =
10277 PerformCopyInitialization(
10278 InitializedEntity::InitializeParameter(Context,
10279 FnDecl->getParamDecl(1)),
10280 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010281 if (Arg1.isInvalid())
10282 return ExprError();
10283 Args[0] = LHS = Arg0.takeAs<Expr>();
10284 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010285 }
10286
John McCall4fa0d5f2010-05-06 18:15:07 +000010287 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10288
John McCall7decc9e2010-11-18 06:31:45 +000010289 // Determine the result type.
10290 QualType ResultTy = FnDecl->getResultType();
10291 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10292 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010293
10294 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010295 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10296 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010297 if (FnExpr.isInvalid())
10298 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010299
John McCallb268a282010-08-23 23:25:46 +000010300 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010301 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000010302 Args, ResultTy, VK, OpLoc,
10303 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010304
10305 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010306 FnDecl))
10307 return ExprError();
10308
John McCallb268a282010-08-23 23:25:46 +000010309 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010310 } else {
10311 // We matched a built-in operator. Convert the arguments, then
10312 // break out so that we will build the appropriate built-in
10313 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010314 ExprResult ArgsRes0 =
10315 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10316 Best->Conversions[0], AA_Passing);
10317 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010318 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010319 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010320
John Wiegley01296292011-04-08 18:41:53 +000010321 ExprResult ArgsRes1 =
10322 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10323 Best->Conversions[1], AA_Passing);
10324 if (ArgsRes1.isInvalid())
10325 return ExprError();
10326 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010327 break;
10328 }
10329 }
10330
Douglas Gregor66950a32009-09-30 21:46:01 +000010331 case OR_No_Viable_Function: {
10332 // C++ [over.match.oper]p9:
10333 // If the operator is the operator , [...] and there are no
10334 // viable functions, then the operator is assumed to be the
10335 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000010336 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000010337 break;
10338
Chandler Carruth8e543b32010-12-12 08:17:55 +000010339 // For class as left operand for assignment or compound assigment
10340 // operator do not fall through to handling in built-in, but report that
10341 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000010342 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010343 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000010344 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000010345 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10346 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000010347 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +000010348 } else {
Richard Smith998a5912011-06-05 22:42:48 +000010349 // This is an erroneous use of an operator which can be overloaded by
10350 // a non-member function. Check for non-member operators which were
10351 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010352 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000010353 // FIXME: Recover by calling the found function.
10354 return ExprError();
10355
Douglas Gregor66950a32009-09-30 21:46:01 +000010356 // No viable function; try to create a built-in operation, which will
10357 // produce an error. Then, show the non-viable candidates.
10358 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000010359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010360 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000010361 "C++ binary operator overloading is missing candidates!");
10362 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010363 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010364 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010365 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000010366 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010367
10368 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010369 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010370 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000010371 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000010372 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010373 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010374 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010375 return ExprError();
10376
10377 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000010378 if (isImplicitlyDeleted(Best->Function)) {
10379 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10380 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10381 << getSpecialMember(Method)
10382 << BinaryOperator::getOpcodeStr(Opc)
10383 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith6f1e2c62012-04-02 20:59:25 +000010384
10385 if (getSpecialMember(Method) != CXXInvalid) {
10386 // The user probably meant to call this special member. Just
10387 // explain why it's deleted.
10388 NoteDeletedFunction(Method);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010389 return ExprError();
10390 }
10391 } else {
10392 Diag(OpLoc, diag::err_ovl_deleted_oper)
10393 << Best->Function->isDeleted()
10394 << BinaryOperator::getOpcodeStr(Opc)
10395 << getDeletedOrUnavailableSuffix(Best->Function)
10396 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10397 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010398 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010399 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010400 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000010401 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010402
Douglas Gregor66950a32009-09-30 21:46:01 +000010403 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000010404 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010405}
10406
John McCalldadc5752010-08-24 06:29:42 +000010407ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000010408Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10409 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000010410 Expr *Base, Expr *Idx) {
10411 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000010412 DeclarationName OpName =
10413 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10414
10415 // If either side is type-dependent, create an appropriate dependent
10416 // expression.
10417 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10418
John McCall58cc69d2010-01-27 01:50:18 +000010419 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010420 // CHECKME: no 'operator' keyword?
10421 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10422 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000010423 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010424 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010425 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010426 /*ADL*/ true, /*Overloaded*/ false,
10427 UnresolvedSetIterator(),
10428 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000010429 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000010430
Sebastian Redladba46e2009-10-29 20:17:01 +000010431 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010432 Args,
Sebastian Redladba46e2009-10-29 20:17:01 +000010433 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010434 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000010435 RLoc, false));
Sebastian Redladba46e2009-10-29 20:17:01 +000010436 }
10437
John McCall4124c492011-10-17 18:40:02 +000010438 // Handle placeholders on both operands.
10439 if (checkPlaceholderForOverload(*this, Args[0]))
10440 return ExprError();
10441 if (checkPlaceholderForOverload(*this, Args[1]))
10442 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010443
Sebastian Redladba46e2009-10-29 20:17:01 +000010444 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010445 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010446
10447 // Subscript can only be overloaded as a member function.
10448
10449 // Add operator candidates that are member functions.
10450 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10451
10452 // Add builtin operator candidates.
10453 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10454
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010455 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10456
Sebastian Redladba46e2009-10-29 20:17:01 +000010457 // Perform overload resolution.
10458 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010459 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000010460 case OR_Success: {
10461 // We found a built-in operator or an overloaded operator.
10462 FunctionDecl *FnDecl = Best->Function;
10463
10464 if (FnDecl) {
10465 // We matched an overloaded operator. Build a call to that
10466 // operator.
10467
Eli Friedmanfa0df832012-02-02 03:46:19 +000010468 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth30141632011-02-25 19:41:05 +000010469
John McCalla0296f72010-03-19 07:35:19 +000010470 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010471 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +000010472
Sebastian Redladba46e2009-10-29 20:17:01 +000010473 // Convert the arguments.
10474 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000010475 ExprResult Arg0 =
10476 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10477 Best->FoundDecl, Method);
10478 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010479 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010480 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010481
Anders Carlssona68e51e2010-01-29 18:37:50 +000010482 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010483 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000010484 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010485 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000010486 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010487 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000010488 Owned(Args[1]));
10489 if (InputInit.isInvalid())
10490 return ExprError();
10491
10492 Args[1] = InputInit.takeAs<Expr>();
10493
Sebastian Redladba46e2009-10-29 20:17:01 +000010494 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +000010495 QualType ResultTy = FnDecl->getResultType();
10496 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10497 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +000010498
10499 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010500 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10501 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010502 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10503 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010504 OpLocInfo.getLoc(),
10505 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000010506 if (FnExpr.isInvalid())
10507 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010508
John McCallb268a282010-08-23 23:25:46 +000010509 CXXOperatorCallExpr *TheCall =
10510 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010511 FnExpr.take(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000010512 ResultTy, VK, RLoc,
10513 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000010514
John McCallb268a282010-08-23 23:25:46 +000010515 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000010516 FnDecl))
10517 return ExprError();
10518
John McCallb268a282010-08-23 23:25:46 +000010519 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000010520 } else {
10521 // We matched a built-in operator. Convert the arguments, then
10522 // break out so that we will build the appropriate built-in
10523 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010524 ExprResult ArgsRes0 =
10525 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10526 Best->Conversions[0], AA_Passing);
10527 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000010528 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010529 Args[0] = ArgsRes0.take();
10530
10531 ExprResult ArgsRes1 =
10532 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10533 Best->Conversions[1], AA_Passing);
10534 if (ArgsRes1.isInvalid())
10535 return ExprError();
10536 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000010537
10538 break;
10539 }
10540 }
10541
10542 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000010543 if (CandidateSet.empty())
10544 Diag(LLoc, diag::err_ovl_no_oper)
10545 << Args[0]->getType() << /*subscript*/ 0
10546 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10547 else
10548 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10549 << Args[0]->getType()
10550 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010551 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010552 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000010553 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000010554 }
10555
10556 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010557 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010558 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000010559 << Args[0]->getType() << Args[1]->getType()
10560 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010561 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010562 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010563 return ExprError();
10564
10565 case OR_Deleted:
10566 Diag(LLoc, diag::err_ovl_deleted_oper)
10567 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010568 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000010569 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010570 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000010571 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010572 return ExprError();
10573 }
10574
10575 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000010576 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000010577}
10578
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010579/// BuildCallToMemberFunction - Build a call to a member
10580/// function. MemExpr is the expression that refers to the member
10581/// function (and includes the object parameter), Args/NumArgs are the
10582/// arguments to the function call (not including the object
10583/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000010584/// expression refers to a non-static member function or an overloaded
10585/// member function.
John McCalldadc5752010-08-24 06:29:42 +000010586ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000010587Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10588 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +000010589 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000010590 assert(MemExprE->getType() == Context.BoundMemberTy ||
10591 MemExprE->getType() == Context.OverloadTy);
10592
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010593 // Dig out the member expression. This holds both the object
10594 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000010595 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010596
John McCall0009fcc2011-04-26 20:42:42 +000010597 // Determine whether this is a call to a pointer-to-member function.
10598 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10599 assert(op->getType() == Context.BoundMemberTy);
10600 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10601
10602 QualType fnType =
10603 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10604
10605 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10606 QualType resultType = proto->getCallResultType(Context);
10607 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10608
10609 // Check that the object type isn't more qualified than the
10610 // member function we're calling.
10611 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10612
10613 QualType objectType = op->getLHS()->getType();
10614 if (op->getOpcode() == BO_PtrMemI)
10615 objectType = objectType->castAs<PointerType>()->getPointeeType();
10616 Qualifiers objectQuals = objectType.getQualifiers();
10617
10618 Qualifiers difference = objectQuals - funcQuals;
10619 difference.removeObjCGCAttr();
10620 difference.removeAddressSpace();
10621 if (difference) {
10622 std::string qualsString = difference.getAsString();
10623 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10624 << fnType.getUnqualifiedType()
10625 << qualsString
10626 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10627 }
10628
10629 CXXMemberCallExpr *call
Benjamin Kramerc215e762012-08-24 11:54:20 +000010630 = new (Context) CXXMemberCallExpr(Context, MemExprE,
10631 llvm::makeArrayRef(Args, NumArgs),
John McCall0009fcc2011-04-26 20:42:42 +000010632 resultType, valueKind, RParenLoc);
10633
10634 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010635 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000010636 call, 0))
10637 return ExprError();
10638
10639 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10640 return ExprError();
10641
10642 return MaybeBindToTemporary(call);
10643 }
10644
John McCall4124c492011-10-17 18:40:02 +000010645 UnbridgedCastsSet UnbridgedCasts;
10646 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10647 return ExprError();
10648
John McCall10eae182009-11-30 22:42:35 +000010649 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010650 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000010651 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010652 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000010653 if (isa<MemberExpr>(NakedMemExpr)) {
10654 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000010655 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000010656 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010657 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000010658 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000010659 } else {
10660 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000010661 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010662
John McCall6e9f8f62009-12-03 04:06:58 +000010663 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000010664 Expr::Classification ObjectClassification
10665 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10666 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000010667
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010668 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000010669 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000010670
John McCall2d74de92009-12-01 22:10:20 +000010671 // FIXME: avoid copy.
10672 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10673 if (UnresExpr->hasExplicitTemplateArgs()) {
10674 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10675 TemplateArgs = &TemplateArgsBuffer;
10676 }
10677
John McCall10eae182009-11-30 22:42:35 +000010678 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10679 E = UnresExpr->decls_end(); I != E; ++I) {
10680
John McCall6e9f8f62009-12-03 04:06:58 +000010681 NamedDecl *Func = *I;
10682 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10683 if (isa<UsingShadowDecl>(Func))
10684 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10685
Douglas Gregor02824322011-01-26 19:30:28 +000010686
Francois Pichet64225792011-01-18 05:04:39 +000010687 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010688 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010689 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10690 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000010691 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000010692 // If explicit template arguments were provided, we can't call a
10693 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000010694 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000010695 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010696
John McCalla0296f72010-03-19 07:35:19 +000010697 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010698 ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010699 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000010700 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010701 } else {
John McCall10eae182009-11-30 22:42:35 +000010702 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000010703 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010704 ObjectType, ObjectClassification,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010705 llvm::makeArrayRef(Args, NumArgs),
10706 CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010707 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000010708 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000010709 }
Mike Stump11289f42009-09-09 15:08:12 +000010710
John McCall10eae182009-11-30 22:42:35 +000010711 DeclarationName DeclName = UnresExpr->getMemberName();
10712
John McCall4124c492011-10-17 18:40:02 +000010713 UnbridgedCasts.restore();
10714
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010715 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010716 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000010717 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010718 case OR_Success:
10719 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010720 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +000010721 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000010722 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010723 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010724 break;
10725
10726 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000010727 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010728 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010729 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010730 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10731 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010732 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010733 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010734
10735 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000010736 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000010737 << DeclName << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010738 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10739 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010740 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010741 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010742
10743 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000010744 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000010745 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010746 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010747 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010748 << MemExprE->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010749 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10750 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010751 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000010752 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010753 }
10754
John McCall16df1e52010-03-30 21:47:33 +000010755 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000010756
John McCall2d74de92009-12-01 22:10:20 +000010757 // If overload resolution picked a static member, build a
10758 // non-member call based on that function.
10759 if (Method->isStatic()) {
10760 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10761 Args, NumArgs, RParenLoc);
10762 }
10763
John McCall10eae182009-11-30 22:42:35 +000010764 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010765 }
10766
John McCall7decc9e2010-11-18 06:31:45 +000010767 QualType ResultType = Method->getResultType();
10768 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10769 ResultType = ResultType.getNonLValueExprType(Context);
10770
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010771 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010772 CXXMemberCallExpr *TheCall =
Benjamin Kramerc215e762012-08-24 11:54:20 +000010773 new (Context) CXXMemberCallExpr(Context, MemExprE,
10774 llvm::makeArrayRef(Args, NumArgs),
John McCall7decc9e2010-11-18 06:31:45 +000010775 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010776
Anders Carlssonc4859ba2009-10-10 00:06:20 +000010777 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010778 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000010779 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000010780 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010781
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010782 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000010783 // We only need to do this if there was actually an overload; otherwise
10784 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000010785 if (!Method->isStatic()) {
10786 ExprResult ObjectArg =
10787 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10788 FoundDecl, Method);
10789 if (ObjectArg.isInvalid())
10790 return ExprError();
10791 MemExpr->setBase(ObjectArg.take());
10792 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010793
10794 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000010795 const FunctionProtoType *Proto =
10796 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +000010797 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010798 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000010799 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010800
Eli Friedmanff4b4072012-02-18 04:48:30 +000010801 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10802
Richard Smith55ce3522012-06-25 20:30:08 +000010803 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000010804 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000010805
Anders Carlsson47061ee2011-05-06 14:25:31 +000010806 if ((isa<CXXConstructorDecl>(CurContext) ||
10807 isa<CXXDestructorDecl>(CurContext)) &&
10808 TheCall->getMethodDecl()->isPure()) {
10809 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10810
Chandler Carruth59259262011-06-27 08:31:58 +000010811 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000010812 Diag(MemExpr->getLocStart(),
10813 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10814 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10815 << MD->getParent()->getDeclName();
10816
10817 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000010818 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000010819 }
John McCallb268a282010-08-23 23:25:46 +000010820 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000010821}
10822
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010823/// BuildCallToObjectOfClassType - Build a call to an object of class
10824/// type (C++ [over.call.object]), which can end up invoking an
10825/// overloaded function call operator (@c operator()) or performing a
10826/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000010827ExprResult
John Wiegley01296292011-04-08 18:41:53 +000010828Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000010829 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010830 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010831 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000010832 if (checkPlaceholderForOverload(*this, Obj))
10833 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010834 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000010835
10836 UnbridgedCastsSet UnbridgedCasts;
10837 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10838 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010839
John Wiegley01296292011-04-08 18:41:53 +000010840 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10841 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000010842
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010843 // C++ [over.call.object]p1:
10844 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000010845 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010846 // candidate functions includes at least the function call
10847 // operators of T. The function call operators of T are obtained by
10848 // ordinary lookup of the name operator() in the context of
10849 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000010850 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000010851 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010852
John Wiegley01296292011-04-08 18:41:53 +000010853 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010854 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010855 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010856
John McCall27b18f82009-11-17 02:14:36 +000010857 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10858 LookupQualifiedName(R, Record->getDecl());
10859 R.suppressDiagnostics();
10860
Douglas Gregorc473cbb2009-11-15 07:48:03 +000010861 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000010862 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000010863 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10864 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000010865 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000010866 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010867
Douglas Gregorab7897a2008-11-19 22:57:39 +000010868 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010869 // In addition, for each (non-explicit in C++0x) conversion function
10870 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000010871 //
10872 // operator conversion-type-id () cv-qualifier;
10873 //
10874 // where cv-qualifier is the same cv-qualification as, or a
10875 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000010876 // denotes the type "pointer to function of (P1,...,Pn) returning
10877 // R", or the type "reference to pointer to function of
10878 // (P1,...,Pn) returning R", or the type "reference to function
10879 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000010880 // is also considered as a candidate function. Similarly,
10881 // surrogate call functions are added to the set of candidate
10882 // functions for each conversion function declared in an
10883 // accessible base class provided the function is not hidden
10884 // within T by another intervening declaration.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000010885 std::pair<CXXRecordDecl::conversion_iterator,
10886 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000010887 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000010888 for (CXXRecordDecl::conversion_iterator
10889 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000010890 NamedDecl *D = *I;
10891 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10892 if (isa<UsingShadowDecl>(D))
10893 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010894
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010895 // Skip over templated conversion functions; they aren't
10896 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000010897 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000010898 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000010899
John McCall6e9f8f62009-12-03 04:06:58 +000010900 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010901 if (!Conv->isExplicit()) {
10902 // Strip the reference type (if any) and then the pointer type (if
10903 // any) to get down to what might be a function type.
10904 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10905 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10906 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000010907
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010908 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10909 {
10910 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010911 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10912 CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000010913 }
10914 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000010915 }
Mike Stump11289f42009-09-09 15:08:12 +000010916
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010917 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10918
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010919 // Perform overload resolution.
10920 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000010921 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000010922 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010923 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000010924 // Overload resolution succeeded; we'll build the appropriate call
10925 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010926 break;
10927
10928 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000010929 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010930 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000010931 << Object.get()->getType() << /*call*/ 1
10932 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000010933 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010934 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000010935 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010936 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010937 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10938 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010939 break;
10940
10941 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010942 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010943 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000010944 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010945 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10946 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010947 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010948
10949 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010950 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010951 diag::err_ovl_deleted_object_call)
10952 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010953 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010954 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010955 << Object.get()->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010956 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10957 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor171c45a2009-02-18 21:56:37 +000010958 break;
Mike Stump11289f42009-09-09 15:08:12 +000010959 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010960
Douglas Gregorb412e172010-07-25 18:17:45 +000010961 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010962 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010963
John McCall4124c492011-10-17 18:40:02 +000010964 UnbridgedCasts.restore();
10965
Douglas Gregorab7897a2008-11-19 22:57:39 +000010966 if (Best->Function == 0) {
10967 // Since there is no function declaration, this is one of the
10968 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010969 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010970 = cast<CXXConversionDecl>(
10971 Best->Conversions[0].UserDefined.ConversionFunction);
10972
John Wiegley01296292011-04-08 18:41:53 +000010973 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010974 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010975
Douglas Gregorab7897a2008-11-19 22:57:39 +000010976 // We selected one of the surrogate functions that converts the
10977 // object parameter to a function pointer. Perform the conversion
10978 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010979
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010980 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010981 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010982 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10983 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010984 if (Call.isInvalid())
10985 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010986 // Record usage of conversion in an implicit cast.
10987 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10988 CK_UserDefinedConversion,
10989 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010990
Douglas Gregor668443e2011-01-20 00:18:04 +000010991 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010992 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010993 }
10994
Eli Friedmanfa0df832012-02-02 03:46:19 +000010995 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010996 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010997 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010998
Douglas Gregorab7897a2008-11-19 22:57:39 +000010999 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11000 // that calls this method, using Object for the implicit object
11001 // parameter and passing along the remaining arguments.
11002 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011003
11004 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011005 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011006 return ExprError();
11007
Chandler Carruth8e543b32010-12-12 08:17:55 +000011008 const FunctionProtoType *Proto =
11009 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011010
11011 unsigned NumArgsInProto = Proto->getNumArgs();
11012 unsigned NumArgsToCheck = NumArgs;
11013
11014 // Build the full argument list for the method call (the
11015 // implicit object parameter is placed at the beginning of the
11016 // list).
11017 Expr **MethodArgs;
11018 if (NumArgs < NumArgsInProto) {
11019 NumArgsToCheck = NumArgsInProto;
11020 MethodArgs = new Expr*[NumArgsInProto + 1];
11021 } else {
11022 MethodArgs = new Expr*[NumArgs + 1];
11023 }
John Wiegley01296292011-04-08 18:41:53 +000011024 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011025 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11026 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000011027
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011028 DeclarationNameInfo OpLocInfo(
11029 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11030 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011031 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011032 HadMultipleCandidates,
11033 OpLocInfo.getLoc(),
11034 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011035 if (NewFn.isInvalid())
11036 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011037
11038 // Once we've built TheCall, all of the expressions are properly
11039 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000011040 QualType ResultTy = Method->getResultType();
11041 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11042 ResultTy = ResultTy.getNonLValueExprType(Context);
11043
John McCallb268a282010-08-23 23:25:46 +000011044 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011045 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000011046 llvm::makeArrayRef(MethodArgs, NumArgs+1),
Lang Hames5de91cc2012-10-02 04:45:10 +000011047 ResultTy, VK, RParenLoc, false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011048 delete [] MethodArgs;
11049
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011050 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000011051 Method))
11052 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011053
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011054 // We may have default arguments. If so, we need to allocate more
11055 // slots in the call for them.
11056 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000011057 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011058 else if (NumArgs > NumArgsInProto)
11059 NumArgsToCheck = NumArgsInProto;
11060
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011061 bool IsError = false;
11062
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011063 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000011064 ExprResult ObjRes =
11065 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11066 Best->FoundDecl, Method);
11067 if (ObjRes.isInvalid())
11068 IsError = true;
11069 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011070 Object = ObjRes;
John Wiegley01296292011-04-08 18:41:53 +000011071 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011072
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011073 // Check the argument types.
11074 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011075 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011076 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011077 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000011078
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011079 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011080
John McCalldadc5752010-08-24 06:29:42 +000011081 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011082 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011083 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011084 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000011085 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011086
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011087 IsError |= InputInit.isInvalid();
11088 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011089 } else {
John McCalldadc5752010-08-24 06:29:42 +000011090 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011091 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11092 if (DefArg.isInvalid()) {
11093 IsError = true;
11094 break;
11095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011096
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011097 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011098 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011099
11100 TheCall->setArg(i + 1, Arg);
11101 }
11102
11103 // If this is a variadic call, handle args passed through "...".
11104 if (Proto->isVariadic()) {
11105 // Promote the arguments (C99 6.5.2.2p7).
Aaron Ballman9bca21e2012-07-20 20:40:35 +000011106 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000011107 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11108 IsError |= Arg.isInvalid();
11109 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011110 }
11111 }
11112
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011113 if (IsError) return true;
11114
Eli Friedmanff4b4072012-02-18 04:48:30 +000011115 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11116
Richard Smith55ce3522012-06-25 20:30:08 +000011117 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000011118 return true;
11119
John McCalle172be52010-08-24 06:09:16 +000011120 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011121}
11122
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011123/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000011124/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011125/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000011126ExprResult
John McCallb268a282010-08-23 23:25:46 +000011127Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000011128 assert(Base->getType()->isRecordType() &&
11129 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000011130
John McCall4124c492011-10-17 18:40:02 +000011131 if (checkPlaceholderForOverload(*this, Base))
11132 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011133
John McCallbc077cf2010-02-08 23:07:23 +000011134 SourceLocation Loc = Base->getExprLoc();
11135
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011136 // C++ [over.ref]p1:
11137 //
11138 // [...] An expression x->m is interpreted as (x.operator->())->m
11139 // for a class object x of type T if T::operator->() exists and if
11140 // the operator is selected as the best match function by the
11141 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000011142 DeclarationName OpName =
11143 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000011144 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011145 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000011146
John McCallbc077cf2010-02-08 23:07:23 +000011147 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011148 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000011149 return ExprError();
11150
John McCall27b18f82009-11-17 02:14:36 +000011151 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11152 LookupQualifiedName(R, BaseRecord->getDecl());
11153 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000011154
11155 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000011156 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000011157 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11158 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000011159 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011160
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011161 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11162
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011163 // Perform overload resolution.
11164 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011165 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011166 case OR_Success:
11167 // Overload resolution succeeded; we'll build the call below.
11168 break;
11169
11170 case OR_No_Viable_Function:
11171 if (CandidateSet.empty())
11172 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000011173 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011174 else
11175 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000011176 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011177 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011178 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011179
11180 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011181 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11182 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011183 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011184 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011185
11186 case OR_Deleted:
11187 Diag(OpLoc, diag::err_ovl_deleted_oper)
11188 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011189 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011190 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011191 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011192 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011193 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011194 }
11195
Eli Friedmanfa0df832012-02-02 03:46:19 +000011196 MarkFunctionReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000011197 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000011198 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000011199
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011200 // Convert the object parameter.
11201 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000011202 ExprResult BaseResult =
11203 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11204 Best->FoundDecl, Method);
11205 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000011206 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011207 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000011208
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011209 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011210 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011211 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011212 if (FnExpr.isInvalid())
11213 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011214
John McCall7decc9e2010-11-18 06:31:45 +000011215 QualType ResultTy = Method->getResultType();
11216 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11217 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000011218 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011219 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011220 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011221
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011222 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011223 Method))
11224 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000011225
11226 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011227}
11228
Richard Smithbcc22fc2012-03-09 08:00:36 +000011229/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11230/// a literal operator described by the provided lookup results.
11231ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11232 DeclarationNameInfo &SuffixInfo,
11233 ArrayRef<Expr*> Args,
11234 SourceLocation LitEndLoc,
11235 TemplateArgumentListInfo *TemplateArgs) {
11236 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000011237
Richard Smithbcc22fc2012-03-09 08:00:36 +000011238 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11239 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11240 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000011241
Richard Smithbcc22fc2012-03-09 08:00:36 +000011242 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11243
Richard Smithbcc22fc2012-03-09 08:00:36 +000011244 // Perform overload resolution. This will usually be trivial, but might need
11245 // to perform substitutions for a literal operator template.
11246 OverloadCandidateSet::iterator Best;
11247 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11248 case OR_Success:
11249 case OR_Deleted:
11250 break;
11251
11252 case OR_No_Viable_Function:
11253 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11254 << R.getLookupName();
11255 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11256 return ExprError();
11257
11258 case OR_Ambiguous:
11259 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11260 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11261 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000011262 }
11263
Richard Smithbcc22fc2012-03-09 08:00:36 +000011264 FunctionDecl *FD = Best->Function;
11265 MarkFunctionReferenced(UDSuffixLoc, FD);
11266 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smithc67fdd42012-03-07 08:35:16 +000011267
Richard Smithbcc22fc2012-03-09 08:00:36 +000011268 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11269 SuffixInfo.getLoc(),
11270 SuffixInfo.getInfo());
11271 if (Fn.isInvalid())
11272 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000011273
11274 // Check the argument types. This should almost always be a no-op, except
11275 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000011276 Expr *ConvArgs[2];
11277 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11278 ExprResult InputInit = PerformCopyInitialization(
11279 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11280 SourceLocation(), Args[ArgIdx]);
11281 if (InputInit.isInvalid())
11282 return true;
11283 ConvArgs[ArgIdx] = InputInit.take();
11284 }
11285
Richard Smithc67fdd42012-03-07 08:35:16 +000011286 QualType ResultTy = FD->getResultType();
11287 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11288 ResultTy = ResultTy.getNonLValueExprType(Context);
11289
Richard Smithc67fdd42012-03-07 08:35:16 +000011290 UserDefinedLiteral *UDL =
Benjamin Kramerc215e762012-08-24 11:54:20 +000011291 new (Context) UserDefinedLiteral(Context, Fn.take(),
11292 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000011293 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11294
11295 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11296 return ExprError();
11297
Richard Smith55ce3522012-06-25 20:30:08 +000011298 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smithc67fdd42012-03-07 08:35:16 +000011299 return ExprError();
11300
11301 return MaybeBindToTemporary(UDL);
11302}
11303
Sam Panzer0f384432012-08-21 00:52:01 +000011304/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11305/// given LookupResult is non-empty, it is assumed to describe a member which
11306/// will be invoked. Otherwise, the function will be found via argument
11307/// dependent lookup.
11308/// CallExpr is set to a valid expression and FRS_Success returned on success,
11309/// otherwise CallExpr is set to ExprError() and some non-success value
11310/// is returned.
11311Sema::ForRangeStatus
11312Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11313 SourceLocation RangeLoc, VarDecl *Decl,
11314 BeginEndFunction BEF,
11315 const DeclarationNameInfo &NameInfo,
11316 LookupResult &MemberLookup,
11317 OverloadCandidateSet *CandidateSet,
11318 Expr *Range, ExprResult *CallExpr) {
11319 CandidateSet->clear();
11320 if (!MemberLookup.empty()) {
11321 ExprResult MemberRef =
11322 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11323 /*IsPtr=*/false, CXXScopeSpec(),
11324 /*TemplateKWLoc=*/SourceLocation(),
11325 /*FirstQualifierInScope=*/0,
11326 MemberLookup,
11327 /*TemplateArgs=*/0);
11328 if (MemberRef.isInvalid()) {
11329 *CallExpr = ExprError();
11330 Diag(Range->getLocStart(), diag::note_in_for_range)
11331 << RangeLoc << BEF << Range->getType();
11332 return FRS_DiagnosticIssued;
11333 }
11334 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11335 if (CallExpr->isInvalid()) {
11336 *CallExpr = ExprError();
11337 Diag(Range->getLocStart(), diag::note_in_for_range)
11338 << RangeLoc << BEF << Range->getType();
11339 return FRS_DiagnosticIssued;
11340 }
11341 } else {
11342 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000011343 UnresolvedLookupExpr *Fn =
11344 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11345 NestedNameSpecifierLoc(), NameInfo,
11346 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000011347 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000011348
11349 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11350 CandidateSet, CallExpr);
11351 if (CandidateSet->empty() || CandidateSetError) {
11352 *CallExpr = ExprError();
11353 return FRS_NoViableFunction;
11354 }
11355 OverloadCandidateSet::iterator Best;
11356 OverloadingResult OverloadResult =
11357 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11358
11359 if (OverloadResult == OR_No_Viable_Function) {
11360 *CallExpr = ExprError();
11361 return FRS_NoViableFunction;
11362 }
11363 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11364 Loc, 0, CandidateSet, &Best,
11365 OverloadResult,
11366 /*AllowTypoCorrection=*/false);
11367 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11368 *CallExpr = ExprError();
11369 Diag(Range->getLocStart(), diag::note_in_for_range)
11370 << RangeLoc << BEF << Range->getType();
11371 return FRS_DiagnosticIssued;
11372 }
11373 }
11374 return FRS_Success;
11375}
11376
11377
Douglas Gregorcd695e52008-11-10 20:40:00 +000011378/// FixOverloadedFunctionReference - E is an expression that refers to
11379/// a C++ overloaded function (possibly with some parentheses and
11380/// perhaps a '&' around it). We have resolved the overloaded function
11381/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000011382/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000011383Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000011384 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000011385 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011386 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11387 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011388 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011389 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011390
Douglas Gregor51c538b2009-11-20 19:42:02 +000011391 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011392 }
11393
Douglas Gregor51c538b2009-11-20 19:42:02 +000011394 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000011395 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11396 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011397 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000011398 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000011399 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000011400 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000011401 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011402 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011403
11404 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000011405 ICE->getCastKind(),
11406 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000011407 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011408 }
11409
Douglas Gregor51c538b2009-11-20 19:42:02 +000011410 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000011411 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000011412 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011413 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11414 if (Method->isStatic()) {
11415 // Do nothing: static member functions aren't any different
11416 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000011417 } else {
John McCalle66edc12009-11-24 19:00:30 +000011418 // Fix the sub expression, which really has to be an
11419 // UnresolvedLookupExpr holding an overloaded member function
11420 // or template.
John McCall16df1e52010-03-30 21:47:33 +000011421 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11422 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000011423 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011424 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011425
John McCalld14a8642009-11-21 08:51:07 +000011426 assert(isa<DeclRefExpr>(SubExpr)
11427 && "fixed to something other than a decl ref");
11428 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11429 && "fixed to a member ref with no nested name qualifier");
11430
11431 // We have taken the address of a pointer to member
11432 // function. Perform the computation here so that we get the
11433 // appropriate pointer to member type.
11434 QualType ClassType
11435 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11436 QualType MemPtrType
11437 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11438
John McCall7decc9e2010-11-18 06:31:45 +000011439 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11440 VK_RValue, OK_Ordinary,
11441 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000011442 }
11443 }
John McCall16df1e52010-03-30 21:47:33 +000011444 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11445 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000011446 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000011447 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011448
John McCalle3027922010-08-25 11:45:40 +000011449 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011450 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000011451 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000011452 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011453 }
John McCalld14a8642009-11-21 08:51:07 +000011454
11455 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000011456 // FIXME: avoid copy.
11457 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000011458 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000011459 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11460 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000011461 }
11462
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011463 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11464 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011465 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011466 Fn,
John McCall113bee02012-03-10 09:33:50 +000011467 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011468 ULE->getNameLoc(),
11469 Fn->getType(),
11470 VK_LValue,
11471 Found.getDecl(),
11472 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011473 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011474 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11475 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000011476 }
11477
John McCall10eae182009-11-30 22:42:35 +000011478 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000011479 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000011480 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11481 if (MemExpr->hasExplicitTemplateArgs()) {
11482 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11483 TemplateArgs = &TemplateArgsBuffer;
11484 }
John McCall6b51f282009-11-23 01:53:49 +000011485
John McCall2d74de92009-12-01 22:10:20 +000011486 Expr *Base;
11487
John McCall7decc9e2010-11-18 06:31:45 +000011488 // If we're filling in a static method where we used to have an
11489 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000011490 if (MemExpr->isImplicitAccess()) {
11491 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011492 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11493 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011494 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011495 Fn,
John McCall113bee02012-03-10 09:33:50 +000011496 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011497 MemExpr->getMemberLoc(),
11498 Fn->getType(),
11499 VK_LValue,
11500 Found.getDecl(),
11501 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000011502 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011503 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11504 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000011505 } else {
11506 SourceLocation Loc = MemExpr->getMemberLoc();
11507 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000011508 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000011509 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000011510 Base = new (Context) CXXThisExpr(Loc,
11511 MemExpr->getBaseType(),
11512 /*isImplicit=*/true);
11513 }
John McCall2d74de92009-12-01 22:10:20 +000011514 } else
John McCallc3007a22010-10-26 07:05:15 +000011515 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000011516
John McCall4adb38c2011-04-27 00:36:17 +000011517 ExprValueKind valueKind;
11518 QualType type;
11519 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11520 valueKind = VK_LValue;
11521 type = Fn->getType();
11522 } else {
11523 valueKind = VK_RValue;
11524 type = Context.BoundMemberTy;
11525 }
11526
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011527 MemberExpr *ME = MemberExpr::Create(Context, Base,
11528 MemExpr->isArrow(),
11529 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000011530 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011531 Fn,
11532 Found,
11533 MemExpr->getMemberNameInfo(),
11534 TemplateArgs,
11535 type, valueKind, OK_Ordinary);
11536 ME->setHadMultipleCandidates(true);
Richard Smith4f6a2c42012-11-14 07:06:31 +000011537 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011538 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000011539 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011540
John McCallc3007a22010-10-26 07:05:15 +000011541 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000011542}
11543
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011544ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000011545 DeclAccessPair Found,
11546 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000011547 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000011548}
11549
Douglas Gregor5251f1b2008-10-21 16:13:35 +000011550} // end namespace clang