blob: f8e0819887d9c13da79378e9537be152b99e7b09 [file] [log] [blame]
Nick Lewyckye1121512013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemerc729b0b2013-09-16 22:44:20 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Lex/Preprocessor.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000031#include "llvm/ADT/DenseSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000034#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035#include <algorithm>
36
37namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000038using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000039
Nick Lewycky134af912013-02-07 05:08:22 +000040/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000041static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000042CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
43 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000044 SourceLocation Loc = SourceLocation(),
45 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000046 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000047 return ExprError();
48 // If FoundDecl is different from Fn (such as if one is a template
49 // and the other a specialization), make sure DiagnoseUseOfDecl is
50 // called on both.
51 // FIXME: This would be more comprehensively addressed by modifying
52 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
53 // being used.
54 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000055 return ExprError();
John McCall113bee02012-03-10 09:33:50 +000056 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000057 VK_LValue, Loc, LocInfo);
58 if (HadMultipleCandidates)
59 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000060
61 S.MarkDeclRefReferenced(DRE);
Nick Lewycky134af912013-02-07 05:08:22 +000062
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000063 ExprResult E = S.Owned(DRE);
John Wiegley01296292011-04-08 18:41:53 +000064 E = S.DefaultFunctionArrayConversion(E.take());
65 if (E.isInvalid())
66 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +000067 return E;
John McCall7decc9e2010-11-18 06:31:45 +000068}
69
John McCall5c32be02010-08-24 20:38:10 +000070static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
71 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000072 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000073 bool CStyle,
74 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000075
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000076static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
77 QualType &ToType,
78 bool InOverloadResolution,
79 StandardConversionSequence &SCS,
80 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000081static OverloadingResult
82IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
83 UserDefinedConversionSequence& User,
84 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000085 bool AllowExplicit,
86 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000087
88
89static ImplicitConversionSequence::CompareKind
90CompareStandardConversionSequences(Sema &S,
91 const StandardConversionSequence& SCS1,
92 const StandardConversionSequence& SCS2);
93
94static ImplicitConversionSequence::CompareKind
95CompareQualificationConversions(Sema &S,
96 const StandardConversionSequence& SCS1,
97 const StandardConversionSequence& SCS2);
98
99static ImplicitConversionSequence::CompareKind
100CompareDerivedToBaseConversions(Sema &S,
101 const StandardConversionSequence& SCS1,
102 const StandardConversionSequence& SCS2);
103
104
105
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106/// GetConversionCategory - Retrieve the implicit conversion
107/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +0000108ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109GetConversionCategory(ImplicitConversionKind Kind) {
110 static const ImplicitConversionCategory
111 Category[(int)ICK_Num_Conversion_Kinds] = {
112 ICC_Identity,
113 ICC_Lvalue_Transformation,
114 ICC_Lvalue_Transformation,
115 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000116 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000117 ICC_Qualification_Adjustment,
118 ICC_Promotion,
119 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000120 ICC_Promotion,
121 ICC_Conversion,
122 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000123 ICC_Conversion,
124 ICC_Conversion,
125 ICC_Conversion,
126 ICC_Conversion,
127 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000128 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000129 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000130 ICC_Conversion,
131 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000132 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000133 ICC_Conversion
134 };
135 return Category[(int)Kind];
136}
137
138/// GetConversionRank - Retrieve the implicit conversion rank
139/// corresponding to the given implicit conversion kind.
140ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
141 static const ImplicitConversionRank
142 Rank[(int)ICK_Num_Conversion_Kinds] = {
143 ICR_Exact_Match,
144 ICR_Exact_Match,
145 ICR_Exact_Match,
146 ICR_Exact_Match,
147 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000148 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000149 ICR_Promotion,
150 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000151 ICR_Promotion,
152 ICR_Conversion,
153 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000154 ICR_Conversion,
155 ICR_Conversion,
156 ICR_Conversion,
157 ICR_Conversion,
158 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000159 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000160 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000161 ICR_Conversion,
162 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000163 ICR_Complex_Real_Conversion,
164 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000165 ICR_Conversion,
166 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000167 };
168 return Rank[(int)Kind];
169}
170
171/// GetImplicitConversionName - Return the name of this kind of
172/// implicit conversion.
173const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000174 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000175 "No conversion",
176 "Lvalue-to-rvalue",
177 "Array-to-pointer",
178 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000179 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000180 "Qualification",
181 "Integral promotion",
182 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000183 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000184 "Integral conversion",
185 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000186 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000187 "Floating-integral conversion",
188 "Pointer conversion",
189 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000190 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000191 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000192 "Derived-to-base conversion",
193 "Vector conversion",
194 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000195 "Complex-real conversion",
196 "Block Pointer conversion",
197 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000198 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000199 };
200 return Name[Kind];
201}
202
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000203/// StandardConversionSequence - Set the standard conversion
204/// sequence to the identity conversion.
205void StandardConversionSequence::setAsIdentityConversion() {
206 First = ICK_Identity;
207 Second = ICK_Identity;
208 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000209 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000210 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000211 ReferenceBinding = false;
212 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000213 IsLvalueReference = true;
214 BindsToFunctionLvalue = false;
215 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000216 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000217 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000218 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000219}
220
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221/// getRank - Retrieve the rank of this standard conversion sequence
222/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
223/// implicit conversions.
224ImplicitConversionRank StandardConversionSequence::getRank() const {
225 ImplicitConversionRank Rank = ICR_Exact_Match;
226 if (GetConversionRank(First) > Rank)
227 Rank = GetConversionRank(First);
228 if (GetConversionRank(Second) > Rank)
229 Rank = GetConversionRank(Second);
230 if (GetConversionRank(Third) > Rank)
231 Rank = GetConversionRank(Third);
232 return Rank;
233}
234
235/// isPointerConversionToBool - Determines whether this conversion is
236/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000237/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000238/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000239bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 // Note that FromType has not necessarily been transformed by the
241 // array-to-pointer or function-to-pointer implicit conversions, so
242 // check for their presence as well as checking whether FromType is
243 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000244 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000245 (getFromType()->isPointerType() ||
246 getFromType()->isObjCObjectPointerType() ||
247 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000248 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000249 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
250 return true;
251
252 return false;
253}
254
Douglas Gregor5c407d92008-10-23 00:40:37 +0000255/// isPointerConversionToVoidPointer - Determines whether this
256/// conversion is a conversion of a pointer to a void pointer. This is
257/// used as part of the ranking of standard conversion sequences (C++
258/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000259bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000260StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000261isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000262 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000263 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000264
265 // Note that FromType has not necessarily been transformed by the
266 // array-to-pointer implicit conversion, so check for its presence
267 // and redo the conversion to get a pointer.
268 if (First == ICK_Array_To_Pointer)
269 FromType = Context.getArrayDecayedType(FromType);
270
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000271 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000272 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000273 return ToPtrType->getPointeeType()->isVoidType();
274
275 return false;
276}
277
Richard Smith66e05fe2012-01-18 05:21:49 +0000278/// Skip any implicit casts which could be either part of a narrowing conversion
279/// or after one in an implicit conversion.
280static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
281 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
282 switch (ICE->getCastKind()) {
283 case CK_NoOp:
284 case CK_IntegralCast:
285 case CK_IntegralToBoolean:
286 case CK_IntegralToFloating:
287 case CK_FloatingToIntegral:
288 case CK_FloatingToBoolean:
289 case CK_FloatingCast:
290 Converted = ICE->getSubExpr();
291 continue;
292
293 default:
294 return Converted;
295 }
296 }
297
298 return Converted;
299}
300
301/// Check if this standard conversion sequence represents a narrowing
302/// conversion, according to C++11 [dcl.init.list]p7.
303///
304/// \param Ctx The AST context.
305/// \param Converted The result of applying this standard conversion sequence.
306/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
307/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000308/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
309/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000310NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000311StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
312 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000313 APValue &ConstantValue,
314 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000315 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000316
317 // C++11 [dcl.init.list]p7:
318 // A narrowing conversion is an implicit conversion ...
319 QualType FromType = getToType(0);
320 QualType ToType = getToType(1);
321 switch (Second) {
322 // -- from a floating-point type to an integer type, or
323 //
324 // -- from an integer type or unscoped enumeration type to a floating-point
325 // type, except where the source is a constant expression and the actual
326 // value after conversion will fit into the target type and will produce
327 // the original value when converted back to the original type, or
328 case ICK_Floating_Integral:
329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
330 return NK_Type_Narrowing;
331 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
332 llvm::APSInt IntConstantValue;
333 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
334 if (Initializer &&
335 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
336 // Convert the integer to the floating type.
337 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
338 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
339 llvm::APFloat::rmNearestTiesToEven);
340 // And back.
341 llvm::APSInt ConvertedValue = IntConstantValue;
342 bool ignored;
343 Result.convertToInteger(ConvertedValue,
344 llvm::APFloat::rmTowardZero, &ignored);
345 // If the resulting value is different, this was a narrowing conversion.
346 if (IntConstantValue != ConvertedValue) {
347 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000348 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000349 return NK_Constant_Narrowing;
350 }
351 } else {
352 // Variables are always narrowings.
353 return NK_Variable_Narrowing;
354 }
355 }
356 return NK_Not_Narrowing;
357
358 // -- from long double to double or float, or from double to float, except
359 // where the source is a constant expression and the actual value after
360 // conversion is within the range of values that can be represented (even
361 // if it cannot be represented exactly), or
362 case ICK_Floating_Conversion:
363 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
364 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
365 // FromType is larger than ToType.
366 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
367 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
368 // Constant!
369 assert(ConstantValue.isFloat());
370 llvm::APFloat FloatVal = ConstantValue.getFloat();
371 // Convert the source value into the target type.
372 bool ignored;
373 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
374 Ctx.getFloatTypeSemantics(ToType),
375 llvm::APFloat::rmNearestTiesToEven, &ignored);
376 // If there was no overflow, the source value is within the range of
377 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000378 if (ConvertStatus & llvm::APFloat::opOverflow) {
379 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000380 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000381 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000382 } else {
383 return NK_Variable_Narrowing;
384 }
385 }
386 return NK_Not_Narrowing;
387
388 // -- from an integer type or unscoped enumeration type to an integer type
389 // that cannot represent all the values of the original type, except where
390 // the source is a constant expression and the actual value after
391 // conversion will fit into the target type and will produce the original
392 // value when converted back to the original type.
393 case ICK_Boolean_Conversion: // Bools are integers too.
394 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
395 // Boolean conversions can be from pointers and pointers to members
396 // [conv.bool], and those aren't considered narrowing conversions.
397 return NK_Not_Narrowing;
398 } // Otherwise, fall through to the integral case.
399 case ICK_Integral_Conversion: {
400 assert(FromType->isIntegralOrUnscopedEnumerationType());
401 assert(ToType->isIntegralOrUnscopedEnumerationType());
402 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
403 const unsigned FromWidth = Ctx.getIntWidth(FromType);
404 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
405 const unsigned ToWidth = Ctx.getIntWidth(ToType);
406
407 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000408 (FromWidth == ToWidth && FromSigned != ToSigned) ||
409 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000410 // Not all values of FromType can be represented in ToType.
411 llvm::APSInt InitializerValue;
412 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000413 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
414 // Such conversions on variables are always narrowing.
415 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000416 }
417 bool Narrowing = false;
418 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000419 // Negative -> unsigned is narrowing. Otherwise, more bits is never
420 // narrowing.
421 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000422 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000423 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000424 // Add a bit to the InitializerValue so we don't have to worry about
425 // signed vs. unsigned comparisons.
426 InitializerValue = InitializerValue.extend(
427 InitializerValue.getBitWidth() + 1);
428 // Convert the initializer to and from the target width and signed-ness.
429 llvm::APSInt ConvertedValue = InitializerValue;
430 ConvertedValue = ConvertedValue.trunc(ToWidth);
431 ConvertedValue.setIsSigned(ToSigned);
432 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
433 ConvertedValue.setIsSigned(InitializerValue.isSigned());
434 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000435 if (ConvertedValue != InitializerValue)
436 Narrowing = true;
437 }
438 if (Narrowing) {
439 ConstantType = Initializer->getType();
440 ConstantValue = APValue(InitializerValue);
441 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000442 }
443 }
444 return NK_Not_Narrowing;
445 }
446
447 default:
448 // Other kinds of conversions are not narrowings.
449 return NK_Not_Narrowing;
450 }
451}
452
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000453/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000454/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000455void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000456 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000457 bool PrintedSomething = false;
458 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000459 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000460 PrintedSomething = true;
461 }
462
463 if (Second != 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(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000468
469 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000470 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000471 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000472 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000473 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000474 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000475 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000476 PrintedSomething = true;
477 }
478
479 if (Third != ICK_Identity) {
480 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000481 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000482 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000483 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484 PrintedSomething = true;
485 }
486
487 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000488 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489 }
490}
491
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000492/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000493/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000494void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000495 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000496 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000497 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000498 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000499 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000500 if (ConversionFunction)
501 OS << '\'' << *ConversionFunction << '\'';
502 else
503 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000505 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000506 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000507 }
508}
509
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000510/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000511/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000512void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000513 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000514 if (isStdInitializerListElement())
515 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000516 switch (ConversionKind) {
517 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000518 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000519 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520 break;
521 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000522 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000523 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000524 break;
525 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000526 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000527 break;
John McCall0d1da222010-01-12 00:44:57 +0000528 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000529 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000530 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000531 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000532 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000533 break;
534 }
535
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000536 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000537}
538
John McCall0d1da222010-01-12 00:44:57 +0000539void AmbiguousConversionSequence::construct() {
540 new (&conversions()) ConversionSet();
541}
542
543void AmbiguousConversionSequence::destruct() {
544 conversions().~ConversionSet();
545}
546
547void
548AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
549 FromTypePtr = O.FromTypePtr;
550 ToTypePtr = O.ToTypePtr;
551 new (&conversions()) ConversionSet(O.conversions());
552}
553
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000554namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000555 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000556 // template argument information.
557 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000558 TemplateArgument FirstArg;
559 TemplateArgument SecondArg;
560 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000561 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000562 // template parameter and template argument information.
563 struct DFIParamWithArguments : DFIArguments {
564 TemplateParameter Param;
565 };
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000566}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000567
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000568/// \brief Convert from Sema's representation of template deduction information
569/// to the form used in overload-candidate information.
Larisse Voufo98b20f12013-07-19 23:00:19 +0000570DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
571 Sema::TemplateDeductionResult TDK,
572 TemplateDeductionInfo &Info) {
573 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000574 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000575 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000576 Result.Data = 0;
577 switch (TDK) {
578 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000579 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000580 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000581 case Sema::TDK_TooManyArguments:
582 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000583 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000584
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000585 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000586 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000587 Result.Data = Info.Param.getOpaqueValue();
588 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589
Richard Smith44ecdbd2013-01-31 05:19:49 +0000590 case Sema::TDK_NonDeducedMismatch: {
591 // FIXME: Should allocate from normal heap so that we can free this later.
592 DFIArguments *Saved = new (Context) DFIArguments;
593 Saved->FirstArg = Info.FirstArg;
594 Saved->SecondArg = Info.SecondArg;
595 Result.Data = Saved;
596 break;
597 }
598
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000599 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000600 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000601 // FIXME: Should allocate from normal heap so that we can free this later.
602 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000603 Saved->Param = Info.Param;
604 Saved->FirstArg = Info.FirstArg;
605 Saved->SecondArg = Info.SecondArg;
606 Result.Data = Saved;
607 break;
608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000610 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000611 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000612 if (Info.hasSFINAEDiagnostic()) {
613 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
614 SourceLocation(), PartialDiagnostic::NullDiagnostic());
615 Info.takeSFINAEDiagnostic(*Diag);
616 Result.HasDiagnostic = true;
617 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000618 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000620 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000621 Result.Data = Info.Expression;
622 break;
623
Richard Smith44ecdbd2013-01-31 05:19:49 +0000624 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000625 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000626 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000627
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000628 return Result;
629}
John McCall0d1da222010-01-12 00:44:57 +0000630
Larisse Voufo98b20f12013-07-19 23:00:19 +0000631void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000632 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
633 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000634 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000635 case Sema::TDK_InstantiationDepth:
636 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000637 case Sema::TDK_TooManyArguments:
638 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000639 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000640 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000641 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000643 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000644 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000645 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000646 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000647 Data = 0;
648 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000649
650 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000651 // FIXME: Destroy the template argument list?
Douglas Gregord09efd42010-05-08 20:07:26 +0000652 Data = 0;
Richard Smith9ca64612012-05-07 09:03:25 +0000653 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
654 Diag->~PartialDiagnosticAt();
655 HasDiagnostic = false;
656 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000657 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658
Douglas Gregor461761d2010-05-08 18:20:53 +0000659 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000660 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000661 break;
662 }
663}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000664
Larisse Voufo98b20f12013-07-19 23:00:19 +0000665PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000666 if (HasDiagnostic)
667 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
668 return 0;
669}
670
Larisse Voufo98b20f12013-07-19 23:00:19 +0000671TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000672 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
673 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000674 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000675 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000676 case Sema::TDK_TooManyArguments:
677 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000678 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000679 case Sema::TDK_NonDeducedMismatch:
680 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000681 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000682
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000683 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000684 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000685 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000686
687 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000688 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000689 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000690
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000691 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000692 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000693 break;
694 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000695
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000696 return TemplateParameter();
697}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000698
Larisse Voufo98b20f12013-07-19 23:00:19 +0000699TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000701 case Sema::TDK_Success:
702 case Sema::TDK_Invalid:
703 case Sema::TDK_InstantiationDepth:
704 case Sema::TDK_TooManyArguments:
705 case Sema::TDK_TooFewArguments:
706 case Sema::TDK_Incomplete:
707 case Sema::TDK_InvalidExplicitArguments:
708 case Sema::TDK_Inconsistent:
709 case Sema::TDK_Underqualified:
710 case Sema::TDK_NonDeducedMismatch:
711 case Sema::TDK_FailedOverloadResolution:
712 return 0;
Douglas Gregord09efd42010-05-08 20:07:26 +0000713
Richard Smith44ecdbd2013-01-31 05:19:49 +0000714 case Sema::TDK_SubstitutionFailure:
715 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716
Richard Smith44ecdbd2013-01-31 05:19:49 +0000717 // Unhandled
718 case Sema::TDK_MiscellaneousDeductionFailure:
719 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000720 }
721
722 return 0;
723}
724
Larisse Voufo98b20f12013-07-19 23:00:19 +0000725const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000728 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000729 case Sema::TDK_InstantiationDepth:
730 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000731 case Sema::TDK_TooManyArguments:
732 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000733 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000734 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000735 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000736 return 0;
737
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000738 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000739 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000740 case Sema::TDK_NonDeducedMismatch:
741 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000742
Douglas Gregor461761d2010-05-08 18:20:53 +0000743 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000744 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000745 break;
746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000747
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000748 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000749}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000750
Larisse Voufo98b20f12013-07-19 23:00:19 +0000751const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000752 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
753 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000754 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000755 case Sema::TDK_InstantiationDepth:
756 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000757 case Sema::TDK_TooManyArguments:
758 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000759 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000760 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000761 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000762 return 0;
763
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000764 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000765 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000766 case Sema::TDK_NonDeducedMismatch:
767 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000768
Douglas Gregor461761d2010-05-08 18:20:53 +0000769 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000770 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000771 break;
772 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000773
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000774 return 0;
775}
776
Larisse Voufo98b20f12013-07-19 23:00:19 +0000777Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000778 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
779 Sema::TDK_FailedOverloadResolution)
780 return static_cast<Expr*>(Data);
781
782 return 0;
783}
784
Benjamin Kramer97e59492012-10-09 15:52:25 +0000785void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000786 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000787 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
788 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000789 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
790 i->DeductionFailure.Destroy();
791 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000792}
793
794void OverloadCandidateSet::clear() {
795 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000796 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000797 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000798 Functions.clear();
799}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000800
John McCall4124c492011-10-17 18:40:02 +0000801namespace {
802 class UnbridgedCastsSet {
803 struct Entry {
804 Expr **Addr;
805 Expr *Saved;
806 };
807 SmallVector<Entry, 2> Entries;
808
809 public:
810 void save(Sema &S, Expr *&E) {
811 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
812 Entry entry = { &E, E };
813 Entries.push_back(entry);
814 E = S.stripARCUnbridgedCast(E);
815 }
816
817 void restore() {
818 for (SmallVectorImpl<Entry>::iterator
819 i = Entries.begin(), e = Entries.end(); i != e; ++i)
820 *i->Addr = i->Saved;
821 }
822 };
823}
824
825/// checkPlaceholderForOverload - Do any interesting placeholder-like
826/// preprocessing on the given expression.
827///
828/// \param unbridgedCasts a collection to which to add unbridged casts;
829/// without this, they will be immediately diagnosed as errors
830///
831/// Return true on unrecoverable error.
832static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
833 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000834 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
835 // We can't handle overloaded expressions here because overload
836 // resolution might reasonably tweak them.
837 if (placeholder->getKind() == BuiltinType::Overload) return false;
838
839 // If the context potentially accepts unbridged ARC casts, strip
840 // the unbridged cast and add it to the collection for later restoration.
841 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
842 unbridgedCasts) {
843 unbridgedCasts->save(S, E);
844 return false;
845 }
846
847 // Go ahead and check everything else.
848 ExprResult result = S.CheckPlaceholderExpr(E);
849 if (result.isInvalid())
850 return true;
851
852 E = result.take();
853 return false;
854 }
855
856 // Nothing to do.
857 return false;
858}
859
860/// checkArgPlaceholdersForOverload - Check a set of call operands for
861/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000862static bool checkArgPlaceholdersForOverload(Sema &S,
863 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000864 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000865 for (unsigned i = 0, e = Args.size(); i != e; ++i)
866 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000867 return true;
868
869 return false;
870}
871
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000872// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000873// overload of the declarations in Old. This routine returns false if
874// New and Old cannot be overloaded, e.g., if New has the same
875// signature as some function in Old (C++ 1.3.10) or if the Old
876// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000877// it does return false, MatchedDecl will point to the decl that New
878// cannot be overloaded with. This decl may be a UsingShadowDecl on
879// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000880//
881// Example: Given the following input:
882//
883// void f(int, float); // #1
884// void f(int, int); // #2
885// int f(int, int); // #3
886//
887// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000888// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000889//
John McCall3d988d92009-12-02 08:47:38 +0000890// When we process #2, Old contains only the FunctionDecl for #1. By
891// comparing the parameter types, we see that #1 and #2 are overloaded
892// (since they have different signatures), so this routine returns
893// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000894//
John McCall3d988d92009-12-02 08:47:38 +0000895// When we process #3, Old is an overload set containing #1 and #2. We
896// compare the signatures of #3 to #1 (they're overloaded, so we do
897// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
898// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000899// signature), IsOverload returns false and MatchedDecl will be set to
900// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000901//
902// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
903// into a class by a using declaration. The rules for whether to hide
904// shadow declarations ignore some properties which otherwise figure
905// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000906Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000907Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
908 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000909 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000910 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000911 NamedDecl *OldD = *I;
912
913 bool OldIsUsingDecl = false;
914 if (isa<UsingShadowDecl>(OldD)) {
915 OldIsUsingDecl = true;
916
917 // We can always introduce two using declarations into the same
918 // context, even if they have identical signatures.
919 if (NewIsUsingDecl) continue;
920
921 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
922 }
923
924 // If either declaration was introduced by a using declaration,
925 // we'll need to use slightly different rules for matching.
926 // Essentially, these rules are the normal rules, except that
927 // function templates hide function templates with different
928 // return types or template parameter lists.
929 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000930 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
931 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000932
John McCall3d988d92009-12-02 08:47:38 +0000933 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000934 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
935 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
936 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
937 continue;
938 }
939
John McCalldaa3d6b2009-12-09 03:35:25 +0000940 Match = *I;
941 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000942 }
John McCall3d988d92009-12-02 08:47:38 +0000943 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000944 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
945 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
946 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
947 continue;
948 }
949
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000950 if (!shouldLinkPossiblyHiddenDecl(*I, New))
951 continue;
952
John McCalldaa3d6b2009-12-09 03:35:25 +0000953 Match = *I;
954 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000955 }
John McCalla8987a2942010-11-10 03:01:53 +0000956 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000957 // We can overload with these, which can show up when doing
958 // redeclaration checks for UsingDecls.
959 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000960 } else if (isa<TagDecl>(OldD)) {
961 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000962 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
963 // Optimistically assume that an unresolved using decl will
964 // overload; if it doesn't, we'll have to diagnose during
965 // template instantiation.
966 } else {
John McCall1f82f242009-11-18 22:49:29 +0000967 // (C++ 13p1):
968 // Only function declarations can be overloaded; object and type
969 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000970 Match = *I;
971 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000972 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000973 }
John McCall1f82f242009-11-18 22:49:29 +0000974
John McCalldaa3d6b2009-12-09 03:35:25 +0000975 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000976}
977
Richard Smithac974a32013-06-30 09:48:50 +0000978bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
979 bool UseUsingDeclRules) {
980 // C++ [basic.start.main]p2: This function shall not be overloaded.
981 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000982 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000983
David Majnemerc729b0b2013-09-16 22:44:20 +0000984 // MSVCRT user defined entry points cannot be overloaded.
985 if (New->isMSVCRTEntryPoint())
986 return false;
987
John McCall1f82f242009-11-18 22:49:29 +0000988 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
989 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
990
991 // C++ [temp.fct]p2:
992 // A function template can be overloaded with other function templates
993 // and with normal (non-template) functions.
994 if ((OldTemplate == 0) != (NewTemplate == 0))
995 return true;
996
997 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000998 QualType OldQType = Context.getCanonicalType(Old->getType());
999 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001000
1001 // Compare the signatures (C++ 1.3.10) of the two functions to
1002 // determine whether they are overloads. If we find any mismatch
1003 // in the signature, they are overloads.
1004
1005 // If either of these functions is a K&R-style function (no
1006 // prototype), then we consider them to have matching signatures.
1007 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1008 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1009 return false;
1010
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001011 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1012 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001013
1014 // The signature of a function includes the types of its
1015 // parameters (C++ 1.3.10), which includes the presence or absence
1016 // of the ellipsis; see C++ DR 357).
1017 if (OldQType != NewQType &&
1018 (OldType->getNumArgs() != NewType->getNumArgs() ||
1019 OldType->isVariadic() != NewType->isVariadic() ||
Richard Smithac974a32013-06-30 09:48:50 +00001020 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001021 return true;
1022
1023 // C++ [temp.over.link]p4:
1024 // The signature of a function template consists of its function
1025 // signature, its return type and its template parameter list. The names
1026 // of the template parameters are significant only for establishing the
1027 // relationship between the template parameters and the rest of the
1028 // signature.
1029 //
1030 // We check the return type and template parameter lists for function
1031 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001032 //
1033 // However, we don't consider either of these when deciding whether
1034 // a member introduced by a shadow declaration is hidden.
1035 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001036 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1037 OldTemplate->getTemplateParameters(),
1038 false, TPL_TemplateMatch) ||
John McCall1f82f242009-11-18 22:49:29 +00001039 OldType->getResultType() != NewType->getResultType()))
1040 return true;
1041
1042 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001043 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001044 //
1045 // As part of this, also check whether one of the member functions
1046 // is static, in which case they are not overloads (C++
1047 // 13.1p2). While not part of the definition of the signature,
1048 // this check is important to determine whether these functions
1049 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001050 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1051 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001052 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001053 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1054 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1055 if (!UseUsingDeclRules &&
1056 (OldMethod->getRefQualifier() == RQ_None ||
1057 NewMethod->getRefQualifier() == RQ_None)) {
1058 // C++0x [over.load]p2:
1059 // - Member function declarations with the same name and the same
1060 // parameter-type-list as well as member function template
1061 // declarations with the same name, the same parameter-type-list, and
1062 // the same template parameter lists cannot be overloaded if any of
1063 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001064 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001065 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001066 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001067 }
1068 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001069 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001070
Richard Smith574f4f62013-01-14 05:37:29 +00001071 // We may not have applied the implicit const for a constexpr member
1072 // function yet (because we haven't yet resolved whether this is a static
1073 // or non-static member function). Add it now, on the assumption that this
1074 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001075 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001076 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smithac974a32013-06-30 09:48:50 +00001077 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001078 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001079 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001080
1081 // We do not allow overloading based off of '__restrict'.
1082 OldQuals &= ~Qualifiers::Restrict;
1083 NewQuals &= ~Qualifiers::Restrict;
1084 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001085 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001086 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001087
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001088 // enable_if attributes are an order-sensitive part of the signature.
1089 for (specific_attr_iterator<EnableIfAttr>
1090 NewI = New->specific_attr_begin<EnableIfAttr>(),
1091 NewE = New->specific_attr_end<EnableIfAttr>(),
1092 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1093 OldE = Old->specific_attr_end<EnableIfAttr>();
1094 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1095 if (NewI == NewE || OldI == OldE)
1096 return true;
1097 llvm::FoldingSetNodeID NewID, OldID;
1098 NewI->getCond()->Profile(NewID, Context, true);
1099 OldI->getCond()->Profile(OldID, Context, true);
1100 if (!(NewID == OldID))
1101 return true;
1102 }
1103
John McCall1f82f242009-11-18 22:49:29 +00001104 // The signatures match; this is not an overload.
1105 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001106}
1107
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001108/// \brief Checks availability of the function depending on the current
1109/// function context. Inside an unavailable function, unavailability is ignored.
1110///
1111/// \returns true if \arg FD is unavailable and current context is inside
1112/// an available function, false otherwise.
1113bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1114 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1115}
1116
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001117/// \brief Tries a user-defined conversion from From to ToType.
1118///
1119/// Produces an implicit conversion sequence for when a standard conversion
1120/// is not an option. See TryImplicitConversion for more information.
1121static ImplicitConversionSequence
1122TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1123 bool SuppressUserConversions,
1124 bool AllowExplicit,
1125 bool InOverloadResolution,
1126 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001127 bool AllowObjCWritebackConversion,
1128 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001129 ImplicitConversionSequence ICS;
1130
1131 if (SuppressUserConversions) {
1132 // We're not in the case above, so there is no conversion that
1133 // we can perform.
1134 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1135 return ICS;
1136 }
1137
1138 // Attempt user-defined conversion.
1139 OverloadCandidateSet Conversions(From->getExprLoc());
1140 OverloadingResult UserDefResult
1141 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001142 AllowExplicit, AllowObjCConversionOnExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001143
1144 if (UserDefResult == OR_Success) {
1145 ICS.setUserDefined();
1146 // C++ [over.ics.user]p4:
1147 // A conversion of an expression of class type to the same class
1148 // type is given Exact Match rank, and a conversion of an
1149 // expression of class type to a base class of that type is
1150 // given Conversion rank, in spite of the fact that a copy
1151 // constructor (i.e., a user-defined conversion function) is
1152 // called for those cases.
1153 if (CXXConstructorDecl *Constructor
1154 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1155 QualType FromCanon
1156 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1157 QualType ToCanon
1158 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1159 if (Constructor->isCopyConstructor() &&
1160 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1161 // Turn this into a "standard" conversion sequence, so that it
1162 // gets ranked with standard conversion sequences.
1163 ICS.setStandard();
1164 ICS.Standard.setAsIdentityConversion();
1165 ICS.Standard.setFromType(From->getType());
1166 ICS.Standard.setAllToTypes(ToType);
1167 ICS.Standard.CopyConstructor = Constructor;
1168 if (ToCanon != FromCanon)
1169 ICS.Standard.Second = ICK_Derived_To_Base;
1170 }
1171 }
1172
1173 // C++ [over.best.ics]p4:
1174 // However, when considering the argument of a user-defined
1175 // conversion function that is a candidate by 13.3.1.3 when
1176 // invoked for the copying of the temporary in the second step
1177 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1178 // 13.3.1.6 in all cases, only standard conversion sequences and
1179 // ellipsis conversion sequences are allowed.
1180 if (SuppressUserConversions && ICS.isUserDefined()) {
1181 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1182 }
1183 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1184 ICS.setAmbiguous();
1185 ICS.Ambiguous.setFromType(From->getType());
1186 ICS.Ambiguous.setToType(ToType);
1187 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1188 Cand != Conversions.end(); ++Cand)
1189 if (Cand->Viable)
1190 ICS.Ambiguous.addConversion(Cand->Function);
1191 } else {
1192 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1193 }
1194
1195 return ICS;
1196}
1197
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001198/// TryImplicitConversion - Attempt to perform an implicit conversion
1199/// from the given expression (Expr) to the given type (ToType). This
1200/// function returns an implicit conversion sequence that can be used
1201/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001202///
1203/// void f(float f);
1204/// void g(int i) { f(i); }
1205///
1206/// this routine would produce an implicit conversion sequence to
1207/// describe the initialization of f from i, which will be a standard
1208/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1209/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1210//
1211/// Note that this routine only determines how the conversion can be
1212/// performed; it does not actually perform the conversion. As such,
1213/// it will not produce any diagnostics if no conversion is available,
1214/// but will instead return an implicit conversion sequence of kind
1215/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001216///
1217/// If @p SuppressUserConversions, then user-defined conversions are
1218/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001219/// If @p AllowExplicit, then explicit user-defined conversions are
1220/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001221///
1222/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1223/// writeback conversion, which allows __autoreleasing id* parameters to
1224/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001225static ImplicitConversionSequence
1226TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1227 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001228 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001229 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001230 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001231 bool AllowObjCWritebackConversion,
1232 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001233 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001234 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001235 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001236 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001237 return ICS;
1238 }
1239
David Blaikiebbafb8a2012-03-11 07:00:24 +00001240 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001241 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001242 return ICS;
1243 }
1244
Douglas Gregor836a7e82010-08-11 02:15:33 +00001245 // C++ [over.ics.user]p4:
1246 // A conversion of an expression of class type to the same class
1247 // type is given Exact Match rank, and a conversion of an
1248 // expression of class type to a base class of that type is
1249 // given Conversion rank, in spite of the fact that a copy/move
1250 // constructor (i.e., a user-defined conversion function) is
1251 // called for those cases.
1252 QualType FromType = From->getType();
1253 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001254 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1255 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001256 ICS.setStandard();
1257 ICS.Standard.setAsIdentityConversion();
1258 ICS.Standard.setFromType(FromType);
1259 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001260
Douglas Gregor5ab11652010-04-17 22:01:05 +00001261 // We don't actually check at this point whether there is a valid
1262 // copy/move constructor, since overloading just assumes that it
1263 // exists. When we actually perform initialization, we'll find the
1264 // appropriate constructor to copy the returned object, if needed.
1265 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001266
Douglas Gregor5ab11652010-04-17 22:01:05 +00001267 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001268 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001269 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001270
Douglas Gregor836a7e82010-08-11 02:15:33 +00001271 return ICS;
1272 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001273
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001274 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1275 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001276 AllowObjCWritebackConversion,
1277 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001278}
1279
John McCall31168b02011-06-15 23:02:42 +00001280ImplicitConversionSequence
1281Sema::TryImplicitConversion(Expr *From, QualType ToType,
1282 bool SuppressUserConversions,
1283 bool AllowExplicit,
1284 bool InOverloadResolution,
1285 bool CStyle,
1286 bool AllowObjCWritebackConversion) {
1287 return clang::TryImplicitConversion(*this, From, ToType,
1288 SuppressUserConversions, AllowExplicit,
1289 InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001290 AllowObjCWritebackConversion,
1291 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001292}
1293
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001294/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001295/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001296/// converted expression. Flavor is the kind of conversion we're
1297/// performing, used in the error message. If @p AllowExplicit,
1298/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001299ExprResult
1300Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001301 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001302 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001303 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001304}
1305
John Wiegley01296292011-04-08 18:41:53 +00001306ExprResult
1307Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001308 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001309 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001310 if (checkPlaceholderForOverload(*this, From))
1311 return ExprError();
1312
John McCall31168b02011-06-15 23:02:42 +00001313 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1314 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001315 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001316 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001317 if (getLangOpts().ObjC1)
1318 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1319 ToType, From->getType(), From);
John McCall5c32be02010-08-24 20:38:10 +00001320 ICS = clang::TryImplicitConversion(*this, From, ToType,
1321 /*SuppressUserConversions=*/false,
1322 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001323 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001324 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001325 AllowObjCWritebackConversion,
1326 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001327 return PerformImplicitConversion(From, ToType, ICS, Action);
1328}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001329
1330/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001331/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001332bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1333 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001334 if (Context.hasSameUnqualifiedType(FromType, ToType))
1335 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001336
John McCall991eb4b2010-12-21 00:44:39 +00001337 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1338 // where F adds one of the following at most once:
1339 // - a pointer
1340 // - a member pointer
1341 // - a block pointer
1342 CanQualType CanTo = Context.getCanonicalType(ToType);
1343 CanQualType CanFrom = Context.getCanonicalType(FromType);
1344 Type::TypeClass TyClass = CanTo->getTypeClass();
1345 if (TyClass != CanFrom->getTypeClass()) return false;
1346 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1347 if (TyClass == Type::Pointer) {
1348 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1349 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1350 } else if (TyClass == Type::BlockPointer) {
1351 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1352 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1353 } else if (TyClass == Type::MemberPointer) {
1354 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1355 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1356 } else {
1357 return false;
1358 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001359
John McCall991eb4b2010-12-21 00:44:39 +00001360 TyClass = CanTo->getTypeClass();
1361 if (TyClass != CanFrom->getTypeClass()) return false;
1362 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1363 return false;
1364 }
1365
1366 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1367 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1368 if (!EInfo.getNoReturn()) return false;
1369
1370 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1371 assert(QualType(FromFn, 0).isCanonical());
1372 if (QualType(FromFn, 0) != CanTo) return false;
1373
1374 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001375 return true;
1376}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001377
Douglas Gregor46188682010-05-18 22:42:18 +00001378/// \brief Determine whether the conversion from FromType to ToType is a valid
1379/// vector conversion.
1380///
1381/// \param ICK Will be set to the vector conversion kind, if this is a vector
1382/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001383static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1384 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001385 // We need at least one of these types to be a vector type to have a vector
1386 // conversion.
1387 if (!ToType->isVectorType() && !FromType->isVectorType())
1388 return false;
1389
1390 // Identical types require no conversions.
1391 if (Context.hasSameUnqualifiedType(FromType, ToType))
1392 return false;
1393
1394 // There are no conversions between extended vector types, only identity.
1395 if (ToType->isExtVectorType()) {
1396 // There are no conversions between extended vector types other than the
1397 // identity conversion.
1398 if (FromType->isExtVectorType())
1399 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001400
Douglas Gregor46188682010-05-18 22:42:18 +00001401 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001402 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001403 ICK = ICK_Vector_Splat;
1404 return true;
1405 }
1406 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001407
1408 // We can perform the conversion between vector types in the following cases:
1409 // 1)vector types are equivalent AltiVec and GCC vector types
1410 // 2)lax vector conversions are permitted and the vector types are of the
1411 // same size
1412 if (ToType->isVectorType() && FromType->isVectorType()) {
1413 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001414 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruth9c524c12010-08-08 05:02:51 +00001415 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001416 ICK = ICK_Vector_Conversion;
1417 return true;
1418 }
Douglas Gregor46188682010-05-18 22:42:18 +00001419 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001420
Douglas Gregor46188682010-05-18 22:42:18 +00001421 return false;
1422}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001423
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001424static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1425 bool InOverloadResolution,
1426 StandardConversionSequence &SCS,
1427 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001428
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001429/// IsStandardConversion - Determines whether there is a standard
1430/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1431/// expression From to the type ToType. Standard conversion sequences
1432/// only consider non-class types; for conversions that involve class
1433/// types, use TryImplicitConversion. If a conversion exists, SCS will
1434/// contain the standard conversion sequence required to perform this
1435/// conversion and this routine will return true. Otherwise, this
1436/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001437static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1438 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001439 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001440 bool CStyle,
1441 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001442 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001443
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001444 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001445 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001446 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001447 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001448 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001449 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001450
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001451 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001452 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001453 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001454 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001455 return false;
1456
Mike Stump11289f42009-09-09 15:08:12 +00001457 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001458 }
1459
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001460 // The first conversion can be an lvalue-to-rvalue conversion,
1461 // array-to-pointer conversion, or function-to-pointer conversion
1462 // (C++ 4p1).
1463
John McCall5c32be02010-08-24 20:38:10 +00001464 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001465 DeclAccessPair AccessPair;
1466 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001467 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001468 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001469 // We were able to resolve the address of the overloaded function,
1470 // so we can convert to the type of that function.
1471 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001472
1473 // we can sometimes resolve &foo<int> regardless of ToType, so check
1474 // if the type matches (identity) or we are converting to bool
1475 if (!S.Context.hasSameUnqualifiedType(
1476 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1477 QualType resultTy;
1478 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001479 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001480 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1481 // otherwise, only a boolean conversion is standard
1482 if (!ToType->isBooleanType())
1483 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001484 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001485
Chandler Carruthffce2452011-03-29 08:08:18 +00001486 // Check if the "from" expression is taking the address of an overloaded
1487 // function and recompute the FromType accordingly. Take advantage of the
1488 // fact that non-static member functions *must* have such an address-of
1489 // expression.
1490 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1491 if (Method && !Method->isStatic()) {
1492 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1493 "Non-unary operator on non-static member address");
1494 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1495 == UO_AddrOf &&
1496 "Non-address-of operator on non-static member address");
1497 const Type *ClassType
1498 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1499 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001500 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1501 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1502 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001503 "Non-address-of operator for overloaded function expression");
1504 FromType = S.Context.getPointerType(FromType);
1505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001506
Douglas Gregor980fb162010-04-29 18:24:40 +00001507 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001508 assert(S.Context.hasSameType(
1509 FromType,
1510 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001511 } else {
1512 return false;
1513 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001514 }
John McCall154a2fd2011-08-30 00:57:29 +00001515 // Lvalue-to-rvalue conversion (C++11 4.1):
1516 // A glvalue (3.10) of a non-function, non-array type T can
1517 // be converted to a prvalue.
1518 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001519 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001520 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001521 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001522 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001523
Douglas Gregorc79862f2012-04-12 17:51:55 +00001524 // C11 6.3.2.1p2:
1525 // ... if the lvalue has atomic type, the value has the non-atomic version
1526 // of the type of the lvalue ...
1527 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1528 FromType = Atomic->getValueType();
1529
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001530 // If T is a non-class type, the type of the rvalue is the
1531 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001532 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1533 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001534 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001535 } else if (FromType->isArrayType()) {
1536 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001537 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001538
1539 // An lvalue or rvalue of type "array of N T" or "array of unknown
1540 // bound of T" can be converted to an rvalue of type "pointer to
1541 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001542 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001543
John McCall5c32be02010-08-24 20:38:10 +00001544 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001545 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001546 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001547
1548 // For the purpose of ranking in overload resolution
1549 // (13.3.3.1.1), this conversion is considered an
1550 // array-to-pointer conversion followed by a qualification
1551 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001552 SCS.Second = ICK_Identity;
1553 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001554 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001555 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001556 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001557 }
John McCall086a4642010-11-24 05:12:34 +00001558 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001559 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001560 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001561
1562 // An lvalue of function type T can be converted to an rvalue of
1563 // type "pointer to T." The result is a pointer to the
1564 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001565 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001566 } else {
1567 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001568 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001569 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001570 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001571
1572 // The second conversion can be an integral promotion, floating
1573 // point promotion, integral conversion, floating point conversion,
1574 // floating-integral conversion, pointer conversion,
1575 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001576 // For overloading in C, this can also be a "compatible-type"
1577 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001578 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001579 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001580 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001581 // The unqualified versions of the types are the same: there's no
1582 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001583 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001584 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001585 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001586 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001587 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001588 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001589 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001590 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001591 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001592 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001593 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001594 SCS.Second = ICK_Complex_Promotion;
1595 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001596 } else if (ToType->isBooleanType() &&
1597 (FromType->isArithmeticType() ||
1598 FromType->isAnyPointerType() ||
1599 FromType->isBlockPointerType() ||
1600 FromType->isMemberPointerType() ||
1601 FromType->isNullPtrType())) {
1602 // Boolean conversions (C++ 4.12).
1603 SCS.Second = ICK_Boolean_Conversion;
1604 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001605 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001606 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001607 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001608 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001609 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001610 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001611 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001612 SCS.Second = ICK_Complex_Conversion;
1613 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001614 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1615 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001616 // Complex-real conversions (C99 6.3.1.7)
1617 SCS.Second = ICK_Complex_Real;
1618 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001619 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001620 // Floating point conversions (C++ 4.8).
1621 SCS.Second = ICK_Floating_Conversion;
1622 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001623 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001624 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001625 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001626 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001627 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001628 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001629 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001630 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001631 SCS.Second = ICK_Block_Pointer_Conversion;
1632 } else if (AllowObjCWritebackConversion &&
1633 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1634 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001635 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1636 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001637 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001638 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001639 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001640 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001641 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001642 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001643 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001644 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001645 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001646 SCS.Second = SecondICK;
1647 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001648 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001649 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001650 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001651 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001652 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001653 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001654 // Treat a conversion that strips "noreturn" as an identity conversion.
1655 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001656 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1657 InOverloadResolution,
1658 SCS, CStyle)) {
1659 SCS.Second = ICK_TransparentUnionConversion;
1660 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001661 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1662 CStyle)) {
1663 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001664 // appropriately.
1665 return true;
Guy Benyei259f9f42013-02-07 16:05:33 +00001666 } else if (ToType->isEventT() &&
1667 From->isIntegerConstantExpr(S.getASTContext()) &&
1668 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1669 SCS.Second = ICK_Zero_Event_Conversion;
1670 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001671 } else {
1672 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001673 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001674 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001675 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001676
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001677 QualType CanonFrom;
1678 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001679 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001680 bool ObjCLifetimeConversion;
1681 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1682 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001683 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001684 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001685 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001686 CanonFrom = S.Context.getCanonicalType(FromType);
1687 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001688 } else {
1689 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001690 SCS.Third = ICK_Identity;
1691
Mike Stump11289f42009-09-09 15:08:12 +00001692 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001693 // [...] Any difference in top-level cv-qualification is
1694 // subsumed by the initialization itself and does not constitute
1695 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001696 CanonFrom = S.Context.getCanonicalType(FromType);
1697 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001698 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001699 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001700 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001701 FromType = ToType;
1702 CanonFrom = CanonTo;
1703 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001704 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001705 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001706
1707 // If we have not converted the argument type to the parameter type,
1708 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001709 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001710 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001711
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001712 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001713}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001714
1715static bool
1716IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1717 QualType &ToType,
1718 bool InOverloadResolution,
1719 StandardConversionSequence &SCS,
1720 bool CStyle) {
1721
1722 const RecordType *UT = ToType->getAsUnionType();
1723 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1724 return false;
1725 // The field to initialize within the transparent union.
1726 RecordDecl *UD = UT->getDecl();
1727 // It's compatible if the expression matches any of the fields.
1728 for (RecordDecl::field_iterator it = UD->field_begin(),
1729 itend = UD->field_end();
1730 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001731 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1732 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001733 ToType = it->getType();
1734 return true;
1735 }
1736 }
1737 return false;
1738}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001739
1740/// IsIntegralPromotion - Determines whether the conversion from the
1741/// expression From (whose potentially-adjusted type is FromType) to
1742/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1743/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001744bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001745 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001746 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001747 if (!To) {
1748 return false;
1749 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001750
1751 // An rvalue of type char, signed char, unsigned char, short int, or
1752 // unsigned short int can be converted to an rvalue of type int if
1753 // int can represent all the values of the source type; otherwise,
1754 // the source rvalue can be converted to an rvalue of type unsigned
1755 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001756 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1757 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001758 if (// We can promote any signed, promotable integer type to an int
1759 (FromType->isSignedIntegerType() ||
1760 // We can promote any unsigned integer type whose size is
1761 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001762 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001763 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001764 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001765 }
1766
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001767 return To->getKind() == BuiltinType::UInt;
1768 }
1769
Richard Smithb9c5a602012-09-13 21:18:54 +00001770 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001771 // A prvalue of an unscoped enumeration type whose underlying type is not
1772 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1773 // following types that can represent all the values of the enumeration
1774 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1775 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001776 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001777 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001778 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001779 // with lowest integer conversion rank (4.13) greater than the rank of long
1780 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001781 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001782 // C++11 [conv.prom]p4:
1783 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1784 // can be converted to a prvalue of its underlying type. Moreover, if
1785 // integral promotion can be applied to its underlying type, a prvalue of an
1786 // unscoped enumeration type whose underlying type is fixed can also be
1787 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001788 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1789 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1790 // provided for a scoped enumeration.
1791 if (FromEnumType->getDecl()->isScoped())
1792 return false;
1793
Richard Smithb9c5a602012-09-13 21:18:54 +00001794 // We can perform an integral promotion to the underlying type of the enum,
1795 // even if that's not the promoted type.
1796 if (FromEnumType->getDecl()->isFixed()) {
1797 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1798 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1799 IsIntegralPromotion(From, Underlying, ToType);
1800 }
1801
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001802 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001803 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001804 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001805 return Context.hasSameUnqualifiedType(ToType,
1806 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001807 }
John McCall56774992009-12-09 09:09:27 +00001808
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001809 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001810 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1811 // to an rvalue a prvalue of the first of the following types that can
1812 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001813 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001814 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001815 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001816 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001817 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001818 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001819 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001820 // Determine whether the type we're converting from is signed or
1821 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001822 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001823 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001824
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001825 // The types we'll try to promote to, in the appropriate
1826 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001827 QualType PromoteTypes[6] = {
1828 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001829 Context.LongTy, Context.UnsignedLongTy ,
1830 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001831 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001832 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001833 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1834 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001835 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001836 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1837 // We found the type that we can promote to. If this is the
1838 // type we wanted, we have a promotion. Otherwise, no
1839 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001840 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001841 }
1842 }
1843 }
1844
1845 // An rvalue for an integral bit-field (9.6) can be converted to an
1846 // rvalue of type int if int can represent all the values of the
1847 // bit-field; otherwise, it can be converted to unsigned int if
1848 // unsigned int can represent all the values of the bit-field. If
1849 // the bit-field is larger yet, no integral promotion applies to
1850 // it. If the bit-field has an enumerated type, it is treated as any
1851 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001852 // FIXME: We should delay checking of bit-fields until we actually perform the
1853 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001854 using llvm::APSInt;
1855 if (From)
John McCalld25db7e2013-05-06 21:39:12 +00001856 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001857 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001858 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001859 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1860 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1861 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001862
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001863 // Are we promoting to an int from a bitfield that fits in an int?
1864 if (BitWidth < ToSize ||
1865 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1866 return To->getKind() == BuiltinType::Int;
1867 }
Mike Stump11289f42009-09-09 15:08:12 +00001868
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001869 // Are we promoting to an unsigned int from an unsigned bitfield
1870 // that fits into an unsigned int?
1871 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1872 return To->getKind() == BuiltinType::UInt;
1873 }
Mike Stump11289f42009-09-09 15:08:12 +00001874
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001875 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001876 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001877 }
Mike Stump11289f42009-09-09 15:08:12 +00001878
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001879 // An rvalue of type bool can be converted to an rvalue of type int,
1880 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001881 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001882 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001883 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001884
1885 return false;
1886}
1887
1888/// IsFloatingPointPromotion - Determines whether the conversion from
1889/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1890/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001891bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001892 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1893 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001894 /// An rvalue of type float can be converted to an rvalue of type
1895 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001896 if (FromBuiltin->getKind() == BuiltinType::Float &&
1897 ToBuiltin->getKind() == BuiltinType::Double)
1898 return true;
1899
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001900 // C99 6.3.1.5p1:
1901 // When a float is promoted to double or long double, or a
1902 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001903 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001904 (FromBuiltin->getKind() == BuiltinType::Float ||
1905 FromBuiltin->getKind() == BuiltinType::Double) &&
1906 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1907 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001908
1909 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001910 if (!getLangOpts().NativeHalfType &&
1911 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001912 ToBuiltin->getKind() == BuiltinType::Float)
1913 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001914 }
1915
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001916 return false;
1917}
1918
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001919/// \brief Determine if a conversion is a complex promotion.
1920///
1921/// A complex promotion is defined as a complex -> complex conversion
1922/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001923/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001924bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001925 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001926 if (!FromComplex)
1927 return false;
1928
John McCall9dd450b2009-09-21 23:43:11 +00001929 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001930 if (!ToComplex)
1931 return false;
1932
1933 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001934 ToComplex->getElementType()) ||
1935 IsIntegralPromotion(0, FromComplex->getElementType(),
1936 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001937}
1938
Douglas Gregor237f96c2008-11-26 23:31:11 +00001939/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1940/// the pointer type FromPtr to a pointer to type ToPointee, with the
1941/// same type qualifiers as FromPtr has on its pointee type. ToType,
1942/// if non-empty, will be a pointer to ToType that may or may not have
1943/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001944///
Mike Stump11289f42009-09-09 15:08:12 +00001945static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001946BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001947 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001948 ASTContext &Context,
1949 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001950 assert((FromPtr->getTypeClass() == Type::Pointer ||
1951 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1952 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001953
John McCall31168b02011-06-15 23:02:42 +00001954 /// Conversions to 'id' subsume cv-qualifier conversions.
1955 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001956 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001957
1958 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001959 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001960 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001961 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001962
John McCall31168b02011-06-15 23:02:42 +00001963 if (StripObjCLifetime)
1964 Quals.removeObjCLifetime();
1965
Mike Stump11289f42009-09-09 15:08:12 +00001966 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001967 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001968 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001969 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001970 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001971
1972 // Build a pointer to ToPointee. It has the right qualifiers
1973 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001974 if (isa<ObjCObjectPointerType>(ToType))
1975 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001976 return Context.getPointerType(ToPointee);
1977 }
1978
1979 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001980 QualType QualifiedCanonToPointee
1981 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001983 if (isa<ObjCObjectPointerType>(ToType))
1984 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1985 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001986}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001987
Mike Stump11289f42009-09-09 15:08:12 +00001988static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001989 bool InOverloadResolution,
1990 ASTContext &Context) {
1991 // Handle value-dependent integral null pointer constants correctly.
1992 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1993 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001994 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001995 return !InOverloadResolution;
1996
Douglas Gregor56751b52009-09-25 04:25:58 +00001997 return Expr->isNullPointerConstant(Context,
1998 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1999 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002000}
Mike Stump11289f42009-09-09 15:08:12 +00002001
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002002/// IsPointerConversion - Determines whether the conversion of the
2003/// expression From, which has the (possibly adjusted) type FromType,
2004/// can be converted to the type ToType via a pointer conversion (C++
2005/// 4.10). If so, returns true and places the converted type (that
2006/// might differ from ToType in its cv-qualifiers at some level) into
2007/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002008///
Douglas Gregora29dc052008-11-27 01:19:21 +00002009/// This routine also supports conversions to and from block pointers
2010/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2011/// pointers to interfaces. FIXME: Once we've determined the
2012/// appropriate overloading rules for Objective-C, we may want to
2013/// split the Objective-C checks into a different routine; however,
2014/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002015/// conversions, so for now they live here. IncompatibleObjC will be
2016/// set if the conversion is an allowed Objective-C conversion that
2017/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002018bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002019 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002020 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002021 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002022 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002023 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2024 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002025 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002026
Mike Stump11289f42009-09-09 15:08:12 +00002027 // Conversion from a null pointer constant to any Objective-C pointer type.
2028 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002029 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002030 ConvertedType = ToType;
2031 return true;
2032 }
2033
Douglas Gregor231d1c62008-11-27 00:15:41 +00002034 // Blocks: Block pointers can be converted to void*.
2035 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002036 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002037 ConvertedType = ToType;
2038 return true;
2039 }
2040 // Blocks: A null pointer constant can be converted to a block
2041 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002042 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002043 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002044 ConvertedType = ToType;
2045 return true;
2046 }
2047
Sebastian Redl576fd422009-05-10 18:38:11 +00002048 // If the left-hand-side is nullptr_t, the right side can be a null
2049 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002050 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002051 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002052 ConvertedType = ToType;
2053 return true;
2054 }
2055
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002056 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002057 if (!ToTypePtr)
2058 return false;
2059
2060 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002061 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002062 ConvertedType = ToType;
2063 return true;
2064 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002065
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002066 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002067 // , including objective-c pointers.
2068 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002069 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002070 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002071 ConvertedType = BuildSimilarlyQualifiedPointerType(
2072 FromType->getAs<ObjCObjectPointerType>(),
2073 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002074 ToType, Context);
2075 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002076 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002077 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002078 if (!FromTypePtr)
2079 return false;
2080
2081 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002082
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002083 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002084 // pointer conversion, so don't do all of the work below.
2085 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2086 return false;
2087
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002088 // An rvalue of type "pointer to cv T," where T is an object type,
2089 // can be converted to an rvalue of type "pointer to cv void" (C++
2090 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002091 if (FromPointeeType->isIncompleteOrObjectType() &&
2092 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002093 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002094 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002095 ToType, Context,
2096 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002097 return true;
2098 }
2099
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002100 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002101 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002102 ToPointeeType->isVoidType()) {
2103 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2104 ToPointeeType,
2105 ToType, Context);
2106 return true;
2107 }
2108
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002109 // When we're overloading in C, we allow a special kind of pointer
2110 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002111 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002112 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002113 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002114 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002115 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002116 return true;
2117 }
2118
Douglas Gregor5c407d92008-10-23 00:40:37 +00002119 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002120 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002121 // An rvalue of type "pointer to cv D," where D is a class type,
2122 // can be converted to an rvalue of type "pointer to cv B," where
2123 // B is a base class (clause 10) of D. If B is an inaccessible
2124 // (clause 11) or ambiguous (10.2) base class of D, a program that
2125 // necessitates this conversion is ill-formed. The result of the
2126 // conversion is a pointer to the base class sub-object of the
2127 // derived class object. The null pointer value is converted to
2128 // the null pointer value of the destination type.
2129 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002130 // Note that we do not check for ambiguity or inaccessibility
2131 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002132 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002133 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002134 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002135 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002136 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002137 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002138 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002139 ToType, Context);
2140 return true;
2141 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002142
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002143 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2144 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2145 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2146 ToPointeeType,
2147 ToType, Context);
2148 return true;
2149 }
2150
Douglas Gregora119f102008-12-19 19:13:09 +00002151 return false;
2152}
Douglas Gregoraec25842011-04-26 23:16:46 +00002153
2154/// \brief Adopt the given qualifiers for the given type.
2155static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2156 Qualifiers TQs = T.getQualifiers();
2157
2158 // Check whether qualifiers already match.
2159 if (TQs == Qs)
2160 return T;
2161
2162 if (Qs.compatiblyIncludes(TQs))
2163 return Context.getQualifiedType(T, Qs);
2164
2165 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2166}
Douglas Gregora119f102008-12-19 19:13:09 +00002167
2168/// isObjCPointerConversion - Determines whether this is an
2169/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2170/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002171bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002172 QualType& ConvertedType,
2173 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002174 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002175 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002176
Douglas Gregoraec25842011-04-26 23:16:46 +00002177 // The set of qualifiers on the type we're converting from.
2178 Qualifiers FromQualifiers = FromType.getQualifiers();
2179
Steve Naroff7cae42b2009-07-10 23:34:53 +00002180 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002181 const ObjCObjectPointerType* ToObjCPtr =
2182 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002183 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002184 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002185
Steve Naroff7cae42b2009-07-10 23:34:53 +00002186 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002187 // If the pointee types are the same (ignoring qualifications),
2188 // then this is not a pointer conversion.
2189 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2190 FromObjCPtr->getPointeeType()))
2191 return false;
2192
Douglas Gregoraec25842011-04-26 23:16:46 +00002193 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002194 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002195 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002196 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002197 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002198 return true;
2199 }
2200 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002201 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002202 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002203 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002204 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002205 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002206 return true;
2207 }
2208 // Objective C++: We're able to convert from a pointer to an
2209 // interface to a pointer to a different interface.
2210 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002211 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2212 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002213 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002214 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2215 FromObjCPtr->getPointeeType()))
2216 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002217 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002218 ToObjCPtr->getPointeeType(),
2219 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002220 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002221 return true;
2222 }
2223
2224 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2225 // Okay: this is some kind of implicit downcast of Objective-C
2226 // interfaces, which is permitted. However, we're going to
2227 // complain about it.
2228 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002229 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002230 ToObjCPtr->getPointeeType(),
2231 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002232 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002233 return true;
2234 }
Mike Stump11289f42009-09-09 15:08:12 +00002235 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002236 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002237 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002238 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002239 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002240 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002241 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002242 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002243 // to a block pointer type.
2244 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002245 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002246 return true;
2247 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002248 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002249 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002250 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002251 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002252 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002253 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002254 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002255 return true;
2256 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002257 else
Douglas Gregora119f102008-12-19 19:13:09 +00002258 return false;
2259
Douglas Gregor033f56d2008-12-23 00:53:59 +00002260 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002261 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002262 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002263 else if (const BlockPointerType *FromBlockPtr =
2264 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002265 FromPointeeType = FromBlockPtr->getPointeeType();
2266 else
Douglas Gregora119f102008-12-19 19:13:09 +00002267 return false;
2268
Douglas Gregora119f102008-12-19 19:13:09 +00002269 // If we have pointers to pointers, recursively check whether this
2270 // is an Objective-C conversion.
2271 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2272 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2273 IncompatibleObjC)) {
2274 // We always complain about this conversion.
2275 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002276 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002277 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002278 return true;
2279 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002280 // Allow conversion of pointee being objective-c pointer to another one;
2281 // as in I* to id.
2282 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2283 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2284 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2285 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002286
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002287 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002288 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002289 return true;
2290 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002291
Douglas Gregor033f56d2008-12-23 00:53:59 +00002292 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002293 // differences in the argument and result types are in Objective-C
2294 // pointer conversions. If so, we permit the conversion (but
2295 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002296 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002297 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002298 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002299 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002300 if (FromFunctionType && ToFunctionType) {
2301 // If the function types are exactly the same, this isn't an
2302 // Objective-C pointer conversion.
2303 if (Context.getCanonicalType(FromPointeeType)
2304 == Context.getCanonicalType(ToPointeeType))
2305 return false;
2306
2307 // Perform the quick checks that will tell us whether these
2308 // function types are obviously different.
2309 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2310 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2311 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2312 return false;
2313
2314 bool HasObjCConversion = false;
2315 if (Context.getCanonicalType(FromFunctionType->getResultType())
2316 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2317 // Okay, the types match exactly. Nothing to do.
2318 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2319 ToFunctionType->getResultType(),
2320 ConvertedType, IncompatibleObjC)) {
2321 // Okay, we have an Objective-C pointer conversion.
2322 HasObjCConversion = true;
2323 } else {
2324 // Function types are too different. Abort.
2325 return false;
2326 }
Mike Stump11289f42009-09-09 15:08:12 +00002327
Douglas Gregora119f102008-12-19 19:13:09 +00002328 // Check argument types.
2329 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2330 ArgIdx != NumArgs; ++ArgIdx) {
2331 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2332 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2333 if (Context.getCanonicalType(FromArgType)
2334 == Context.getCanonicalType(ToArgType)) {
2335 // Okay, the types match exactly. Nothing to do.
2336 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2337 ConvertedType, IncompatibleObjC)) {
2338 // Okay, we have an Objective-C pointer conversion.
2339 HasObjCConversion = true;
2340 } else {
2341 // Argument types are too different. Abort.
2342 return false;
2343 }
2344 }
2345
2346 if (HasObjCConversion) {
2347 // We had an Objective-C conversion. Allow this pointer
2348 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002349 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002350 IncompatibleObjC = true;
2351 return true;
2352 }
2353 }
2354
Sebastian Redl72b597d2009-01-25 19:43:20 +00002355 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002356}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002357
John McCall31168b02011-06-15 23:02:42 +00002358/// \brief Determine whether this is an Objective-C writeback conversion,
2359/// used for parameter passing when performing automatic reference counting.
2360///
2361/// \param FromType The type we're converting form.
2362///
2363/// \param ToType The type we're converting to.
2364///
2365/// \param ConvertedType The type that will be produced after applying
2366/// this conversion.
2367bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2368 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002369 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002370 Context.hasSameUnqualifiedType(FromType, ToType))
2371 return false;
2372
2373 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2374 QualType ToPointee;
2375 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2376 ToPointee = ToPointer->getPointeeType();
2377 else
2378 return false;
2379
2380 Qualifiers ToQuals = ToPointee.getQualifiers();
2381 if (!ToPointee->isObjCLifetimeType() ||
2382 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002383 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002384 return false;
2385
2386 // Argument must be a pointer to __strong to __weak.
2387 QualType FromPointee;
2388 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2389 FromPointee = FromPointer->getPointeeType();
2390 else
2391 return false;
2392
2393 Qualifiers FromQuals = FromPointee.getQualifiers();
2394 if (!FromPointee->isObjCLifetimeType() ||
2395 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2396 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2397 return false;
2398
2399 // Make sure that we have compatible qualifiers.
2400 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2401 if (!ToQuals.compatiblyIncludes(FromQuals))
2402 return false;
2403
2404 // Remove qualifiers from the pointee type we're converting from; they
2405 // aren't used in the compatibility check belong, and we'll be adding back
2406 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2407 FromPointee = FromPointee.getUnqualifiedType();
2408
2409 // The unqualified form of the pointee types must be compatible.
2410 ToPointee = ToPointee.getUnqualifiedType();
2411 bool IncompatibleObjC;
2412 if (Context.typesAreCompatible(FromPointee, ToPointee))
2413 FromPointee = ToPointee;
2414 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2415 IncompatibleObjC))
2416 return false;
2417
2418 /// \brief Construct the type we're converting to, which is a pointer to
2419 /// __autoreleasing pointee.
2420 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2421 ConvertedType = Context.getPointerType(FromPointee);
2422 return true;
2423}
2424
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002425bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2426 QualType& ConvertedType) {
2427 QualType ToPointeeType;
2428 if (const BlockPointerType *ToBlockPtr =
2429 ToType->getAs<BlockPointerType>())
2430 ToPointeeType = ToBlockPtr->getPointeeType();
2431 else
2432 return false;
2433
2434 QualType FromPointeeType;
2435 if (const BlockPointerType *FromBlockPtr =
2436 FromType->getAs<BlockPointerType>())
2437 FromPointeeType = FromBlockPtr->getPointeeType();
2438 else
2439 return false;
2440 // We have pointer to blocks, check whether the only
2441 // differences in the argument and result types are in Objective-C
2442 // pointer conversions. If so, we permit the conversion.
2443
2444 const FunctionProtoType *FromFunctionType
2445 = FromPointeeType->getAs<FunctionProtoType>();
2446 const FunctionProtoType *ToFunctionType
2447 = ToPointeeType->getAs<FunctionProtoType>();
2448
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002449 if (!FromFunctionType || !ToFunctionType)
2450 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002451
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002452 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002453 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002454
2455 // Perform the quick checks that will tell us whether these
2456 // function types are obviously different.
2457 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2458 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2459 return false;
2460
2461 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2462 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2463 if (FromEInfo != ToEInfo)
2464 return false;
2465
2466 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002467 if (Context.hasSameType(FromFunctionType->getResultType(),
2468 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002469 // Okay, the types match exactly. Nothing to do.
2470 } else {
2471 QualType RHS = FromFunctionType->getResultType();
2472 QualType LHS = ToFunctionType->getResultType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002473 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002474 !RHS.hasQualifiers() && LHS.hasQualifiers())
2475 LHS = LHS.getUnqualifiedType();
2476
2477 if (Context.hasSameType(RHS,LHS)) {
2478 // OK exact match.
2479 } else if (isObjCPointerConversion(RHS, LHS,
2480 ConvertedType, IncompatibleObjC)) {
2481 if (IncompatibleObjC)
2482 return false;
2483 // Okay, we have an Objective-C pointer conversion.
2484 }
2485 else
2486 return false;
2487 }
2488
2489 // Check argument types.
2490 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2491 ArgIdx != NumArgs; ++ArgIdx) {
2492 IncompatibleObjC = false;
2493 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2494 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2495 if (Context.hasSameType(FromArgType, ToArgType)) {
2496 // Okay, the types match exactly. Nothing to do.
2497 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2498 ConvertedType, IncompatibleObjC)) {
2499 if (IncompatibleObjC)
2500 return false;
2501 // Okay, we have an Objective-C pointer conversion.
2502 } else
2503 // Argument types are too different. Abort.
2504 return false;
2505 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002506 if (LangOpts.ObjCAutoRefCount &&
2507 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2508 ToFunctionType))
2509 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002510
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002511 ConvertedType = ToType;
2512 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002513}
2514
Richard Trieucaff2472011-11-23 22:32:32 +00002515enum {
2516 ft_default,
2517 ft_different_class,
2518 ft_parameter_arity,
2519 ft_parameter_mismatch,
2520 ft_return_type,
2521 ft_qualifer_mismatch
2522};
2523
2524/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2525/// function types. Catches different number of parameter, mismatch in
2526/// parameter types, and different return types.
2527void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2528 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002529 // If either type is not valid, include no extra info.
2530 if (FromType.isNull() || ToType.isNull()) {
2531 PDiag << ft_default;
2532 return;
2533 }
2534
Richard Trieucaff2472011-11-23 22:32:32 +00002535 // Get the function type from the pointers.
2536 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2537 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2538 *ToMember = ToType->getAs<MemberPointerType>();
2539 if (FromMember->getClass() != ToMember->getClass()) {
2540 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2541 << QualType(FromMember->getClass(), 0);
2542 return;
2543 }
2544 FromType = FromMember->getPointeeType();
2545 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002546 }
2547
Richard Trieu96ed5b62011-12-13 23:19:45 +00002548 if (FromType->isPointerType())
2549 FromType = FromType->getPointeeType();
2550 if (ToType->isPointerType())
2551 ToType = ToType->getPointeeType();
2552
2553 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002554 FromType = FromType.getNonReferenceType();
2555 ToType = ToType.getNonReferenceType();
2556
Richard Trieucaff2472011-11-23 22:32:32 +00002557 // Don't print extra info for non-specialized template functions.
2558 if (FromType->isInstantiationDependentType() &&
2559 !FromType->getAs<TemplateSpecializationType>()) {
2560 PDiag << ft_default;
2561 return;
2562 }
2563
Richard Trieu96ed5b62011-12-13 23:19:45 +00002564 // No extra info for same types.
2565 if (Context.hasSameType(FromType, ToType)) {
2566 PDiag << ft_default;
2567 return;
2568 }
2569
Richard Trieucaff2472011-11-23 22:32:32 +00002570 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2571 *ToFunction = ToType->getAs<FunctionProtoType>();
2572
2573 // Both types need to be function types.
2574 if (!FromFunction || !ToFunction) {
2575 PDiag << ft_default;
2576 return;
2577 }
2578
2579 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2580 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2581 << FromFunction->getNumArgs();
2582 return;
2583 }
2584
2585 // Handle different parameter types.
2586 unsigned ArgPos;
2587 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2588 PDiag << ft_parameter_mismatch << ArgPos + 1
2589 << ToFunction->getArgType(ArgPos)
2590 << FromFunction->getArgType(ArgPos);
2591 return;
2592 }
2593
2594 // Handle different return type.
2595 if (!Context.hasSameType(FromFunction->getResultType(),
2596 ToFunction->getResultType())) {
2597 PDiag << ft_return_type << ToFunction->getResultType()
2598 << FromFunction->getResultType();
2599 return;
2600 }
2601
2602 unsigned FromQuals = FromFunction->getTypeQuals(),
2603 ToQuals = ToFunction->getTypeQuals();
2604 if (FromQuals != ToQuals) {
2605 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2606 return;
2607 }
2608
2609 // Unable to find a difference, so add no extra info.
2610 PDiag << ft_default;
2611}
2612
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002613/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002614/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002615/// they have same number of arguments. If the parameters are different,
2616/// ArgPos will have the parameter index of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002617bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002618 const FunctionProtoType *NewType,
2619 unsigned *ArgPos) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002620 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2621 N = NewType->arg_type_begin(),
2622 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002623 if (!Context.hasSameType(O->getUnqualifiedType(),
2624 N->getUnqualifiedType())) {
Larisse Voufo4154f462013-08-06 03:57:41 +00002625 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2626 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002627 }
2628 }
2629 return true;
2630}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002631
Douglas Gregor39c16d42008-10-24 04:54:22 +00002632/// CheckPointerConversion - Check the pointer conversion from the
2633/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002634/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002635/// conversions for which IsPointerConversion has already returned
2636/// true. It returns true and produces a diagnostic if there was an
2637/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002638bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002639 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002640 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002641 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002642 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002643 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002644
John McCall8cb679e2010-11-15 09:13:47 +00002645 Kind = CK_BitCast;
2646
David Blaikie1c7c8f72012-08-08 17:33:31 +00002647 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2648 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2649 Expr::NPCK_ZeroExpression) {
2650 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2651 DiagRuntimeBehavior(From->getExprLoc(), From,
2652 PDiag(diag::warn_impcast_bool_to_null_pointer)
2653 << ToType << From->getSourceRange());
2654 else if (!isUnevaluatedContext())
2655 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2656 << ToType << From->getSourceRange();
2657 }
John McCall9320b872011-09-09 05:25:32 +00002658 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2659 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002660 QualType FromPointeeType = FromPtrType->getPointeeType(),
2661 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002662
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002663 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2664 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002665 // We must have a derived-to-base conversion. Check an
2666 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002667 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2668 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002669 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002670 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002671 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002672
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002673 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002674 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002675 }
2676 }
John McCall9320b872011-09-09 05:25:32 +00002677 } else if (const ObjCObjectPointerType *ToPtrType =
2678 ToType->getAs<ObjCObjectPointerType>()) {
2679 if (const ObjCObjectPointerType *FromPtrType =
2680 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002681 // Objective-C++ conversions are always okay.
2682 // FIXME: We should have a different class of conversions for the
2683 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002684 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002685 return false;
John McCall9320b872011-09-09 05:25:32 +00002686 } else if (FromType->isBlockPointerType()) {
2687 Kind = CK_BlockPointerToObjCPointerCast;
2688 } else {
2689 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002690 }
John McCall9320b872011-09-09 05:25:32 +00002691 } else if (ToType->isBlockPointerType()) {
2692 if (!FromType->isBlockPointerType())
2693 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002694 }
John McCall8cb679e2010-11-15 09:13:47 +00002695
2696 // We shouldn't fall into this case unless it's valid for other
2697 // reasons.
2698 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2699 Kind = CK_NullToPointer;
2700
Douglas Gregor39c16d42008-10-24 04:54:22 +00002701 return false;
2702}
2703
Sebastian Redl72b597d2009-01-25 19:43:20 +00002704/// IsMemberPointerConversion - Determines whether the conversion of the
2705/// expression From, which has the (possibly adjusted) type FromType, can be
2706/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2707/// If so, returns true and places the converted type (that might differ from
2708/// ToType in its cv-qualifiers at some level) into ConvertedType.
2709bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002710 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002711 bool InOverloadResolution,
2712 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002713 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002714 if (!ToTypePtr)
2715 return false;
2716
2717 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002718 if (From->isNullPointerConstant(Context,
2719 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2720 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002721 ConvertedType = ToType;
2722 return true;
2723 }
2724
2725 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002726 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002727 if (!FromTypePtr)
2728 return false;
2729
2730 // A pointer to member of B can be converted to a pointer to member of D,
2731 // where D is derived from B (C++ 4.11p2).
2732 QualType FromClass(FromTypePtr->getClass(), 0);
2733 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002734
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002735 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002736 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002737 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002738 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2739 ToClass.getTypePtr());
2740 return true;
2741 }
2742
2743 return false;
2744}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002745
Sebastian Redl72b597d2009-01-25 19:43:20 +00002746/// CheckMemberPointerConversion - Check the member pointer conversion from the
2747/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002748/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002749/// for which IsMemberPointerConversion has already returned true. It returns
2750/// true and produces a diagnostic if there was an error, or returns false
2751/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002752bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002753 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002754 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002755 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002756 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002757 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002758 if (!FromPtrType) {
2759 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002760 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002761 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002762 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002763 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002764 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002765 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002766
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002767 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002768 assert(ToPtrType && "No member pointer cast has a target type "
2769 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002770
Sebastian Redled8f2002009-01-28 18:33:18 +00002771 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2772 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002773
Sebastian Redled8f2002009-01-28 18:33:18 +00002774 // FIXME: What about dependent types?
2775 assert(FromClass->isRecordType() && "Pointer into non-class.");
2776 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002777
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002778 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002779 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002780 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2781 assert(DerivationOkay &&
2782 "Should not have been called if derivation isn't OK.");
2783 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002784
Sebastian Redled8f2002009-01-28 18:33:18 +00002785 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2786 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002787 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2788 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2789 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2790 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002791 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002792
Douglas Gregor89ee6822009-02-28 01:32:25 +00002793 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002794 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2795 << FromClass << ToClass << QualType(VBase, 0)
2796 << From->getSourceRange();
2797 return true;
2798 }
2799
John McCall5b0829a2010-02-10 09:31:12 +00002800 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002801 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2802 Paths.front(),
2803 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002804
Anders Carlssond7923c62009-08-22 23:33:40 +00002805 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002806 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002807 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002808 return false;
2809}
2810
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002811/// Determine whether the lifetime conversion between the two given
2812/// qualifiers sets is nontrivial.
2813static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2814 Qualifiers ToQuals) {
2815 // Converting anything to const __unsafe_unretained is trivial.
2816 if (ToQuals.hasConst() &&
2817 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2818 return false;
2819
2820 return true;
2821}
2822
Douglas Gregor9a657932008-10-21 23:43:52 +00002823/// IsQualificationConversion - Determines whether the conversion from
2824/// an rvalue of type FromType to ToType is a qualification conversion
2825/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002826///
2827/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2828/// when the qualification conversion involves a change in the Objective-C
2829/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002830bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002831Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002832 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002833 FromType = Context.getCanonicalType(FromType);
2834 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002835 ObjCLifetimeConversion = false;
2836
Douglas Gregor9a657932008-10-21 23:43:52 +00002837 // If FromType and ToType are the same type, this is not a
2838 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002839 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002840 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002841
Douglas Gregor9a657932008-10-21 23:43:52 +00002842 // (C++ 4.4p4):
2843 // A conversion can add cv-qualifiers at levels other than the first
2844 // in multi-level pointers, subject to the following rules: [...]
2845 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002846 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002847 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002848 // Within each iteration of the loop, we check the qualifiers to
2849 // determine if this still looks like a qualification
2850 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002851 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002852 // until there are no more pointers or pointers-to-members left to
2853 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002854 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002855
Douglas Gregor90609aa2011-04-25 18:40:17 +00002856 Qualifiers FromQuals = FromType.getQualifiers();
2857 Qualifiers ToQuals = ToType.getQualifiers();
2858
John McCall31168b02011-06-15 23:02:42 +00002859 // Objective-C ARC:
2860 // Check Objective-C lifetime conversions.
2861 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2862 UnwrappedAnyPointer) {
2863 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002864 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2865 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002866 FromQuals.removeObjCLifetime();
2867 ToQuals.removeObjCLifetime();
2868 } else {
2869 // Qualification conversions cannot cast between different
2870 // Objective-C lifetime qualifiers.
2871 return false;
2872 }
2873 }
2874
Douglas Gregorf30053d2011-05-08 06:09:53 +00002875 // Allow addition/removal of GC attributes but not changing GC attributes.
2876 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2877 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2878 FromQuals.removeObjCGCAttr();
2879 ToQuals.removeObjCGCAttr();
2880 }
2881
Douglas Gregor9a657932008-10-21 23:43:52 +00002882 // -- for every j > 0, if const is in cv 1,j then const is in cv
2883 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002884 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002885 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002886
Douglas Gregor9a657932008-10-21 23:43:52 +00002887 // -- if the cv 1,j and cv 2,j are different, then const is in
2888 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002889 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002890 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002891 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002892
Douglas Gregor9a657932008-10-21 23:43:52 +00002893 // Keep track of whether all prior cv-qualifiers in the "to" type
2894 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002895 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002896 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002897 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002898
2899 // We are left with FromType and ToType being the pointee types
2900 // after unwrapping the original FromType and ToType the same number
2901 // of types. If we unwrapped any pointers, and if FromType and
2902 // ToType have the same unqualified type (since we checked
2903 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002904 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002905}
2906
Douglas Gregorc79862f2012-04-12 17:51:55 +00002907/// \brief - Determine whether this is a conversion from a scalar type to an
2908/// atomic type.
2909///
2910/// If successful, updates \c SCS's second and third steps in the conversion
2911/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002912static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2913 bool InOverloadResolution,
2914 StandardConversionSequence &SCS,
2915 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002916 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2917 if (!ToAtomic)
2918 return false;
2919
2920 StandardConversionSequence InnerSCS;
2921 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2922 InOverloadResolution, InnerSCS,
2923 CStyle, /*AllowObjCWritebackConversion=*/false))
2924 return false;
2925
2926 SCS.Second = InnerSCS.Second;
2927 SCS.setToType(1, InnerSCS.getToType(1));
2928 SCS.Third = InnerSCS.Third;
2929 SCS.QualificationIncludesObjCLifetime
2930 = InnerSCS.QualificationIncludesObjCLifetime;
2931 SCS.setToType(2, InnerSCS.getToType(2));
2932 return true;
2933}
2934
Sebastian Redle5417162012-03-27 18:33:03 +00002935static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2936 CXXConstructorDecl *Constructor,
2937 QualType Type) {
2938 const FunctionProtoType *CtorType =
2939 Constructor->getType()->getAs<FunctionProtoType>();
2940 if (CtorType->getNumArgs() > 0) {
2941 QualType FirstArg = CtorType->getArgType(0);
2942 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2943 return true;
2944 }
2945 return false;
2946}
2947
Sebastian Redl82ace982012-02-11 23:51:08 +00002948static OverloadingResult
2949IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2950 CXXRecordDecl *To,
2951 UserDefinedConversionSequence &User,
2952 OverloadCandidateSet &CandidateSet,
2953 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002954 DeclContext::lookup_result R = S.LookupConstructors(To);
2955 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002956 Con != ConEnd; ++Con) {
2957 NamedDecl *D = *Con;
2958 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2959
2960 // Find the constructor (which may be a template).
2961 CXXConstructorDecl *Constructor = 0;
2962 FunctionTemplateDecl *ConstructorTmpl
2963 = dyn_cast<FunctionTemplateDecl>(D);
2964 if (ConstructorTmpl)
2965 Constructor
2966 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2967 else
2968 Constructor = cast<CXXConstructorDecl>(D);
2969
2970 bool Usable = !Constructor->isInvalidDecl() &&
2971 S.isInitListConstructor(Constructor) &&
2972 (AllowExplicit || !Constructor->isExplicit());
2973 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002974 // If the first argument is (a reference to) the target type,
2975 // suppress conversions.
2976 bool SuppressUserConversions =
2977 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002978 if (ConstructorTmpl)
2979 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2980 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002981 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002982 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002983 else
2984 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002985 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002986 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002987 }
2988 }
2989
2990 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2991
2992 OverloadCandidateSet::iterator Best;
2993 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2994 case OR_Success: {
2995 // Record the standard conversion we used and the conversion function.
2996 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002997 QualType ThisType = Constructor->getThisType(S.Context);
2998 // Initializer lists don't have conversions as such.
2999 User.Before.setAsIdentityConversion();
3000 User.HadMultipleCandidates = HadMultipleCandidates;
3001 User.ConversionFunction = Constructor;
3002 User.FoundConversionFunction = Best->FoundDecl;
3003 User.After.setAsIdentityConversion();
3004 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3005 User.After.setAllToTypes(ToType);
3006 return OR_Success;
3007 }
3008
3009 case OR_No_Viable_Function:
3010 return OR_No_Viable_Function;
3011 case OR_Deleted:
3012 return OR_Deleted;
3013 case OR_Ambiguous:
3014 return OR_Ambiguous;
3015 }
3016
3017 llvm_unreachable("Invalid OverloadResult!");
3018}
3019
Douglas Gregor576e98c2009-01-30 23:27:23 +00003020/// Determines whether there is a user-defined conversion sequence
3021/// (C++ [over.ics.user]) that converts expression From to the type
3022/// ToType. If such a conversion exists, User will contain the
3023/// user-defined conversion sequence that performs such a conversion
3024/// and this routine will return true. Otherwise, this routine returns
3025/// false and User is unspecified.
3026///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003027/// \param AllowExplicit true if the conversion should consider C++0x
3028/// "explicit" conversion functions as well as non-explicit conversion
3029/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003030///
3031/// \param AllowObjCConversionOnExplicit true if the conversion should
3032/// allow an extra Objective-C pointer conversion on uses of explicit
3033/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003034static OverloadingResult
3035IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003036 UserDefinedConversionSequence &User,
3037 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003038 bool AllowExplicit,
3039 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003040 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003041
Douglas Gregor5ab11652010-04-17 22:01:05 +00003042 // Whether we will only visit constructors.
3043 bool ConstructorsOnly = false;
3044
3045 // If the type we are conversion to is a class type, enumerate its
3046 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003047 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003048 // C++ [over.match.ctor]p1:
3049 // When objects of class type are direct-initialized (8.5), or
3050 // copy-initialized from an expression of the same or a
3051 // derived class type (8.5), overload resolution selects the
3052 // constructor. [...] For copy-initialization, the candidate
3053 // functions are all the converting constructors (12.3.1) of
3054 // that class. The argument list is the expression-list within
3055 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003056 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003057 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003058 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003059 ConstructorsOnly = true;
3060
Benjamin Kramer90633e32012-11-23 17:04:52 +00003061 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003062 // RequireCompleteType may have returned true due to some invalid decl
3063 // during template instantiation, but ToType may be complete enough now
3064 // to try to recover.
3065 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003066 // We're not going to find any constructors.
3067 } else if (CXXRecordDecl *ToRecordDecl
3068 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003069
3070 Expr **Args = &From;
3071 unsigned NumArgs = 1;
3072 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003073 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003074 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003075 OverloadingResult Result = IsInitializerListConstructorConversion(
3076 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3077 if (Result != OR_No_Viable_Function)
3078 return Result;
3079 // Never mind.
3080 CandidateSet.clear();
3081
3082 // If we're list-initializing, we pass the individual elements as
3083 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003084 Args = InitList->getInits();
3085 NumArgs = InitList->getNumInits();
3086 ListInitializing = true;
3087 }
3088
David Blaikieff7d47a2012-12-19 00:45:41 +00003089 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3090 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003091 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003092 NamedDecl *D = *Con;
3093 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3094
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003095 // Find the constructor (which may be a template).
3096 CXXConstructorDecl *Constructor = 0;
3097 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003098 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003099 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003100 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003101 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3102 else
John McCalla0296f72010-03-19 07:35:19 +00003103 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003104
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003105 bool Usable = !Constructor->isInvalidDecl();
3106 if (ListInitializing)
3107 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3108 else
3109 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3110 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003111 bool SuppressUserConversions = !ConstructorsOnly;
3112 if (SuppressUserConversions && ListInitializing) {
3113 SuppressUserConversions = false;
3114 if (NumArgs == 1) {
3115 // If the first argument is (a reference to) the target type,
3116 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003117 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3118 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003119 }
3120 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003121 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003122 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3123 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003124 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003125 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003126 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003127 // Allow one user-defined conversion when user specifies a
3128 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003129 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003130 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003131 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003132 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003133 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003134 }
3135 }
3136
Douglas Gregor5ab11652010-04-17 22:01:05 +00003137 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003138 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003139 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003140 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003141 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003142 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003143 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003144 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3145 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003146 std::pair<CXXRecordDecl::conversion_iterator,
3147 CXXRecordDecl::conversion_iterator>
3148 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3149 for (CXXRecordDecl::conversion_iterator
3150 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003151 DeclAccessPair FoundDecl = I.getPair();
3152 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003153 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3154 if (isa<UsingShadowDecl>(D))
3155 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3156
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003157 CXXConversionDecl *Conv;
3158 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003159 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3160 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003161 else
John McCallda4458e2010-03-31 01:36:47 +00003162 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003163
3164 if (AllowExplicit || !Conv->isExplicit()) {
3165 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003166 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3167 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003168 CandidateSet,
3169 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003170 else
John McCall5c32be02010-08-24 20:38:10 +00003171 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003172 From, ToType, CandidateSet,
3173 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003174 }
3175 }
3176 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003177 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003178
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003179 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3180
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003181 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003182 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003183 case OR_Success:
3184 // Record the standard conversion we used and the conversion function.
3185 if (CXXConstructorDecl *Constructor
3186 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3187 // C++ [over.ics.user]p1:
3188 // If the user-defined conversion is specified by a
3189 // constructor (12.3.1), the initial standard conversion
3190 // sequence converts the source type to the type required by
3191 // the argument of the constructor.
3192 //
3193 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003194 if (isa<InitListExpr>(From)) {
3195 // Initializer lists don't have conversions as such.
3196 User.Before.setAsIdentityConversion();
3197 } else {
3198 if (Best->Conversions[0].isEllipsis())
3199 User.EllipsisConversion = true;
3200 else {
3201 User.Before = Best->Conversions[0].Standard;
3202 User.EllipsisConversion = false;
3203 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003204 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003205 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003206 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003207 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003208 User.After.setAsIdentityConversion();
3209 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3210 User.After.setAllToTypes(ToType);
3211 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003212 }
3213 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003214 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3215 // C++ [over.ics.user]p1:
3216 //
3217 // [...] If the user-defined conversion is specified by a
3218 // conversion function (12.3.2), the initial standard
3219 // conversion sequence converts the source type to the
3220 // implicit object parameter of the conversion function.
3221 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003222 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003223 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003224 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003225 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003226
John McCall5c32be02010-08-24 20:38:10 +00003227 // C++ [over.ics.user]p2:
3228 // The second standard conversion sequence converts the
3229 // result of the user-defined conversion to the target type
3230 // for the sequence. Since an implicit conversion sequence
3231 // is an initialization, the special rules for
3232 // initialization by user-defined conversion apply when
3233 // selecting the best user-defined conversion for a
3234 // user-defined conversion sequence (see 13.3.3 and
3235 // 13.3.3.1).
3236 User.After = Best->FinalConversion;
3237 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003238 }
David Blaikie8a40f702012-01-17 06:56:22 +00003239 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003240
John McCall5c32be02010-08-24 20:38:10 +00003241 case OR_No_Viable_Function:
3242 return OR_No_Viable_Function;
3243 case OR_Deleted:
3244 // No conversion here! We're done.
3245 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003246
John McCall5c32be02010-08-24 20:38:10 +00003247 case OR_Ambiguous:
3248 return OR_Ambiguous;
3249 }
3250
David Blaikie8a40f702012-01-17 06:56:22 +00003251 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003252}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003253
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003254bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003255Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003256 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003257 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003258 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003259 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003260 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003261 if (OvResult == OR_Ambiguous)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003262 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003263 diag::err_typecheck_ambiguous_condition)
3264 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003265 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003266 if (!RequireCompleteType(From->getLocStart(), ToType,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003267 diag::err_typecheck_nonviable_condition_incomplete,
3268 From->getType(), From->getSourceRange()))
3269 Diag(From->getLocStart(),
3270 diag::err_typecheck_nonviable_condition)
3271 << From->getType() << From->getSourceRange() << ToType;
3272 }
Fariborz Jahanian76197412009-11-18 18:26:29 +00003273 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003274 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003275 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003276 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003277}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003278
Douglas Gregor2837aa22012-02-22 17:32:19 +00003279/// \brief Compare the user-defined conversion functions or constructors
3280/// of two user-defined conversion sequences to determine whether any ordering
3281/// is possible.
3282static ImplicitConversionSequence::CompareKind
3283compareConversionFunctions(Sema &S,
3284 FunctionDecl *Function1,
3285 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003286 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003287 return ImplicitConversionSequence::Indistinguishable;
3288
3289 // Objective-C++:
3290 // If both conversion functions are implicitly-declared conversions from
3291 // a lambda closure type to a function pointer and a block pointer,
3292 // respectively, always prefer the conversion to a function pointer,
3293 // because the function pointer is more lightweight and is more likely
3294 // to keep code working.
3295 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3296 if (!Conv1)
3297 return ImplicitConversionSequence::Indistinguishable;
3298
3299 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3300 if (!Conv2)
3301 return ImplicitConversionSequence::Indistinguishable;
3302
3303 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3304 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3305 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3306 if (Block1 != Block2)
3307 return Block1? ImplicitConversionSequence::Worse
3308 : ImplicitConversionSequence::Better;
3309 }
3310
3311 return ImplicitConversionSequence::Indistinguishable;
3312}
3313
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003314/// CompareImplicitConversionSequences - Compare two implicit
3315/// conversion sequences to determine whether one is better than the
3316/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003317static ImplicitConversionSequence::CompareKind
3318CompareImplicitConversionSequences(Sema &S,
3319 const ImplicitConversionSequence& ICS1,
3320 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003321{
3322 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3323 // conversion sequences (as defined in 13.3.3.1)
3324 // -- a standard conversion sequence (13.3.3.1.1) is a better
3325 // conversion sequence than a user-defined conversion sequence or
3326 // an ellipsis conversion sequence, and
3327 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3328 // conversion sequence than an ellipsis conversion sequence
3329 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003330 //
John McCall0d1da222010-01-12 00:44:57 +00003331 // C++0x [over.best.ics]p10:
3332 // For the purpose of ranking implicit conversion sequences as
3333 // described in 13.3.3.2, the ambiguous conversion sequence is
3334 // treated as a user-defined sequence that is indistinguishable
3335 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00003336 if (ICS1.getKindRank() < ICS2.getKindRank())
3337 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003338 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003339 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003340
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003341 // The following checks require both conversion sequences to be of
3342 // the same kind.
3343 if (ICS1.getKind() != ICS2.getKind())
3344 return ImplicitConversionSequence::Indistinguishable;
3345
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003346 ImplicitConversionSequence::CompareKind Result =
3347 ImplicitConversionSequence::Indistinguishable;
3348
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003349 // Two implicit conversion sequences of the same form are
3350 // indistinguishable conversion sequences unless one of the
3351 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003352 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003353 Result = CompareStandardConversionSequences(S,
3354 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003355 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003356 // User-defined conversion sequence U1 is a better conversion
3357 // sequence than another user-defined conversion sequence U2 if
3358 // they contain the same user-defined conversion function or
3359 // constructor and if the second standard conversion sequence of
3360 // U1 is better than the second standard conversion sequence of
3361 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003362 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003363 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003364 Result = CompareStandardConversionSequences(S,
3365 ICS1.UserDefined.After,
3366 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003367 else
3368 Result = compareConversionFunctions(S,
3369 ICS1.UserDefined.ConversionFunction,
3370 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003371 }
3372
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003373 // List-initialization sequence L1 is a better conversion sequence than
3374 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3375 // for some X and L2 does not.
3376 if (Result == ImplicitConversionSequence::Indistinguishable &&
Richard Smitha93f1022013-09-06 22:30:28 +00003377 !ICS1.isBad()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003378 if (ICS1.isStdInitializerListElement() &&
3379 !ICS2.isStdInitializerListElement())
3380 return ImplicitConversionSequence::Better;
3381 if (!ICS1.isStdInitializerListElement() &&
3382 ICS2.isStdInitializerListElement())
3383 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003384 }
3385
3386 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003387}
3388
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003389static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3390 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3391 Qualifiers Quals;
3392 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003393 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003394 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003395
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003396 return Context.hasSameUnqualifiedType(T1, T2);
3397}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003398
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003399// Per 13.3.3.2p3, compare the given standard conversion sequences to
3400// determine if one is a proper subset of the other.
3401static ImplicitConversionSequence::CompareKind
3402compareStandardConversionSubsets(ASTContext &Context,
3403 const StandardConversionSequence& SCS1,
3404 const StandardConversionSequence& SCS2) {
3405 ImplicitConversionSequence::CompareKind Result
3406 = ImplicitConversionSequence::Indistinguishable;
3407
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003409 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003410 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3411 return ImplicitConversionSequence::Better;
3412 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3413 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003414
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003415 if (SCS1.Second != SCS2.Second) {
3416 if (SCS1.Second == ICK_Identity)
3417 Result = ImplicitConversionSequence::Better;
3418 else if (SCS2.Second == ICK_Identity)
3419 Result = ImplicitConversionSequence::Worse;
3420 else
3421 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003422 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003423 return ImplicitConversionSequence::Indistinguishable;
3424
3425 if (SCS1.Third == SCS2.Third) {
3426 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3427 : ImplicitConversionSequence::Indistinguishable;
3428 }
3429
3430 if (SCS1.Third == ICK_Identity)
3431 return Result == ImplicitConversionSequence::Worse
3432 ? ImplicitConversionSequence::Indistinguishable
3433 : ImplicitConversionSequence::Better;
3434
3435 if (SCS2.Third == ICK_Identity)
3436 return Result == ImplicitConversionSequence::Better
3437 ? ImplicitConversionSequence::Indistinguishable
3438 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003440 return ImplicitConversionSequence::Indistinguishable;
3441}
3442
Douglas Gregore696ebb2011-01-26 14:52:12 +00003443/// \brief Determine whether one of the given reference bindings is better
3444/// than the other based on what kind of bindings they are.
3445static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3446 const StandardConversionSequence &SCS2) {
3447 // C++0x [over.ics.rank]p3b4:
3448 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3449 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003450 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003451 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003452 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003453 // reference*.
3454 //
3455 // FIXME: Rvalue references. We're going rogue with the above edits,
3456 // because the semantics in the current C++0x working paper (N3225 at the
3457 // time of this writing) break the standard definition of std::forward
3458 // and std::reference_wrapper when dealing with references to functions.
3459 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003460 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3461 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3462 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003463
Douglas Gregore696ebb2011-01-26 14:52:12 +00003464 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3465 SCS2.IsLvalueReference) ||
3466 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3467 !SCS2.IsLvalueReference);
3468}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003469
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003470/// CompareStandardConversionSequences - Compare two standard
3471/// conversion sequences to determine whether one is better than the
3472/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003473static ImplicitConversionSequence::CompareKind
3474CompareStandardConversionSequences(Sema &S,
3475 const StandardConversionSequence& SCS1,
3476 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003477{
3478 // Standard conversion sequence S1 is a better conversion sequence
3479 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3480
3481 // -- S1 is a proper subsequence of S2 (comparing the conversion
3482 // sequences in the canonical form defined by 13.3.3.1.1,
3483 // excluding any Lvalue Transformation; the identity conversion
3484 // sequence is considered to be a subsequence of any
3485 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003486 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003487 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003488 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003489
3490 // -- the rank of S1 is better than the rank of S2 (by the rules
3491 // defined below), or, if not that,
3492 ImplicitConversionRank Rank1 = SCS1.getRank();
3493 ImplicitConversionRank Rank2 = SCS2.getRank();
3494 if (Rank1 < Rank2)
3495 return ImplicitConversionSequence::Better;
3496 else if (Rank2 < Rank1)
3497 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003498
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003499 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3500 // are indistinguishable unless one of the following rules
3501 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003502
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003503 // A conversion that is not a conversion of a pointer, or
3504 // pointer to member, to bool is better than another conversion
3505 // that is such a conversion.
3506 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3507 return SCS2.isPointerConversionToBool()
3508 ? ImplicitConversionSequence::Better
3509 : ImplicitConversionSequence::Worse;
3510
Douglas Gregor5c407d92008-10-23 00:40:37 +00003511 // C++ [over.ics.rank]p4b2:
3512 //
3513 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003514 // conversion of B* to A* is better than conversion of B* to
3515 // void*, and conversion of A* to void* is better than conversion
3516 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003517 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003518 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003519 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003520 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003521 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3522 // Exactly one of the conversion sequences is a conversion to
3523 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003524 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3525 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003526 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3527 // Neither conversion sequence converts to a void pointer; compare
3528 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003529 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003530 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003531 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003532 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3533 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003534 // Both conversion sequences are conversions to void
3535 // pointers. Compare the source types to determine if there's an
3536 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003537 QualType FromType1 = SCS1.getFromType();
3538 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003539
3540 // Adjust the types we're converting from via the array-to-pointer
3541 // conversion, if we need to.
3542 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003543 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003544 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003545 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003546
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003547 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3548 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003549
John McCall5c32be02010-08-24 20:38:10 +00003550 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003551 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003552 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003553 return ImplicitConversionSequence::Worse;
3554
3555 // Objective-C++: If one interface is more specific than the
3556 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003557 const ObjCObjectPointerType* FromObjCPtr1
3558 = FromType1->getAs<ObjCObjectPointerType>();
3559 const ObjCObjectPointerType* FromObjCPtr2
3560 = FromType2->getAs<ObjCObjectPointerType>();
3561 if (FromObjCPtr1 && FromObjCPtr2) {
3562 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3563 FromObjCPtr2);
3564 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3565 FromObjCPtr1);
3566 if (AssignLeft != AssignRight) {
3567 return AssignLeft? ImplicitConversionSequence::Better
3568 : ImplicitConversionSequence::Worse;
3569 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003570 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003571 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003572
3573 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3574 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003575 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003576 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003577 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003578
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003579 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003580 // Check for a better reference binding based on the kind of bindings.
3581 if (isBetterReferenceBindingKind(SCS1, SCS2))
3582 return ImplicitConversionSequence::Better;
3583 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3584 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003585
Sebastian Redlb28b4072009-03-22 23:49:27 +00003586 // C++ [over.ics.rank]p3b4:
3587 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3588 // which the references refer are the same type except for
3589 // top-level cv-qualifiers, and the type to which the reference
3590 // initialized by S2 refers is more cv-qualified than the type
3591 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003592 QualType T1 = SCS1.getToType(2);
3593 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003594 T1 = S.Context.getCanonicalType(T1);
3595 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003596 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003597 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3598 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003599 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003600 // Objective-C++ ARC: If the references refer to objects with different
3601 // lifetimes, prefer bindings that don't change lifetime.
3602 if (SCS1.ObjCLifetimeConversionBinding !=
3603 SCS2.ObjCLifetimeConversionBinding) {
3604 return SCS1.ObjCLifetimeConversionBinding
3605 ? ImplicitConversionSequence::Worse
3606 : ImplicitConversionSequence::Better;
3607 }
3608
Chandler Carruth8e543b32010-12-12 08:17:55 +00003609 // If the type is an array type, promote the element qualifiers to the
3610 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003611 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003612 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003613 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003614 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003615 if (T2.isMoreQualifiedThan(T1))
3616 return ImplicitConversionSequence::Better;
3617 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003618 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003619 }
3620 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003621
Francois Pichet08d2fa02011-09-18 21:37:37 +00003622 // In Microsoft mode, prefer an integral conversion to a
3623 // floating-to-integral conversion if the integral conversion
3624 // is between types of the same size.
3625 // For example:
3626 // void f(float);
3627 // void f(int);
3628 // int main {
3629 // long a;
3630 // f(a);
3631 // }
3632 // Here, MSVC will call f(int) instead of generating a compile error
3633 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003634 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3635 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003636 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003637 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003638 return ImplicitConversionSequence::Better;
3639
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003640 return ImplicitConversionSequence::Indistinguishable;
3641}
3642
3643/// CompareQualificationConversions - Compares two standard conversion
3644/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003645/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3646ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003647CompareQualificationConversions(Sema &S,
3648 const StandardConversionSequence& SCS1,
3649 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003650 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003651 // -- S1 and S2 differ only in their qualification conversion and
3652 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3653 // cv-qualification signature of type T1 is a proper subset of
3654 // the cv-qualification signature of type T2, and S1 is not the
3655 // deprecated string literal array-to-pointer conversion (4.2).
3656 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3657 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3658 return ImplicitConversionSequence::Indistinguishable;
3659
3660 // FIXME: the example in the standard doesn't use a qualification
3661 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003662 QualType T1 = SCS1.getToType(2);
3663 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003664 T1 = S.Context.getCanonicalType(T1);
3665 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003666 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003667 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3668 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003669
3670 // If the types are the same, we won't learn anything by unwrapped
3671 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003672 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003673 return ImplicitConversionSequence::Indistinguishable;
3674
Chandler Carruth607f38e2009-12-29 07:16:59 +00003675 // If the type is an array type, promote the element qualifiers to the type
3676 // for comparison.
3677 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003678 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003679 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003680 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003681
Mike Stump11289f42009-09-09 15:08:12 +00003682 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003683 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003684
3685 // Objective-C++ ARC:
3686 // Prefer qualification conversions not involving a change in lifetime
3687 // to qualification conversions that do not change lifetime.
3688 if (SCS1.QualificationIncludesObjCLifetime !=
3689 SCS2.QualificationIncludesObjCLifetime) {
3690 Result = SCS1.QualificationIncludesObjCLifetime
3691 ? ImplicitConversionSequence::Worse
3692 : ImplicitConversionSequence::Better;
3693 }
3694
John McCall5c32be02010-08-24 20:38:10 +00003695 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003696 // Within each iteration of the loop, we check the qualifiers to
3697 // determine if this still looks like a qualification
3698 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003699 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003700 // until there are no more pointers or pointers-to-members left
3701 // to unwrap. This essentially mimics what
3702 // IsQualificationConversion does, but here we're checking for a
3703 // strict subset of qualifiers.
3704 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3705 // The qualifiers are the same, so this doesn't tell us anything
3706 // about how the sequences rank.
3707 ;
3708 else if (T2.isMoreQualifiedThan(T1)) {
3709 // T1 has fewer qualifiers, so it could be the better sequence.
3710 if (Result == ImplicitConversionSequence::Worse)
3711 // Neither has qualifiers that are a subset of the other's
3712 // qualifiers.
3713 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003714
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003715 Result = ImplicitConversionSequence::Better;
3716 } else if (T1.isMoreQualifiedThan(T2)) {
3717 // T2 has fewer qualifiers, so it could be the better sequence.
3718 if (Result == ImplicitConversionSequence::Better)
3719 // Neither has qualifiers that are a subset of the other's
3720 // qualifiers.
3721 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003722
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003723 Result = ImplicitConversionSequence::Worse;
3724 } else {
3725 // Qualifiers are disjoint.
3726 return ImplicitConversionSequence::Indistinguishable;
3727 }
3728
3729 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003730 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003731 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003732 }
3733
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003734 // Check that the winning standard conversion sequence isn't using
3735 // the deprecated string literal array to pointer conversion.
3736 switch (Result) {
3737 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003738 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003739 Result = ImplicitConversionSequence::Indistinguishable;
3740 break;
3741
3742 case ImplicitConversionSequence::Indistinguishable:
3743 break;
3744
3745 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003746 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003747 Result = ImplicitConversionSequence::Indistinguishable;
3748 break;
3749 }
3750
3751 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003752}
3753
Douglas Gregor5c407d92008-10-23 00:40:37 +00003754/// CompareDerivedToBaseConversions - Compares two standard conversion
3755/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003756/// various kinds of derived-to-base conversions (C++
3757/// [over.ics.rank]p4b3). As part of these checks, we also look at
3758/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003759ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003760CompareDerivedToBaseConversions(Sema &S,
3761 const StandardConversionSequence& SCS1,
3762 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003763 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003764 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003765 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003766 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003767
3768 // Adjust the types we're converting from via the array-to-pointer
3769 // conversion, if we need to.
3770 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003771 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003772 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003773 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003774
3775 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003776 FromType1 = S.Context.getCanonicalType(FromType1);
3777 ToType1 = S.Context.getCanonicalType(ToType1);
3778 FromType2 = S.Context.getCanonicalType(FromType2);
3779 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003780
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003781 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003782 //
3783 // If class B is derived directly or indirectly from class A and
3784 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003785 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003786 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003787 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003788 SCS2.Second == ICK_Pointer_Conversion &&
3789 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3790 FromType1->isPointerType() && FromType2->isPointerType() &&
3791 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003792 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003793 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003794 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003795 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003796 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003797 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003798 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003799 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003800
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003801 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003802 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003803 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003804 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003805 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003806 return ImplicitConversionSequence::Worse;
3807 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003808
3809 // -- conversion of B* to A* is better than conversion of C* to A*,
3810 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003811 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003812 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003813 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003814 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003815 }
3816 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3817 SCS2.Second == ICK_Pointer_Conversion) {
3818 const ObjCObjectPointerType *FromPtr1
3819 = FromType1->getAs<ObjCObjectPointerType>();
3820 const ObjCObjectPointerType *FromPtr2
3821 = FromType2->getAs<ObjCObjectPointerType>();
3822 const ObjCObjectPointerType *ToPtr1
3823 = ToType1->getAs<ObjCObjectPointerType>();
3824 const ObjCObjectPointerType *ToPtr2
3825 = ToType2->getAs<ObjCObjectPointerType>();
3826
3827 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3828 // Apply the same conversion ranking rules for Objective-C pointer types
3829 // that we do for C++ pointers to class types. However, we employ the
3830 // Objective-C pseudo-subtyping relationship used for assignment of
3831 // Objective-C pointer types.
3832 bool FromAssignLeft
3833 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3834 bool FromAssignRight
3835 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3836 bool ToAssignLeft
3837 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3838 bool ToAssignRight
3839 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3840
3841 // A conversion to an a non-id object pointer type or qualified 'id'
3842 // type is better than a conversion to 'id'.
3843 if (ToPtr1->isObjCIdType() &&
3844 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3845 return ImplicitConversionSequence::Worse;
3846 if (ToPtr2->isObjCIdType() &&
3847 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3848 return ImplicitConversionSequence::Better;
3849
3850 // A conversion to a non-id object pointer type is better than a
3851 // conversion to a qualified 'id' type
3852 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3853 return ImplicitConversionSequence::Worse;
3854 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3855 return ImplicitConversionSequence::Better;
3856
3857 // A conversion to an a non-Class object pointer type or qualified 'Class'
3858 // type is better than a conversion to 'Class'.
3859 if (ToPtr1->isObjCClassType() &&
3860 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3861 return ImplicitConversionSequence::Worse;
3862 if (ToPtr2->isObjCClassType() &&
3863 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3864 return ImplicitConversionSequence::Better;
3865
3866 // A conversion to a non-Class object pointer type is better than a
3867 // conversion to a qualified 'Class' type.
3868 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3869 return ImplicitConversionSequence::Worse;
3870 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3871 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003872
Douglas Gregor058d3de2011-01-31 18:51:41 +00003873 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3874 if (S.Context.hasSameType(FromType1, FromType2) &&
3875 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3876 (ToAssignLeft != ToAssignRight))
3877 return ToAssignLeft? ImplicitConversionSequence::Worse
3878 : ImplicitConversionSequence::Better;
3879
3880 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3881 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3882 (FromAssignLeft != FromAssignRight))
3883 return FromAssignLeft? ImplicitConversionSequence::Better
3884 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003885 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003886 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003887
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003888 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003889 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3890 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3891 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003892 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003893 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003894 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003895 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003896 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003897 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003898 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003899 ToType2->getAs<MemberPointerType>();
3900 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3901 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3902 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3903 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3904 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3905 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3906 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3907 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003908 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003909 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003910 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003911 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003912 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003913 return ImplicitConversionSequence::Better;
3914 }
3915 // conversion of B::* to C::* is better than conversion of A::* to C::*
3916 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003917 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003918 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003919 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003920 return ImplicitConversionSequence::Worse;
3921 }
3922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003923
Douglas Gregor5ab11652010-04-17 22:01:05 +00003924 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003925 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003926 // -- binding of an expression of type C to a reference of type
3927 // B& is better than binding an expression of type C to a
3928 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003929 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3930 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3931 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003932 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003933 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003934 return ImplicitConversionSequence::Worse;
3935 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003936
Douglas Gregor2fe98832008-11-03 19:09:14 +00003937 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003938 // -- binding of an expression of type B to a reference of type
3939 // A& is better than binding an expression of type C to a
3940 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003941 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3942 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3943 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003944 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003945 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003946 return ImplicitConversionSequence::Worse;
3947 }
3948 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003949
Douglas Gregor5c407d92008-10-23 00:40:37 +00003950 return ImplicitConversionSequence::Indistinguishable;
3951}
3952
Douglas Gregor45bb4832013-03-26 23:36:30 +00003953/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3954/// C++ class.
3955static bool isTypeValid(QualType T) {
3956 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3957 return !Record->isInvalidDecl();
3958
3959 return true;
3960}
3961
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003962/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3963/// determine whether they are reference-related,
3964/// reference-compatible, reference-compatible with added
3965/// qualification, or incompatible, for use in C++ initialization by
3966/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3967/// type, and the first type (T1) is the pointee type of the reference
3968/// type being initialized.
3969Sema::ReferenceCompareResult
3970Sema::CompareReferenceRelationship(SourceLocation Loc,
3971 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003972 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003973 bool &ObjCConversion,
3974 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003975 assert(!OrigT1->isReferenceType() &&
3976 "T1 must be the pointee type of the reference type");
3977 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3978
3979 QualType T1 = Context.getCanonicalType(OrigT1);
3980 QualType T2 = Context.getCanonicalType(OrigT2);
3981 Qualifiers T1Quals, T2Quals;
3982 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3983 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3984
3985 // C++ [dcl.init.ref]p4:
3986 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3987 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3988 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003989 DerivedToBase = false;
3990 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003991 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003992 if (UnqualT1 == UnqualT2) {
3993 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003994 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00003995 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3996 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003997 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003998 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3999 UnqualT2->isObjCObjectOrInterfaceType() &&
4000 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4001 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004002 else
4003 return Ref_Incompatible;
4004
4005 // At this point, we know that T1 and T2 are reference-related (at
4006 // least).
4007
4008 // If the type is an array type, promote the element qualifiers to the type
4009 // for comparison.
4010 if (isa<ArrayType>(T1) && T1Quals)
4011 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4012 if (isa<ArrayType>(T2) && T2Quals)
4013 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4014
4015 // C++ [dcl.init.ref]p4:
4016 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4017 // reference-related to T2 and cv1 is the same cv-qualification
4018 // as, or greater cv-qualification than, cv2. For purposes of
4019 // overload resolution, cases for which cv1 is greater
4020 // cv-qualification than cv2 are identified as
4021 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004022 //
4023 // Note that we also require equivalence of Objective-C GC and address-space
4024 // qualifiers when performing these computations, so that e.g., an int in
4025 // address space 1 is not reference-compatible with an int in address
4026 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004027 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4028 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004029 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4030 ObjCLifetimeConversion = true;
4031
John McCall31168b02011-06-15 23:02:42 +00004032 T1Quals.removeObjCLifetime();
4033 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004034 }
4035
Douglas Gregord517d552011-04-28 17:56:11 +00004036 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004037 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004038 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004039 return Ref_Compatible_With_Added_Qualification;
4040 else
4041 return Ref_Related;
4042}
4043
Douglas Gregor836a7e82010-08-11 02:15:33 +00004044/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004045/// with DeclType. Return true if something definite is found.
4046static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004047FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4048 QualType DeclType, SourceLocation DeclLoc,
4049 Expr *Init, QualType T2, bool AllowRvalues,
4050 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004051 assert(T2->isRecordType() && "Can only find conversions of record types.");
4052 CXXRecordDecl *T2RecordDecl
4053 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4054
4055 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004056 std::pair<CXXRecordDecl::conversion_iterator,
4057 CXXRecordDecl::conversion_iterator>
4058 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4059 for (CXXRecordDecl::conversion_iterator
4060 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004061 NamedDecl *D = *I;
4062 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4063 if (isa<UsingShadowDecl>(D))
4064 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4065
4066 FunctionTemplateDecl *ConvTemplate
4067 = dyn_cast<FunctionTemplateDecl>(D);
4068 CXXConversionDecl *Conv;
4069 if (ConvTemplate)
4070 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4071 else
4072 Conv = cast<CXXConversionDecl>(D);
4073
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004074 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004075 // explicit conversions, skip it.
4076 if (!AllowExplicit && Conv->isExplicit())
4077 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004078
Douglas Gregor836a7e82010-08-11 02:15:33 +00004079 if (AllowRvalues) {
4080 bool DerivedToBase = false;
4081 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004082 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004083
4084 // If we are initializing an rvalue reference, don't permit conversion
4085 // functions that return lvalues.
4086 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4087 const ReferenceType *RefType
4088 = Conv->getConversionType()->getAs<LValueReferenceType>();
4089 if (RefType && !RefType->getPointeeType()->isFunctionType())
4090 continue;
4091 }
4092
Douglas Gregor836a7e82010-08-11 02:15:33 +00004093 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004094 S.CompareReferenceRelationship(
4095 DeclLoc,
4096 Conv->getConversionType().getNonReferenceType()
4097 .getUnqualifiedType(),
4098 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004099 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004100 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004101 continue;
4102 } else {
4103 // If the conversion function doesn't return a reference type,
4104 // it can't be considered for this conversion. An rvalue reference
4105 // is only acceptable if its referencee is a function type.
4106
4107 const ReferenceType *RefType =
4108 Conv->getConversionType()->getAs<ReferenceType>();
4109 if (!RefType ||
4110 (!RefType->isLValueReferenceType() &&
4111 !RefType->getPointeeType()->isFunctionType()))
4112 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004113 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004114
Douglas Gregor836a7e82010-08-11 02:15:33 +00004115 if (ConvTemplate)
4116 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004117 Init, DeclType, CandidateSet,
4118 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004119 else
4120 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004121 DeclType, CandidateSet,
4122 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004123 }
4124
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004125 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4126
Sebastian Redld92badf2010-06-30 18:13:39 +00004127 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004128 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004129 case OR_Success:
4130 // C++ [over.ics.ref]p1:
4131 //
4132 // [...] If the parameter binds directly to the result of
4133 // applying a conversion function to the argument
4134 // expression, the implicit conversion sequence is a
4135 // user-defined conversion sequence (13.3.3.1.2), with the
4136 // second standard conversion sequence either an identity
4137 // conversion or, if the conversion function returns an
4138 // entity of a type that is a derived class of the parameter
4139 // type, a derived-to-base Conversion.
4140 if (!Best->FinalConversion.DirectBinding)
4141 return false;
4142
4143 ICS.setUserDefined();
4144 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4145 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004146 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004147 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004148 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004149 ICS.UserDefined.EllipsisConversion = false;
4150 assert(ICS.UserDefined.After.ReferenceBinding &&
4151 ICS.UserDefined.After.DirectBinding &&
4152 "Expected a direct reference binding!");
4153 return true;
4154
4155 case OR_Ambiguous:
4156 ICS.setAmbiguous();
4157 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4158 Cand != CandidateSet.end(); ++Cand)
4159 if (Cand->Viable)
4160 ICS.Ambiguous.addConversion(Cand->Function);
4161 return true;
4162
4163 case OR_No_Viable_Function:
4164 case OR_Deleted:
4165 // There was no suitable conversion, or we found a deleted
4166 // conversion; continue with other checks.
4167 return false;
4168 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004169
David Blaikie8a40f702012-01-17 06:56:22 +00004170 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004171}
4172
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004173/// \brief Compute an implicit conversion sequence for reference
4174/// initialization.
4175static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004176TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004177 SourceLocation DeclLoc,
4178 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004179 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004180 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4181
4182 // Most paths end in a failed conversion.
4183 ImplicitConversionSequence ICS;
4184 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4185
4186 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4187 QualType T2 = Init->getType();
4188
4189 // If the initializer is the address of an overloaded function, try
4190 // to resolve the overloaded function. If all goes well, T2 is the
4191 // type of the resulting function.
4192 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4193 DeclAccessPair Found;
4194 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4195 false, Found))
4196 T2 = Fn->getType();
4197 }
4198
4199 // Compute some basic properties of the types and the initializer.
4200 bool isRValRef = DeclType->isRValueReferenceType();
4201 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004202 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004203 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004204 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004205 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004206 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004207 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004208
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004209
Sebastian Redld92badf2010-06-30 18:13:39 +00004210 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004211 // A reference to type "cv1 T1" is initialized by an expression
4212 // of type "cv2 T2" as follows:
4213
Sebastian Redld92badf2010-06-30 18:13:39 +00004214 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004215 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004216 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4217 // reference-compatible with "cv2 T2," or
4218 //
4219 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4220 if (InitCategory.isLValue() &&
4221 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004222 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004223 // When a parameter of reference type binds directly (8.5.3)
4224 // to an argument expression, the implicit conversion sequence
4225 // is the identity conversion, unless the argument expression
4226 // has a type that is a derived class of the parameter type,
4227 // in which case the implicit conversion sequence is a
4228 // derived-to-base Conversion (13.3.3.1).
4229 ICS.setStandard();
4230 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004231 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4232 : ObjCConversion? ICK_Compatible_Conversion
4233 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004234 ICS.Standard.Third = ICK_Identity;
4235 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4236 ICS.Standard.setToType(0, T2);
4237 ICS.Standard.setToType(1, T1);
4238 ICS.Standard.setToType(2, T1);
4239 ICS.Standard.ReferenceBinding = true;
4240 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004241 ICS.Standard.IsLvalueReference = !isRValRef;
4242 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4243 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004244 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004245 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004246 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004247
Sebastian Redld92badf2010-06-30 18:13:39 +00004248 // Nothing more to do: the inaccessibility/ambiguity check for
4249 // derived-to-base conversions is suppressed when we're
4250 // computing the implicit conversion sequence (C++
4251 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004252 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004253 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004254
Sebastian Redld92badf2010-06-30 18:13:39 +00004255 // -- has a class type (i.e., T2 is a class type), where T1 is
4256 // not reference-related to T2, and can be implicitly
4257 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4258 // is reference-compatible with "cv3 T3" 92) (this
4259 // conversion is selected by enumerating the applicable
4260 // conversion functions (13.3.1.6) and choosing the best
4261 // one through overload resolution (13.3)),
4262 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004263 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004264 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004265 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4266 Init, T2, /*AllowRvalues=*/false,
4267 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004268 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004269 }
4270 }
4271
Sebastian Redld92badf2010-06-30 18:13:39 +00004272 // -- Otherwise, the reference shall be an lvalue reference to a
4273 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004274 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004276 // We actually handle one oddity of C++ [over.ics.ref] at this
4277 // point, which is that, due to p2 (which short-circuits reference
4278 // binding by only attempting a simple conversion for non-direct
4279 // bindings) and p3's strange wording, we allow a const volatile
4280 // reference to bind to an rvalue. Hence the check for the presence
4281 // of "const" rather than checking for "const" being the only
4282 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004283 // This is also the point where rvalue references and lvalue inits no longer
4284 // go together.
Richard Smithce4f6082012-05-24 04:29:20 +00004285 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004286 return ICS;
4287
Douglas Gregorf143cd52011-01-24 16:14:37 +00004288 // -- If the initializer expression
4289 //
4290 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004291 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004292 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4293 (InitCategory.isXValue() ||
4294 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4295 (InitCategory.isLValue() && T2->isFunctionType()))) {
4296 ICS.setStandard();
4297 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004298 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004299 : ObjCConversion? ICK_Compatible_Conversion
4300 : ICK_Identity;
4301 ICS.Standard.Third = ICK_Identity;
4302 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4303 ICS.Standard.setToType(0, T2);
4304 ICS.Standard.setToType(1, T1);
4305 ICS.Standard.setToType(2, T1);
4306 ICS.Standard.ReferenceBinding = true;
4307 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4308 // binding unless we're binding to a class prvalue.
4309 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4310 // allow the use of rvalue references in C++98/03 for the benefit of
4311 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004312 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004313 S.getLangOpts().CPlusPlus11 ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004314 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004315 ICS.Standard.IsLvalueReference = !isRValRef;
4316 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004317 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004318 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004319 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004320 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004321 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004322 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323
Douglas Gregorf143cd52011-01-24 16:14:37 +00004324 // -- has a class type (i.e., T2 is a class type), where T1 is not
4325 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004326 // an xvalue, class prvalue, or function lvalue of type
4327 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004328 // "cv3 T3",
4329 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004330 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004331 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004332 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004333 // class subobject).
4334 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004335 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004336 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4337 Init, T2, /*AllowRvalues=*/true,
4338 AllowExplicit)) {
4339 // In the second case, if the reference is an rvalue reference
4340 // and the second standard conversion sequence of the
4341 // user-defined conversion sequence includes an lvalue-to-rvalue
4342 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004343 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004344 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4345 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4346
Douglas Gregor95273c32011-01-21 16:36:05 +00004347 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004348 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004349
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004350 // -- Otherwise, a temporary of type "cv1 T1" is created and
4351 // initialized from the initializer expression using the
4352 // rules for a non-reference copy initialization (8.5). The
4353 // reference is then bound to the temporary. If T1 is
4354 // reference-related to T2, cv1 must be the same
4355 // cv-qualification as, or greater cv-qualification than,
4356 // cv2; otherwise, the program is ill-formed.
4357 if (RefRelationship == Sema::Ref_Related) {
4358 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4359 // we would be reference-compatible or reference-compatible with
4360 // added qualification. But that wasn't the case, so the reference
4361 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004362 //
4363 // Note that we only want to check address spaces and cvr-qualifiers here.
4364 // ObjC GC and lifetime qualifiers aren't important.
4365 Qualifiers T1Quals = T1.getQualifiers();
4366 Qualifiers T2Quals = T2.getQualifiers();
4367 T1Quals.removeObjCGCAttr();
4368 T1Quals.removeObjCLifetime();
4369 T2Quals.removeObjCGCAttr();
4370 T2Quals.removeObjCLifetime();
4371 if (!T1Quals.compatiblyIncludes(T2Quals))
4372 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004373 }
4374
4375 // If at least one of the types is a class type, the types are not
4376 // related, and we aren't allowed any user conversions, the
4377 // reference binding fails. This case is important for breaking
4378 // recursion, since TryImplicitConversion below will attempt to
4379 // create a temporary through the use of a copy constructor.
4380 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4381 (T1->isRecordType() || T2->isRecordType()))
4382 return ICS;
4383
Douglas Gregorcba72b12011-01-21 05:18:22 +00004384 // If T1 is reference-related to T2 and the reference is an rvalue
4385 // reference, the initializer expression shall not be an lvalue.
4386 if (RefRelationship >= Sema::Ref_Related &&
4387 isRValRef && Init->Classify(S.Context).isLValue())
4388 return ICS;
4389
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004390 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004391 // When a parameter of reference type is not bound directly to
4392 // an argument expression, the conversion sequence is the one
4393 // required to convert the argument expression to the
4394 // underlying type of the reference according to
4395 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4396 // to copy-initializing a temporary of the underlying type with
4397 // the argument expression. Any difference in top-level
4398 // cv-qualification is subsumed by the initialization itself
4399 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004400 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4401 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004402 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004403 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004404 /*AllowObjCWritebackConversion=*/false,
4405 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004406
4407 // Of course, that's still a reference binding.
4408 if (ICS.isStandard()) {
4409 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004410 ICS.Standard.IsLvalueReference = !isRValRef;
4411 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4412 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004413 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004414 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004415 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004416 // Don't allow rvalue references to bind to lvalues.
4417 if (DeclType->isRValueReferenceType()) {
4418 if (const ReferenceType *RefType
4419 = ICS.UserDefined.ConversionFunction->getResultType()
4420 ->getAs<LValueReferenceType>()) {
4421 if (!RefType->getPointeeType()->isFunctionType()) {
4422 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4423 DeclType);
4424 return ICS;
4425 }
4426 }
4427 }
4428
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004429 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004430 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4431 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4432 ICS.UserDefined.After.BindsToRvalue = true;
4433 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4434 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004435 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004436
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004437 return ICS;
4438}
4439
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004440static ImplicitConversionSequence
4441TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4442 bool SuppressUserConversions,
4443 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004444 bool AllowObjCWritebackConversion,
4445 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004446
4447/// TryListConversion - Try to copy-initialize a value of type ToType from the
4448/// initializer list From.
4449static ImplicitConversionSequence
4450TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4451 bool SuppressUserConversions,
4452 bool InOverloadResolution,
4453 bool AllowObjCWritebackConversion) {
4454 // C++11 [over.ics.list]p1:
4455 // When an argument is an initializer list, it is not an expression and
4456 // special rules apply for converting it to a parameter type.
4457
4458 ImplicitConversionSequence Result;
4459 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4460
Sebastian Redl09edce02012-01-23 22:09:39 +00004461 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004462 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004463 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004464 return Result;
4465
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004466 // C++11 [over.ics.list]p2:
4467 // If the parameter type is std::initializer_list<X> or "array of X" and
4468 // all the elements can be implicitly converted to X, the implicit
4469 // conversion sequence is the worst conversion necessary to convert an
4470 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004471 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004472 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004473 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004474 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004475 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004476 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004477 if (!X.isNull()) {
4478 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4479 Expr *Init = From->getInit(i);
4480 ImplicitConversionSequence ICS =
4481 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4482 InOverloadResolution,
4483 AllowObjCWritebackConversion);
4484 // If a single element isn't convertible, fail.
4485 if (ICS.isBad()) {
4486 Result = ICS;
4487 break;
4488 }
4489 // Otherwise, look for the worst conversion.
4490 if (Result.isBad() ||
4491 CompareImplicitConversionSequences(S, ICS, Result) ==
4492 ImplicitConversionSequence::Worse)
4493 Result = ICS;
4494 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004495
4496 // For an empty list, we won't have computed any conversion sequence.
4497 // Introduce the identity conversion sequence.
4498 if (From->getNumInits() == 0) {
4499 Result.setStandard();
4500 Result.Standard.setAsIdentityConversion();
4501 Result.Standard.setFromType(ToType);
4502 Result.Standard.setAllToTypes(ToType);
4503 }
4504
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004505 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004506 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004507 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004508
4509 // C++11 [over.ics.list]p3:
4510 // Otherwise, if the parameter is a non-aggregate class X and overload
4511 // resolution chooses a single best constructor [...] the implicit
4512 // conversion sequence is a user-defined conversion sequence. If multiple
4513 // constructors are viable but none is better than the others, the
4514 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004515 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4516 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004517 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4518 /*AllowExplicit=*/false,
4519 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004520 AllowObjCWritebackConversion,
4521 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004522 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004523
4524 // C++11 [over.ics.list]p4:
4525 // Otherwise, if the parameter has an aggregate type which can be
4526 // initialized from the initializer list [...] the implicit conversion
4527 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004528 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004529 // Type is an aggregate, argument is an init list. At this point it comes
4530 // down to checking whether the initialization works.
4531 // FIXME: Find out whether this parameter is consumed or not.
4532 InitializedEntity Entity =
4533 InitializedEntity::InitializeParameter(S.Context, ToType,
4534 /*Consumed=*/false);
4535 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4536 Result.setUserDefined();
4537 Result.UserDefined.Before.setAsIdentityConversion();
4538 // Initializer lists don't have a type.
4539 Result.UserDefined.Before.setFromType(QualType());
4540 Result.UserDefined.Before.setAllToTypes(QualType());
4541
4542 Result.UserDefined.After.setAsIdentityConversion();
4543 Result.UserDefined.After.setFromType(ToType);
4544 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004545 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004546 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004547 return Result;
4548 }
4549
4550 // C++11 [over.ics.list]p5:
4551 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004552 if (ToType->isReferenceType()) {
4553 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4554 // mention initializer lists in any way. So we go by what list-
4555 // initialization would do and try to extrapolate from that.
4556
4557 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4558
4559 // If the initializer list has a single element that is reference-related
4560 // to the parameter type, we initialize the reference from that.
4561 if (From->getNumInits() == 1) {
4562 Expr *Init = From->getInit(0);
4563
4564 QualType T2 = Init->getType();
4565
4566 // If the initializer is the address of an overloaded function, try
4567 // to resolve the overloaded function. If all goes well, T2 is the
4568 // type of the resulting function.
4569 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4570 DeclAccessPair Found;
4571 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4572 Init, ToType, false, Found))
4573 T2 = Fn->getType();
4574 }
4575
4576 // Compute some basic properties of the types and the initializer.
4577 bool dummy1 = false;
4578 bool dummy2 = false;
4579 bool dummy3 = false;
4580 Sema::ReferenceCompareResult RefRelationship
4581 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4582 dummy2, dummy3);
4583
Richard Smith4d2bbd72013-09-06 01:22:42 +00004584 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004585 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4586 SuppressUserConversions,
4587 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004588 }
Sebastian Redldf888642011-12-03 14:54:30 +00004589 }
4590
4591 // Otherwise, we bind the reference to a temporary created from the
4592 // initializer list.
4593 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4594 InOverloadResolution,
4595 AllowObjCWritebackConversion);
4596 if (Result.isFailure())
4597 return Result;
4598 assert(!Result.isEllipsis() &&
4599 "Sub-initialization cannot result in ellipsis conversion.");
4600
4601 // Can we even bind to a temporary?
4602 if (ToType->isRValueReferenceType() ||
4603 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4604 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4605 Result.UserDefined.After;
4606 SCS.ReferenceBinding = true;
4607 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4608 SCS.BindsToRvalue = true;
4609 SCS.BindsToFunctionLvalue = false;
4610 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4611 SCS.ObjCLifetimeConversionBinding = false;
4612 } else
4613 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4614 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004615 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004616 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004617
4618 // C++11 [over.ics.list]p6:
4619 // Otherwise, if the parameter type is not a class:
4620 if (!ToType->isRecordType()) {
4621 // - if the initializer list has one element, the implicit conversion
4622 // sequence is the one required to convert the element to the
4623 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004624 unsigned NumInits = From->getNumInits();
4625 if (NumInits == 1)
4626 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4627 SuppressUserConversions,
4628 InOverloadResolution,
4629 AllowObjCWritebackConversion);
4630 // - if the initializer list has no elements, the implicit conversion
4631 // sequence is the identity conversion.
4632 else if (NumInits == 0) {
4633 Result.setStandard();
4634 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004635 Result.Standard.setFromType(ToType);
4636 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004637 }
4638 return Result;
4639 }
4640
4641 // C++11 [over.ics.list]p7:
4642 // In all cases other than those enumerated above, no conversion is possible
4643 return Result;
4644}
4645
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004646/// TryCopyInitialization - Try to copy-initialize a value of type
4647/// ToType from the expression From. Return the implicit conversion
4648/// sequence required to pass this argument, which may be a bad
4649/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004650/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004651/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004652static ImplicitConversionSequence
4653TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004654 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004655 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004656 bool AllowObjCWritebackConversion,
4657 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004658 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4659 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4660 InOverloadResolution,AllowObjCWritebackConversion);
4661
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004662 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004663 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004664 /*FIXME:*/From->getLocStart(),
4665 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004666 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004667
John McCall5c32be02010-08-24 20:38:10 +00004668 return TryImplicitConversion(S, From, ToType,
4669 SuppressUserConversions,
4670 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004671 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004672 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004673 AllowObjCWritebackConversion,
4674 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004675}
4676
Anna Zaks1b068122011-07-28 19:46:48 +00004677static bool TryCopyInitialization(const CanQualType FromQTy,
4678 const CanQualType ToQTy,
4679 Sema &S,
4680 SourceLocation Loc,
4681 ExprValueKind FromVK) {
4682 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4683 ImplicitConversionSequence ICS =
4684 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4685
4686 return !ICS.isBad();
4687}
4688
Douglas Gregor436424c2008-11-18 23:14:02 +00004689/// TryObjectArgumentInitialization - Try to initialize the object
4690/// parameter of the given member function (@c Method) from the
4691/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004692static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004693TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004694 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004695 CXXMethodDecl *Method,
4696 CXXRecordDecl *ActingContext) {
4697 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004698 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4699 // const volatile object.
4700 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4701 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004702 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004703
4704 // Set up the conversion sequence as a "bad" conversion, to allow us
4705 // to exit early.
4706 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004707
4708 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004709 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004710 FromType = PT->getPointeeType();
4711
Douglas Gregor02824322011-01-26 19:30:28 +00004712 // When we had a pointer, it's implicitly dereferenced, so we
4713 // better have an lvalue.
4714 assert(FromClassification.isLValue());
4715 }
4716
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004717 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004718
Douglas Gregor02824322011-01-26 19:30:28 +00004719 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004720 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004721 // parameter is
4722 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004723 // - "lvalue reference to cv X" for functions declared without a
4724 // ref-qualifier or with the & ref-qualifier
4725 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004726 // ref-qualifier
4727 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004728 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004729 // cv-qualification on the member function declaration.
4730 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004731 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004732 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004733 // (C++ [over.match.funcs]p5). We perform a simplified version of
4734 // reference binding here, that allows class rvalues to bind to
4735 // non-constant references.
4736
Douglas Gregor02824322011-01-26 19:30:28 +00004737 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004738 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004739 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004740 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004741 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004742 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004743 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004744 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004745 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004746
4747 // Check that we have either the same type or a derived type. It
4748 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004749 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004750 ImplicitConversionKind SecondKind;
4751 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4752 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004753 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004754 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004755 else {
John McCall65eb8792010-02-25 01:37:24 +00004756 ICS.setBad(BadConversionSequence::unrelated_class,
4757 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004758 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004759 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004760
Douglas Gregor02824322011-01-26 19:30:28 +00004761 // Check the ref-qualifier.
4762 switch (Method->getRefQualifier()) {
4763 case RQ_None:
4764 // Do nothing; we don't care about lvalueness or rvalueness.
4765 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004766
Douglas Gregor02824322011-01-26 19:30:28 +00004767 case RQ_LValue:
4768 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4769 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004770 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004771 ImplicitParamType);
4772 return ICS;
4773 }
4774 break;
4775
4776 case RQ_RValue:
4777 if (!FromClassification.isRValue()) {
4778 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004779 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004780 ImplicitParamType);
4781 return ICS;
4782 }
4783 break;
4784 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004785
Douglas Gregor436424c2008-11-18 23:14:02 +00004786 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004787 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004788 ICS.Standard.setAsIdentityConversion();
4789 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004790 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004791 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004792 ICS.Standard.ReferenceBinding = true;
4793 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004794 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004795 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004796 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4797 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4798 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004799 return ICS;
4800}
4801
4802/// PerformObjectArgumentInitialization - Perform initialization of
4803/// the implicit object parameter for the given Method with the given
4804/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004805ExprResult
4806Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004807 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004808 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004809 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004810 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004811 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004812 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004813
Douglas Gregor02824322011-01-26 19:30:28 +00004814 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004815 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004816 FromRecordType = PT->getPointeeType();
4817 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004818 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004819 } else {
4820 FromRecordType = From->getType();
4821 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004822 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004823 }
4824
John McCall6e9f8f62009-12-03 04:06:58 +00004825 // Note that we always use the true parent context when performing
4826 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004827 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004828 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4829 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004830 if (ICS.isBad()) {
4831 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4832 Qualifiers FromQs = FromRecordType.getQualifiers();
4833 Qualifiers ToQs = DestType.getQualifiers();
4834 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4835 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004836 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004837 diag::err_member_function_call_bad_cvr)
4838 << Method->getDeclName() << FromRecordType << (CVR - 1)
4839 << From->getSourceRange();
4840 Diag(Method->getLocation(), diag::note_previous_decl)
4841 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004842 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004843 }
4844 }
4845
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004846 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004847 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004848 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004849 }
Mike Stump11289f42009-09-09 15:08:12 +00004850
John Wiegley01296292011-04-08 18:41:53 +00004851 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4852 ExprResult FromRes =
4853 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4854 if (FromRes.isInvalid())
4855 return ExprError();
4856 From = FromRes.take();
4857 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004858
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004859 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004860 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004861 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004862 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004863}
4864
Douglas Gregor5fb53972009-01-14 15:45:31 +00004865/// TryContextuallyConvertToBool - Attempt to contextually convert the
4866/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004867static ImplicitConversionSequence
4868TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004869 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004870 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004871 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004872 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004873 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004874 /*AllowObjCWritebackConversion=*/false,
4875 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004876}
4877
4878/// PerformContextuallyConvertToBool - Perform a contextual conversion
4879/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004880ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004881 if (checkPlaceholderForOverload(*this, From))
4882 return ExprError();
4883
John McCall5c32be02010-08-24 20:38:10 +00004884 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004885 if (!ICS.isBad())
4886 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004887
Fariborz Jahanian76197412009-11-18 18:26:29 +00004888 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004889 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004890 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004891 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004892 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004893}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004894
Richard Smithf8379a02012-01-18 23:55:52 +00004895/// Check that the specified conversion is permitted in a converted constant
4896/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4897/// is acceptable.
4898static bool CheckConvertedConstantConversions(Sema &S,
4899 StandardConversionSequence &SCS) {
4900 // Since we know that the target type is an integral or unscoped enumeration
4901 // type, most conversion kinds are impossible. All possible First and Third
4902 // conversions are fine.
4903 switch (SCS.Second) {
4904 case ICK_Identity:
4905 case ICK_Integral_Promotion:
4906 case ICK_Integral_Conversion:
Guy Benyei259f9f42013-02-07 16:05:33 +00004907 case ICK_Zero_Event_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004908 return true;
4909
4910 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004911 // Conversion from an integral or unscoped enumeration type to bool is
4912 // classified as ICK_Boolean_Conversion, but it's also an integral
4913 // conversion, so it's permitted in a converted constant expression.
4914 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4915 SCS.getToType(2)->isBooleanType();
4916
Richard Smithf8379a02012-01-18 23:55:52 +00004917 case ICK_Floating_Integral:
4918 case ICK_Complex_Real:
4919 return false;
4920
4921 case ICK_Lvalue_To_Rvalue:
4922 case ICK_Array_To_Pointer:
4923 case ICK_Function_To_Pointer:
4924 case ICK_NoReturn_Adjustment:
4925 case ICK_Qualification:
4926 case ICK_Compatible_Conversion:
4927 case ICK_Vector_Conversion:
4928 case ICK_Vector_Splat:
4929 case ICK_Derived_To_Base:
4930 case ICK_Pointer_Conversion:
4931 case ICK_Pointer_Member:
4932 case ICK_Block_Pointer_Conversion:
4933 case ICK_Writeback_Conversion:
4934 case ICK_Floating_Promotion:
4935 case ICK_Complex_Promotion:
4936 case ICK_Complex_Conversion:
4937 case ICK_Floating_Conversion:
4938 case ICK_TransparentUnionConversion:
4939 llvm_unreachable("unexpected second conversion kind");
4940
4941 case ICK_Num_Conversion_Kinds:
4942 break;
4943 }
4944
4945 llvm_unreachable("unknown conversion kind");
4946}
4947
4948/// CheckConvertedConstantExpression - Check that the expression From is a
4949/// converted constant expression of type T, perform the conversion and produce
4950/// the converted expression, per C++11 [expr.const]p3.
4951ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4952 llvm::APSInt &Value,
4953 CCEKind CCE) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004954 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00004955 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4956
4957 if (checkPlaceholderForOverload(*this, From))
4958 return ExprError();
4959
4960 // C++11 [expr.const]p3 with proposed wording fixes:
4961 // A converted constant expression of type T is a core constant expression,
4962 // implicitly converted to a prvalue of type T, where the converted
4963 // expression is a literal constant expression and the implicit conversion
4964 // sequence contains only user-defined conversions, lvalue-to-rvalue
4965 // conversions, integral promotions, and integral conversions other than
4966 // narrowing conversions.
4967 ImplicitConversionSequence ICS =
4968 TryImplicitConversion(From, T,
4969 /*SuppressUserConversions=*/false,
4970 /*AllowExplicit=*/false,
4971 /*InOverloadResolution=*/false,
4972 /*CStyle=*/false,
4973 /*AllowObjcWritebackConversion=*/false);
4974 StandardConversionSequence *SCS = 0;
4975 switch (ICS.getKind()) {
4976 case ImplicitConversionSequence::StandardConversion:
4977 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004978 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004979 diag::err_typecheck_converted_constant_expression_disallowed)
4980 << From->getType() << From->getSourceRange() << T;
4981 SCS = &ICS.Standard;
4982 break;
4983 case ImplicitConversionSequence::UserDefinedConversion:
4984 // We are converting from class type to an integral or enumeration type, so
4985 // the Before sequence must be trivial.
4986 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004987 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004988 diag::err_typecheck_converted_constant_expression_disallowed)
4989 << From->getType() << From->getSourceRange() << T;
4990 SCS = &ICS.UserDefined.After;
4991 break;
4992 case ImplicitConversionSequence::AmbiguousConversion:
4993 case ImplicitConversionSequence::BadConversion:
4994 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004995 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004996 diag::err_typecheck_converted_constant_expression)
4997 << From->getType() << From->getSourceRange() << T;
4998 return ExprError();
4999
5000 case ImplicitConversionSequence::EllipsisConversion:
5001 llvm_unreachable("ellipsis conversion in converted constant expression");
5002 }
5003
5004 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
5005 if (Result.isInvalid())
5006 return Result;
5007
5008 // Check for a narrowing implicit conversion.
5009 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005010 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00005011 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
5012 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005013 case NK_Variable_Narrowing:
5014 // Implicit conversion to a narrower type, and the value is not a constant
5015 // expression. We'll diagnose this in a moment.
5016 case NK_Not_Narrowing:
5017 break;
5018
5019 case NK_Constant_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005020 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005021 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00005022 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005023 break;
5024
5025 case NK_Type_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005026 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005027 << CCE << /*Constant*/0 << From->getType() << T;
5028 break;
5029 }
5030
5031 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005032 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005033 Expr::EvalResult Eval;
5034 Eval.Diag = &Notes;
5035
Douglas Gregorebe2db72013-04-08 23:24:07 +00005036 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005037 // The expression can't be folded, so we can't keep it at this position in
5038 // the AST.
5039 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005040 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00005041 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00005042
5043 if (Notes.empty()) {
5044 // It's a constant expression.
5045 return Result;
5046 }
Richard Smithf8379a02012-01-18 23:55:52 +00005047 }
5048
5049 // It's not a constant expression. Produce an appropriate diagnostic.
5050 if (Notes.size() == 1 &&
5051 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5052 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5053 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005054 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005055 << CCE << From->getSourceRange();
5056 for (unsigned I = 0; I < Notes.size(); ++I)
5057 Diag(Notes[I].first, Notes[I].second);
5058 }
Richard Smith911e1422012-01-30 22:27:01 +00005059 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00005060}
5061
John McCallfec112d2011-09-09 06:11:02 +00005062/// dropPointerConversions - If the given standard conversion sequence
5063/// involves any pointer conversions, remove them. This may change
5064/// the result type of the conversion sequence.
5065static void dropPointerConversion(StandardConversionSequence &SCS) {
5066 if (SCS.Second == ICK_Pointer_Conversion) {
5067 SCS.Second = ICK_Identity;
5068 SCS.Third = ICK_Identity;
5069 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5070 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005071}
John McCall5c32be02010-08-24 20:38:10 +00005072
John McCallfec112d2011-09-09 06:11:02 +00005073/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5074/// convert the expression From to an Objective-C pointer type.
5075static ImplicitConversionSequence
5076TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5077 // Do an implicit conversion to 'id'.
5078 QualType Ty = S.Context.getObjCIdType();
5079 ImplicitConversionSequence ICS
5080 = TryImplicitConversion(S, From, Ty,
5081 // FIXME: Are these flags correct?
5082 /*SuppressUserConversions=*/false,
5083 /*AllowExplicit=*/true,
5084 /*InOverloadResolution=*/false,
5085 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005086 /*AllowObjCWritebackConversion=*/false,
5087 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005088
5089 // Strip off any final conversions to 'id'.
5090 switch (ICS.getKind()) {
5091 case ImplicitConversionSequence::BadConversion:
5092 case ImplicitConversionSequence::AmbiguousConversion:
5093 case ImplicitConversionSequence::EllipsisConversion:
5094 break;
5095
5096 case ImplicitConversionSequence::UserDefinedConversion:
5097 dropPointerConversion(ICS.UserDefined.After);
5098 break;
5099
5100 case ImplicitConversionSequence::StandardConversion:
5101 dropPointerConversion(ICS.Standard);
5102 break;
5103 }
5104
5105 return ICS;
5106}
5107
5108/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5109/// conversion of the expression From to an Objective-C pointer type.
5110ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005111 if (checkPlaceholderForOverload(*this, From))
5112 return ExprError();
5113
John McCall8b07ec22010-05-15 11:32:37 +00005114 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005115 ImplicitConversionSequence ICS =
5116 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005117 if (!ICS.isBad())
5118 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005119 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005120}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005121
Richard Smith8dd34252012-02-04 07:07:42 +00005122/// Determine whether the provided type is an integral type, or an enumeration
5123/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005124bool Sema::ICEConvertDiagnoser::match(QualType T) {
5125 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5126 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005127}
5128
Larisse Voufo236bec22013-06-10 06:50:24 +00005129static ExprResult
5130diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5131 Sema::ContextualImplicitConverter &Converter,
5132 QualType T, UnresolvedSetImpl &ViableConversions) {
5133
5134 if (Converter.Suppress)
5135 return ExprError();
5136
5137 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5138 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5139 CXXConversionDecl *Conv =
5140 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5141 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5142 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5143 }
5144 return SemaRef.Owned(From);
5145}
5146
5147static bool
5148diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5149 Sema::ContextualImplicitConverter &Converter,
5150 QualType T, bool HadMultipleCandidates,
5151 UnresolvedSetImpl &ExplicitConversions) {
5152 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5153 DeclAccessPair Found = ExplicitConversions[0];
5154 CXXConversionDecl *Conversion =
5155 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5156
5157 // The user probably meant to invoke the given explicit
5158 // conversion; use it.
5159 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5160 std::string TypeStr;
5161 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5162
5163 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5164 << FixItHint::CreateInsertion(From->getLocStart(),
5165 "static_cast<" + TypeStr + ">(")
5166 << FixItHint::CreateInsertion(
5167 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5168 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5169
5170 // If we aren't in a SFINAE context, build a call to the
5171 // explicit conversion function.
5172 if (SemaRef.isSFINAEContext())
5173 return true;
5174
5175 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5176 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5177 HadMultipleCandidates);
5178 if (Result.isInvalid())
5179 return true;
5180 // Record usage of conversion in an implicit cast.
5181 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5182 CK_UserDefinedConversion, Result.get(), 0,
5183 Result.get()->getValueKind());
5184 }
5185 return false;
5186}
5187
5188static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5189 Sema::ContextualImplicitConverter &Converter,
5190 QualType T, bool HadMultipleCandidates,
5191 DeclAccessPair &Found) {
5192 CXXConversionDecl *Conversion =
5193 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5194 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5195
5196 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5197 if (!Converter.SuppressConversion) {
5198 if (SemaRef.isSFINAEContext())
5199 return true;
5200
5201 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5202 << From->getSourceRange();
5203 }
5204
5205 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5206 HadMultipleCandidates);
5207 if (Result.isInvalid())
5208 return true;
5209 // Record usage of conversion in an implicit cast.
5210 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5211 CK_UserDefinedConversion, Result.get(), 0,
5212 Result.get()->getValueKind());
5213 return false;
5214}
5215
5216static ExprResult finishContextualImplicitConversion(
5217 Sema &SemaRef, SourceLocation Loc, Expr *From,
5218 Sema::ContextualImplicitConverter &Converter) {
5219 if (!Converter.match(From->getType()) && !Converter.Suppress)
5220 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5221 << From->getSourceRange();
5222
5223 return SemaRef.DefaultLvalueConversion(From);
5224}
5225
5226static void
5227collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5228 UnresolvedSetImpl &ViableConversions,
5229 OverloadCandidateSet &CandidateSet) {
5230 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5231 DeclAccessPair FoundDecl = ViableConversions[I];
5232 NamedDecl *D = FoundDecl.getDecl();
5233 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5234 if (isa<UsingShadowDecl>(D))
5235 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5236
5237 CXXConversionDecl *Conv;
5238 FunctionTemplateDecl *ConvTemplate;
5239 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5240 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5241 else
5242 Conv = cast<CXXConversionDecl>(D);
5243
5244 if (ConvTemplate)
5245 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005246 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5247 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005248 else
5249 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005250 ToType, CandidateSet,
5251 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005252 }
5253}
5254
Richard Smithccc11812013-05-21 19:05:48 +00005255/// \brief Attempt to convert the given expression to a type which is accepted
5256/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005257///
Richard Smithccc11812013-05-21 19:05:48 +00005258/// This routine will attempt to convert an expression of class type to a
5259/// type accepted by the specified converter. In C++11 and before, the class
5260/// must have a single non-explicit conversion function converting to a matching
5261/// type. In C++1y, there can be multiple such conversion functions, but only
5262/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005263///
Douglas Gregor4799d032010-06-30 00:20:43 +00005264/// \param Loc The source location of the construct that requires the
5265/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005266///
James Dennett18348b62012-06-22 08:52:37 +00005267/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005268///
Richard Smithccc11812013-05-21 19:05:48 +00005269/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005270///
Douglas Gregor4799d032010-06-30 00:20:43 +00005271/// \returns The expression, converted to an integral or enumeration type if
5272/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005273ExprResult Sema::PerformContextualImplicitConversion(
5274 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005275 // We can't perform any more checking for type-dependent expressions.
5276 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00005277 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005278
Eli Friedman1da70392012-01-26 00:26:18 +00005279 // Process placeholders immediately.
5280 if (From->hasPlaceholderType()) {
5281 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005282 if (result.isInvalid())
5283 return result;
Eli Friedman1da70392012-01-26 00:26:18 +00005284 From = result.take();
5285 }
5286
Richard Smithccc11812013-05-21 19:05:48 +00005287 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005288 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005289 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005290 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005291
5292 // FIXME: Check for missing '()' if T is a function type?
5293
Richard Smithccc11812013-05-21 19:05:48 +00005294 // We can only perform contextual implicit conversions on objects of class
5295 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005296 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005297 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005298 if (!Converter.Suppress)
5299 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00005300 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005301 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005302
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005303 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005304 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005305 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005306 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005307
5308 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5309 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5310
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005311 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Richard Smithccc11812013-05-21 19:05:48 +00005312 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005313 }
Richard Smithccc11812013-05-21 19:05:48 +00005314 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005315
5316 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCallb268a282010-08-23 23:25:46 +00005317 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005318
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005319 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005320 UnresolvedSet<4>
5321 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005322 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005323 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo236bec22013-06-10 06:50:24 +00005324 CXXRecordDecl::conversion_iterator> Conversions =
5325 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005326
Larisse Voufo236bec22013-06-10 06:50:24 +00005327 bool HadMultipleCandidates =
5328 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005329
Larisse Voufo236bec22013-06-10 06:50:24 +00005330 // To check that there is only one target type, in C++1y:
5331 QualType ToType;
5332 bool HasUniqueTargetType = true;
5333
5334 // Collect explicit or viable (potentially in C++1y) conversions.
5335 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5336 E = Conversions.second;
5337 I != E; ++I) {
5338 NamedDecl *D = (*I)->getUnderlyingDecl();
5339 CXXConversionDecl *Conversion;
5340 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5341 if (ConvTemplate) {
5342 if (getLangOpts().CPlusPlus1y)
5343 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5344 else
5345 continue; // C++11 does not consider conversion operator templates(?).
5346 } else
5347 Conversion = cast<CXXConversionDecl>(D);
5348
5349 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5350 "Conversion operator templates are considered potentially "
5351 "viable in C++1y");
5352
5353 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5354 if (Converter.match(CurToType) || ConvTemplate) {
5355
5356 if (Conversion->isExplicit()) {
5357 // FIXME: For C++1y, do we need this restriction?
5358 // cf. diagnoseNoViableConversion()
5359 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005360 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005361 } else {
5362 if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5363 if (ToType.isNull())
5364 ToType = CurToType.getUnqualifiedType();
5365 else if (HasUniqueTargetType &&
5366 (CurToType.getUnqualifiedType() != ToType))
5367 HasUniqueTargetType = false;
5368 }
5369 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005370 }
Richard Smith8dd34252012-02-04 07:07:42 +00005371 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005372 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005373
Larisse Voufo236bec22013-06-10 06:50:24 +00005374 if (getLangOpts().CPlusPlus1y) {
5375 // C++1y [conv]p6:
5376 // ... An expression e of class type E appearing in such a context
5377 // is said to be contextually implicitly converted to a specified
5378 // type T and is well-formed if and only if e can be implicitly
5379 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005380 // for conversion functions whose return type is cv T or reference to
5381 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005382 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005383
Larisse Voufo236bec22013-06-10 06:50:24 +00005384 // If no unique T is found:
5385 if (ToType.isNull()) {
5386 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5387 HadMultipleCandidates,
5388 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005389 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005390 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005391 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005392
Larisse Voufo236bec22013-06-10 06:50:24 +00005393 // If more than one unique Ts are found:
5394 if (!HasUniqueTargetType)
5395 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5396 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005397
Larisse Voufo236bec22013-06-10 06:50:24 +00005398 // If one unique T is found:
5399 // First, build a candidate set from the previously recorded
5400 // potentially viable conversions.
5401 OverloadCandidateSet CandidateSet(Loc);
5402 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5403 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005404
Larisse Voufo236bec22013-06-10 06:50:24 +00005405 // Then, perform overload resolution over the candidate set.
5406 OverloadCandidateSet::iterator Best;
5407 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5408 case OR_Success: {
5409 // Apply this conversion.
5410 DeclAccessPair Found =
5411 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5412 if (recordConversion(*this, Loc, From, Converter, T,
5413 HadMultipleCandidates, Found))
5414 return ExprError();
5415 break;
5416 }
5417 case OR_Ambiguous:
5418 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5419 ViableConversions);
5420 case OR_No_Viable_Function:
5421 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5422 HadMultipleCandidates,
5423 ExplicitConversions))
5424 return ExprError();
5425 // fall through 'OR_Deleted' case.
5426 case OR_Deleted:
5427 // We'll complain below about a non-integral condition type.
5428 break;
5429 }
5430 } else {
5431 switch (ViableConversions.size()) {
5432 case 0: {
5433 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5434 HadMultipleCandidates,
5435 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005436 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005437
Larisse Voufo236bec22013-06-10 06:50:24 +00005438 // We'll complain below about a non-integral condition type.
5439 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005440 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005441 case 1: {
5442 // Apply this conversion.
5443 DeclAccessPair Found = ViableConversions[0];
5444 if (recordConversion(*this, Loc, From, Converter, T,
5445 HadMultipleCandidates, Found))
5446 return ExprError();
5447 break;
5448 }
5449 default:
5450 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5451 ViableConversions);
5452 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005453 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005454
Larisse Voufo236bec22013-06-10 06:50:24 +00005455 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005456}
5457
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005458/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005459/// candidate functions, using the given function call arguments. If
5460/// @p SuppressUserConversions, then don't allow user-defined
5461/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005462///
James Dennett2a4d13c2012-06-15 07:13:21 +00005463/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005464/// based on an incomplete set of function arguments. This feature is used by
5465/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005466void
5467Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005468 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005469 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005470 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005471 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005472 bool PartialOverloading,
5473 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005474 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005475 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005476 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005477 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005478 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005479
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005480 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005481 if (!isa<CXXConstructorDecl>(Method)) {
5482 // If we get here, it's because we're calling a member function
5483 // that is named without a member access expression (e.g.,
5484 // "this->f") that was either written explicitly or created
5485 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005486 // function, e.g., X::f(). We use an empty type for the implied
5487 // object argument (C++ [over.call.func]p3), and the acting context
5488 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005489 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005490 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005491 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005492 return;
5493 }
5494 // We treat a constructor like a non-member function, since its object
5495 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005496 }
5497
Douglas Gregorff7028a2009-11-13 23:59:09 +00005498 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005499 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005500
Richard Smith8b86f2d2013-11-04 01:48:18 +00005501 // C++11 [class.copy]p11: [DR1402]
5502 // A defaulted move constructor that is defined as deleted is ignored by
5503 // overload resolution.
5504 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5505 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5506 Constructor->isMoveConstructor())
5507 return;
5508
Douglas Gregor27381f32009-11-23 12:27:39 +00005509 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005510 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005511
Richard Smith8b86f2d2013-11-04 01:48:18 +00005512 if (Constructor) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00005513 // C++ [class.copy]p3:
5514 // A member function template is never instantiated to perform the copy
5515 // of a class object to an object of its class type.
5516 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005517 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005518 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005519 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5520 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005521 return;
5522 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005523
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005524 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005525 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005526 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005527 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005528 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005529 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005530 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005531 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005532
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005533 unsigned NumArgsInProto = Proto->getNumArgs();
5534
5535 // (C++ 13.3.2p2): A candidate function having fewer than m
5536 // parameters is viable only if it has an ellipsis in its parameter
5537 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005538 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005539 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005540 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005541 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005542 return;
5543 }
5544
5545 // (C++ 13.3.2p2): A candidate function having more than m parameters
5546 // is viable only if the (m+1)st parameter has a default argument
5547 // (8.3.6). For the purposes of overload resolution, the
5548 // parameter list is truncated on the right, so that there are
5549 // exactly m parameters.
5550 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005551 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005552 // Not enough arguments.
5553 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005554 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005555 return;
5556 }
5557
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005558 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005559 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005560 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5561 if (CheckCUDATarget(Caller, Function)) {
5562 Candidate.Viable = false;
5563 Candidate.FailureKind = ovl_fail_bad_target;
5564 return;
5565 }
5566
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005567 // Determine the implicit conversion sequences for each of the
5568 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005569 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005570 if (ArgIdx < NumArgsInProto) {
5571 // (C++ 13.3.2p3): for F to be a viable function, there shall
5572 // exist for each argument an implicit conversion sequence
5573 // (13.3.3.1) that converts that argument to the corresponding
5574 // parameter of F.
5575 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005576 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005577 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005578 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005579 /*InOverloadResolution=*/true,
5580 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005581 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005582 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005583 if (Candidate.Conversions[ArgIdx].isBad()) {
5584 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005585 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005586 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005587 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005588 } else {
5589 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5590 // argument for which there is no corresponding parameter is
5591 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005592 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005593 }
5594 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005595
5596 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5597 Candidate.Viable = false;
5598 Candidate.FailureKind = ovl_fail_enable_if;
5599 Candidate.DeductionFailure.Data = FailedAttr;
5600 return;
5601 }
5602}
5603
5604static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5605
5606EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5607 bool MissingImplicitThis) {
5608 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5609 // we need to find the first failing one.
5610 if (!Function->hasAttrs())
5611 return 0;
5612 AttrVec Attrs = Function->getAttrs();
5613 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5614 IsNotEnableIfAttr);
5615 if (Attrs.begin() == E)
5616 return 0;
5617 std::reverse(Attrs.begin(), E);
5618
5619 SFINAETrap Trap(*this);
5620
5621 // Convert the arguments.
5622 SmallVector<Expr *, 16> ConvertedArgs;
5623 bool InitializationFailed = false;
5624 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5625 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5626 !cast<CXXMethodDecl>(Function)->isStatic()) {
5627 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5628 ExprResult R =
5629 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
5630 Method, Method);
5631 if (R.isInvalid()) {
5632 InitializationFailed = true;
5633 break;
5634 }
5635 ConvertedArgs.push_back(R.take());
5636 } else {
5637 ExprResult R =
5638 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5639 Context,
5640 Function->getParamDecl(i)),
5641 SourceLocation(),
5642 Args[i]);
5643 if (R.isInvalid()) {
5644 InitializationFailed = true;
5645 break;
5646 }
5647 ConvertedArgs.push_back(R.take());
5648 }
5649 }
5650
5651 if (InitializationFailed || Trap.hasErrorOccurred())
5652 return cast<EnableIfAttr>(Attrs[0]);
5653
5654 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5655 APValue Result;
5656 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5657 if (!EIA->getCond()->EvaluateWithSubstitution(
5658 Result, Context, Function,
5659 llvm::ArrayRef<const Expr*>(ConvertedArgs.data(),
5660 ConvertedArgs.size())) ||
5661 !Result.isInt() || !Result.getInt().getBoolValue()) {
5662 return EIA;
5663 }
5664 }
5665 return 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005666}
5667
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005668/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005669/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005670void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005671 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005672 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005673 bool SuppressUserConversions,
5674 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005675 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005676 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5677 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005678 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005679 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005680 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005681 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005682 Args.slice(1), CandidateSet,
5683 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005684 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005685 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005686 SuppressUserConversions);
5687 } else {
John McCalla0296f72010-03-19 07:35:19 +00005688 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005689 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5690 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005691 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005692 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005693 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005694 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005695 Args[0]->Classify(Context), Args.slice(1),
5696 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005697 else
John McCalla0296f72010-03-19 07:35:19 +00005698 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005699 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005700 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005701 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005702 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005703}
5704
John McCallf0f1cf02009-11-17 07:50:12 +00005705/// AddMethodCandidate - Adds a named decl (which is some kind of
5706/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005707void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005708 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005709 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005710 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00005711 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005712 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005713 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005714 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005715
5716 if (isa<UsingShadowDecl>(Decl))
5717 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005718
John McCallf0f1cf02009-11-17 07:50:12 +00005719 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5720 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5721 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005722 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5723 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005724 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005725 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005726 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005727 } else {
John McCalla0296f72010-03-19 07:35:19 +00005728 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005729 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005730 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005731 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005732 }
5733}
5734
Douglas Gregor436424c2008-11-18 23:14:02 +00005735/// AddMethodCandidate - Adds the given C++ member function to the set
5736/// of candidate functions, using the given function call arguments
5737/// and the object argument (@c Object). For example, in a call
5738/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5739/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5740/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005741/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005742void
John McCalla0296f72010-03-19 07:35:19 +00005743Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005744 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005745 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005746 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005747 OverloadCandidateSet &CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005748 bool SuppressUserConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005749 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005750 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005751 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005752 assert(!isa<CXXConstructorDecl>(Method) &&
5753 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005754
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005755 if (!CandidateSet.isNewCandidate(Method))
5756 return;
5757
Richard Smith8b86f2d2013-11-04 01:48:18 +00005758 // C++11 [class.copy]p23: [DR1402]
5759 // A defaulted move assignment operator that is defined as deleted is
5760 // ignored by overload resolution.
5761 if (Method->isDefaulted() && Method->isDeleted() &&
5762 Method->isMoveAssignmentOperator())
5763 return;
5764
Douglas Gregor27381f32009-11-23 12:27:39 +00005765 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005766 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005767
Douglas Gregor436424c2008-11-18 23:14:02 +00005768 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005769 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005770 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005771 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005772 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005773 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005774 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005775
5776 unsigned NumArgsInProto = Proto->getNumArgs();
5777
5778 // (C++ 13.3.2p2): A candidate function having fewer than m
5779 // parameters is viable only if it has an ellipsis in its parameter
5780 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005781 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005782 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005783 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005784 return;
5785 }
5786
5787 // (C++ 13.3.2p2): A candidate function having more than m parameters
5788 // is viable only if the (m+1)st parameter has a default argument
5789 // (8.3.6). For the purposes of overload resolution, the
5790 // parameter list is truncated on the right, so that there are
5791 // exactly m parameters.
5792 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005793 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005794 // Not enough arguments.
5795 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005796 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005797 return;
5798 }
5799
5800 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005801
John McCall6e9f8f62009-12-03 04:06:58 +00005802 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005803 // The implicit object argument is ignored.
5804 Candidate.IgnoreObjectArgument = true;
5805 else {
5806 // Determine the implicit conversion sequence for the object
5807 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005808 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005809 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5810 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005811 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005812 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005813 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005814 return;
5815 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005816 }
5817
5818 // Determine the implicit conversion sequences for each of the
5819 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005820 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005821 if (ArgIdx < NumArgsInProto) {
5822 // (C++ 13.3.2p3): for F to be a viable function, there shall
5823 // exist for each argument an implicit conversion sequence
5824 // (13.3.3.1) that converts that argument to the corresponding
5825 // parameter of F.
5826 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005827 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005828 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005829 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005830 /*InOverloadResolution=*/true,
5831 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005832 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005833 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005834 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005835 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005836 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005837 }
5838 } else {
5839 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5840 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005841 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005842 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005843 }
5844 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005845
5846 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
5847 Candidate.Viable = false;
5848 Candidate.FailureKind = ovl_fail_enable_if;
5849 Candidate.DeductionFailure.Data = FailedAttr;
5850 return;
5851 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005852}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005853
Douglas Gregor97628d62009-08-21 00:16:32 +00005854/// \brief Add a C++ member function template as a candidate to the candidate
5855/// set, using template argument deduction to produce an appropriate member
5856/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005857void
Douglas Gregor97628d62009-08-21 00:16:32 +00005858Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005859 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005860 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005861 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005862 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005863 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005864 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005865 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005866 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005867 if (!CandidateSet.isNewCandidate(MethodTmpl))
5868 return;
5869
Douglas Gregor97628d62009-08-21 00:16:32 +00005870 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005871 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005872 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005873 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005874 // candidate functions in the usual way.113) A given name can refer to one
5875 // or more function templates and also to a set of overloaded non-template
5876 // functions. In such a case, the candidate functions generated from each
5877 // function template are combined with the set of non-template candidate
5878 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005879 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005880 FunctionDecl *Specialization = 0;
5881 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005882 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5883 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005884 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005885 Candidate.FoundDecl = FoundDecl;
5886 Candidate.Function = MethodTmpl->getTemplatedDecl();
5887 Candidate.Viable = false;
5888 Candidate.FailureKind = ovl_fail_bad_deduction;
5889 Candidate.IsSurrogate = false;
5890 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005891 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005892 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005893 Info);
5894 return;
5895 }
Mike Stump11289f42009-09-09 15:08:12 +00005896
Douglas Gregor97628d62009-08-21 00:16:32 +00005897 // Add the function template specialization produced by template argument
5898 // deduction as a candidate.
5899 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005900 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005901 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005902 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005903 ActingContext, ObjectType, ObjectClassification, Args,
5904 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005905}
5906
Douglas Gregor05155d82009-08-21 23:19:43 +00005907/// \brief Add a C++ function template specialization as a candidate
5908/// in the candidate set, using template argument deduction to produce
5909/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005910void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005911Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005912 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005913 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005914 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005915 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005916 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005917 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5918 return;
5919
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005920 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005921 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005922 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005923 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005924 // candidate functions in the usual way.113) A given name can refer to one
5925 // or more function templates and also to a set of overloaded non-template
5926 // functions. In such a case, the candidate functions generated from each
5927 // function template are combined with the set of non-template candidate
5928 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005929 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005930 FunctionDecl *Specialization = 0;
5931 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005932 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5933 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005934 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005935 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005936 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5937 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005938 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005939 Candidate.IsSurrogate = false;
5940 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005941 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005942 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005943 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005944 return;
5945 }
Mike Stump11289f42009-09-09 15:08:12 +00005946
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005947 // Add the function template specialization produced by template argument
5948 // deduction as a candidate.
5949 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005950 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005951 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005952}
Mike Stump11289f42009-09-09 15:08:12 +00005953
Douglas Gregor4b60a152013-11-07 22:34:54 +00005954/// Determine whether this is an allowable conversion from the result
5955/// of an explicit conversion operator to the expected type, per C++
5956/// [over.match.conv]p1 and [over.match.ref]p1.
5957///
5958/// \param ConvType The return type of the conversion function.
5959///
5960/// \param ToType The type we are converting to.
5961///
5962/// \param AllowObjCPointerConversion Allow a conversion from one
5963/// Objective-C pointer to another.
5964///
5965/// \returns true if the conversion is allowable, false otherwise.
5966static bool isAllowableExplicitConversion(Sema &S,
5967 QualType ConvType, QualType ToType,
5968 bool AllowObjCPointerConversion) {
5969 QualType ToNonRefType = ToType.getNonReferenceType();
5970
5971 // Easy case: the types are the same.
5972 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
5973 return true;
5974
5975 // Allow qualification conversions.
5976 bool ObjCLifetimeConversion;
5977 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
5978 ObjCLifetimeConversion))
5979 return true;
5980
5981 // If we're not allowed to consider Objective-C pointer conversions,
5982 // we're done.
5983 if (!AllowObjCPointerConversion)
5984 return false;
5985
5986 // Is this an Objective-C pointer conversion?
5987 bool IncompatibleObjC = false;
5988 QualType ConvertedType;
5989 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
5990 IncompatibleObjC);
5991}
5992
Douglas Gregora1f013e2008-11-07 22:36:19 +00005993/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005994/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005995/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005996/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005997/// (which may or may not be the same type as the type that the
5998/// conversion function produces).
5999void
6000Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006001 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006002 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006003 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006004 OverloadCandidateSet& CandidateSet,
6005 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006006 assert(!Conversion->getDescribedFunctionTemplate() &&
6007 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006008 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006009 if (!CandidateSet.isNewCandidate(Conversion))
6010 return;
6011
Richard Smith2a7d4812013-05-04 07:00:32 +00006012 // If the conversion function has an undeduced return type, trigger its
6013 // deduction now.
6014 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
6015 if (DeduceReturnType(Conversion, From->getExprLoc()))
6016 return;
6017 ConvType = Conversion->getConversionType().getNonReferenceType();
6018 }
6019
Richard Smith089c3162013-09-21 21:55:46 +00006020 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6021 // operator is only a candidate if its return type is the target type or
6022 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006023 if (Conversion->isExplicit() &&
6024 !isAllowableExplicitConversion(*this, ConvType, ToType,
6025 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006026 return;
6027
Douglas Gregor27381f32009-11-23 12:27:39 +00006028 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006029 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006030
Douglas Gregora1f013e2008-11-07 22:36:19 +00006031 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006032 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006033 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006034 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006035 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006036 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006037 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006038 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006039 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006040 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006041 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006042
Douglas Gregor6affc782010-08-19 15:37:02 +00006043 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006044 // For conversion functions, the function is considered to be a member of
6045 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006046 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006047 //
6048 // Determine the implicit conversion sequence for the implicit
6049 // object parameter.
6050 QualType ImplicitParamType = From->getType();
6051 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6052 ImplicitParamType = FromPtrType->getPointeeType();
6053 CXXRecordDecl *ConversionContext
6054 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006055
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006056 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006057 = TryObjectArgumentInitialization(*this, From->getType(),
6058 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006059 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006060
John McCall0d1da222010-01-12 00:44:57 +00006061 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006062 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006063 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006064 return;
6065 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006066
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006067 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006068 // derived to base as such conversions are given Conversion Rank. They only
6069 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6070 QualType FromCanon
6071 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6072 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6073 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6074 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006075 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006076 return;
6077 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006078
Douglas Gregora1f013e2008-11-07 22:36:19 +00006079 // To determine what the conversion from the result of calling the
6080 // conversion function to the type we're eventually trying to
6081 // convert to (ToType), we need to synthesize a call to the
6082 // conversion function and attempt copy initialization from it. This
6083 // makes sure that we get the right semantics with respect to
6084 // lvalues/rvalues and the type. Fortunately, we can allocate this
6085 // call on the stack and we don't need its arguments to be
6086 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006087 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006088 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006089 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6090 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006091 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006092 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006093
Richard Smith48d24642011-07-13 22:53:21 +00006094 QualType ConversionType = Conversion->getConversionType();
6095 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006096 Candidate.Viable = false;
6097 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6098 return;
6099 }
6100
Richard Smith48d24642011-07-13 22:53:21 +00006101 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006102
Mike Stump11289f42009-09-09 15:08:12 +00006103 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006104 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6105 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006106 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006107 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006108 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006109 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006110 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006111 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006112 /*InOverloadResolution=*/false,
6113 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006114
John McCall0d1da222010-01-12 00:44:57 +00006115 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006116 case ImplicitConversionSequence::StandardConversion:
6117 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006118
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006119 // C++ [over.ics.user]p3:
6120 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006121 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006122 // shall have exact match rank.
6123 if (Conversion->getPrimaryTemplate() &&
6124 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6125 Candidate.Viable = false;
6126 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006127 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006128 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006129
Douglas Gregorcba72b12011-01-21 05:18:22 +00006130 // C++0x [dcl.init.ref]p5:
6131 // In the second case, if the reference is an rvalue reference and
6132 // the second standard conversion sequence of the user-defined
6133 // conversion sequence includes an lvalue-to-rvalue conversion, the
6134 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006135 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006136 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6137 Candidate.Viable = false;
6138 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006139 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006140 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006141 break;
6142
6143 case ImplicitConversionSequence::BadConversion:
6144 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006145 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006146 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006147
6148 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006149 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006150 "Can only end up with a standard conversion sequence or failure");
6151 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006152
6153 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6154 Candidate.Viable = false;
6155 Candidate.FailureKind = ovl_fail_enable_if;
6156 Candidate.DeductionFailure.Data = FailedAttr;
6157 return;
6158 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006159}
6160
Douglas Gregor05155d82009-08-21 23:19:43 +00006161/// \brief Adds a conversion function template specialization
6162/// candidate to the overload set, using template argument deduction
6163/// to deduce the template arguments of the conversion function
6164/// template from the type that we are converting to (C++
6165/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006166void
Douglas Gregor05155d82009-08-21 23:19:43 +00006167Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006168 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006169 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006170 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006171 OverloadCandidateSet &CandidateSet,
6172 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006173 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6174 "Only conversion function templates permitted here");
6175
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006176 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6177 return;
6178
Craig Toppere6706e42012-09-19 02:26:47 +00006179 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00006180 CXXConversionDecl *Specialization = 0;
6181 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006182 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006183 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006184 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006185 Candidate.FoundDecl = FoundDecl;
6186 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6187 Candidate.Viable = false;
6188 Candidate.FailureKind = ovl_fail_bad_deduction;
6189 Candidate.IsSurrogate = false;
6190 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006191 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006192 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006193 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006194 return;
6195 }
Mike Stump11289f42009-09-09 15:08:12 +00006196
Douglas Gregor05155d82009-08-21 23:19:43 +00006197 // Add the conversion function template specialization produced by
6198 // template argument deduction as a candidate.
6199 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006200 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006201 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006202}
6203
Douglas Gregorab7897a2008-11-19 22:57:39 +00006204/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6205/// converts the given @c Object to a function pointer via the
6206/// conversion function @c Conversion, and then attempts to call it
6207/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6208/// the type of function that we'll eventually be calling.
6209void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006210 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006211 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006212 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006213 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006214 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006215 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006216 if (!CandidateSet.isNewCandidate(Conversion))
6217 return;
6218
Douglas Gregor27381f32009-11-23 12:27:39 +00006219 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006220 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006221
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006222 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006223 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006224 Candidate.Function = 0;
6225 Candidate.Surrogate = Conversion;
6226 Candidate.Viable = true;
6227 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006228 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006229 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006230
6231 // Determine the implicit conversion sequence for the implicit
6232 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006233 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006234 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006235 Object->Classify(Context),
6236 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006237 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006238 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006239 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006240 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006241 return;
6242 }
6243
6244 // The first conversion is actually a user-defined conversion whose
6245 // first conversion is ObjectInit's standard conversion (which is
6246 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006247 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006248 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006249 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006250 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006251 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006252 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006253 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006254 = Candidate.Conversions[0].UserDefined.Before;
6255 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6256
Mike Stump11289f42009-09-09 15:08:12 +00006257 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00006258 unsigned NumArgsInProto = Proto->getNumArgs();
6259
6260 // (C++ 13.3.2p2): A candidate function having fewer than m
6261 // parameters is viable only if it has an ellipsis in its parameter
6262 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006263 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006264 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006265 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006266 return;
6267 }
6268
6269 // Function types don't have any default arguments, so just check if
6270 // we have enough arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006271 if (Args.size() < NumArgsInProto) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006272 // Not enough arguments.
6273 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006274 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006275 return;
6276 }
6277
6278 // Determine the implicit conversion sequences for each of the
6279 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006280 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006281 if (ArgIdx < NumArgsInProto) {
6282 // (C++ 13.3.2p3): for F to be a viable function, there shall
6283 // exist for each argument an implicit conversion sequence
6284 // (13.3.3.1) that converts that argument to the corresponding
6285 // parameter of F.
6286 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006287 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006288 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006289 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006290 /*InOverloadResolution=*/false,
6291 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006292 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006293 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006294 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006295 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006296 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006297 }
6298 } else {
6299 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6300 // argument for which there is no corresponding parameter is
6301 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006302 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006303 }
6304 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006305
6306 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6307 Candidate.Viable = false;
6308 Candidate.FailureKind = ovl_fail_enable_if;
6309 Candidate.DeductionFailure.Data = FailedAttr;
6310 return;
6311 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006312}
6313
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006314/// \brief Add overload candidates for overloaded operators that are
6315/// member functions.
6316///
6317/// Add the overloaded operator candidates that are member functions
6318/// for the operator Op that was used in an operator expression such
6319/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6320/// CandidateSet will store the added overload candidates. (C++
6321/// [over.match.oper]).
6322void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6323 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006324 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006325 OverloadCandidateSet& CandidateSet,
6326 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006327 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6328
6329 // C++ [over.match.oper]p3:
6330 // For a unary operator @ with an operand of a type whose
6331 // cv-unqualified version is T1, and for a binary operator @ with
6332 // a left operand of a type whose cv-unqualified version is T1 and
6333 // a right operand of a type whose cv-unqualified version is T2,
6334 // three sets of candidate functions, designated member
6335 // candidates, non-member candidates and built-in candidates, are
6336 // constructed as follows:
6337 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006338
Richard Smith0feaf0c2013-04-20 12:41:22 +00006339 // -- If T1 is a complete class type or a class currently being
6340 // defined, the set of member candidates is the result of the
6341 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6342 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006343 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006344 // Complete the type if it can be completed.
6345 RequireCompleteType(OpLoc, T1, 0);
6346 // If the type is neither complete nor being defined, bail out now.
6347 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006348 return;
Mike Stump11289f42009-09-09 15:08:12 +00006349
John McCall27b18f82009-11-17 02:14:36 +00006350 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6351 LookupQualifiedName(Operators, T1Rec->getDecl());
6352 Operators.suppressDiagnostics();
6353
Mike Stump11289f42009-09-09 15:08:12 +00006354 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006355 OperEnd = Operators.end();
6356 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006357 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006358 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006359 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006360 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006361 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006362 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006363 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006364}
6365
Douglas Gregora11693b2008-11-12 17:17:38 +00006366/// AddBuiltinCandidate - Add a candidate for a built-in
6367/// operator. ResultTy and ParamTys are the result and parameter types
6368/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006369/// arguments being passed to the candidate. IsAssignmentOperator
6370/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006371/// operator. NumContextualBoolArguments is the number of arguments
6372/// (at the beginning of the argument list) that will be contextually
6373/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006374void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006375 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006376 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006377 bool IsAssignmentOperator,
6378 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006379 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006380 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006381
Douglas Gregora11693b2008-11-12 17:17:38 +00006382 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006383 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00006384 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00006385 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006386 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006387 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006388 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006389 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006390 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6391
6392 // Determine the implicit conversion sequences for each of the
6393 // arguments.
6394 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006395 Candidate.ExplicitCallArguments = Args.size();
6396 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006397 // C++ [over.match.oper]p4:
6398 // For the built-in assignment operators, conversions of the
6399 // left operand are restricted as follows:
6400 // -- no temporaries are introduced to hold the left operand, and
6401 // -- no user-defined conversions are applied to the left
6402 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006403 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006404 //
6405 // We block these conversions by turning off user-defined
6406 // conversions, since that is the only way that initialization of
6407 // a reference to a non-class type can occur from something that
6408 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006409 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006410 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006411 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006412 Candidate.Conversions[ArgIdx]
6413 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006414 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006415 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006416 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006417 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006418 /*InOverloadResolution=*/false,
6419 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006420 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006421 }
John McCall0d1da222010-01-12 00:44:57 +00006422 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006423 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006424 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006425 break;
6426 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006427 }
6428}
6429
Craig Toppercd7b0332013-07-01 06:29:40 +00006430namespace {
6431
Douglas Gregora11693b2008-11-12 17:17:38 +00006432/// BuiltinCandidateTypeSet - A set of types that will be used for the
6433/// candidate operator functions for built-in operators (C++
6434/// [over.built]). The types are separated into pointer types and
6435/// enumeration types.
6436class BuiltinCandidateTypeSet {
6437 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006438 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006439
6440 /// PointerTypes - The set of pointer types that will be used in the
6441 /// built-in candidates.
6442 TypeSet PointerTypes;
6443
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006444 /// MemberPointerTypes - The set of member pointer types that will be
6445 /// used in the built-in candidates.
6446 TypeSet MemberPointerTypes;
6447
Douglas Gregora11693b2008-11-12 17:17:38 +00006448 /// EnumerationTypes - The set of enumeration types that will be
6449 /// used in the built-in candidates.
6450 TypeSet EnumerationTypes;
6451
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006452 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006453 /// candidates.
6454 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006455
6456 /// \brief A flag indicating non-record types are viable candidates
6457 bool HasNonRecordTypes;
6458
6459 /// \brief A flag indicating whether either arithmetic or enumeration types
6460 /// were present in the candidate set.
6461 bool HasArithmeticOrEnumeralTypes;
6462
Douglas Gregor80af3132011-05-21 23:15:46 +00006463 /// \brief A flag indicating whether the nullptr type was present in the
6464 /// candidate set.
6465 bool HasNullPtrType;
6466
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006467 /// Sema - The semantic analysis instance where we are building the
6468 /// candidate type set.
6469 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006470
Douglas Gregora11693b2008-11-12 17:17:38 +00006471 /// Context - The AST context in which we will build the type sets.
6472 ASTContext &Context;
6473
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006474 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6475 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006476 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006477
6478public:
6479 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006480 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006481
Mike Stump11289f42009-09-09 15:08:12 +00006482 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006483 : HasNonRecordTypes(false),
6484 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006485 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006486 SemaRef(SemaRef),
6487 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006488
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006489 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006490 SourceLocation Loc,
6491 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006492 bool AllowExplicitConversions,
6493 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006494
6495 /// pointer_begin - First pointer type found;
6496 iterator pointer_begin() { return PointerTypes.begin(); }
6497
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006498 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006499 iterator pointer_end() { return PointerTypes.end(); }
6500
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006501 /// member_pointer_begin - First member pointer type found;
6502 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6503
6504 /// member_pointer_end - Past the last member pointer type found;
6505 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6506
Douglas Gregora11693b2008-11-12 17:17:38 +00006507 /// enumeration_begin - First enumeration type found;
6508 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6509
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006510 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006511 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006512
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006513 iterator vector_begin() { return VectorTypes.begin(); }
6514 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006515
6516 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6517 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006518 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006519};
6520
Craig Toppercd7b0332013-07-01 06:29:40 +00006521} // end anonymous namespace
6522
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006523/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006524/// the set of pointer types along with any more-qualified variants of
6525/// that type. For example, if @p Ty is "int const *", this routine
6526/// will add "int const *", "int const volatile *", "int const
6527/// restrict *", and "int const volatile restrict *" to the set of
6528/// pointer types. Returns true if the add of @p Ty itself succeeded,
6529/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006530///
6531/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006532bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006533BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6534 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006535
Douglas Gregora11693b2008-11-12 17:17:38 +00006536 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006537 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006538 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006539
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006540 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006541 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006542 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006543 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006544 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6545 PointeeTy = PTy->getPointeeType();
6546 buildObjCPtr = true;
6547 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006548 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006549 }
6550
Sebastian Redl4990a632009-11-18 20:39:26 +00006551 // Don't add qualified variants of arrays. For one, they're not allowed
6552 // (the qualifier would sink to the element type), and for another, the
6553 // only overload situation where it matters is subscript or pointer +- int,
6554 // and those shouldn't have qualifier variants anyway.
6555 if (PointeeTy->isArrayType())
6556 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006557
John McCall8ccfcb52009-09-24 19:53:00 +00006558 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006559 bool hasVolatile = VisibleQuals.hasVolatile();
6560 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006561
John McCall8ccfcb52009-09-24 19:53:00 +00006562 // Iterate through all strict supersets of BaseCVR.
6563 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6564 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006565 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006566 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006567
6568 // Skip over restrict if no restrict found anywhere in the types, or if
6569 // the type cannot be restrict-qualified.
6570 if ((CVR & Qualifiers::Restrict) &&
6571 (!hasRestrict ||
6572 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6573 continue;
6574
6575 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006576 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006577
6578 // Build qualified pointer type.
6579 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006580 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006581 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006582 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006583 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6584
6585 // Insert qualified pointer type.
6586 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006587 }
6588
6589 return true;
6590}
6591
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006592/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6593/// to the set of pointer types along with any more-qualified variants of
6594/// that type. For example, if @p Ty is "int const *", this routine
6595/// will add "int const *", "int const volatile *", "int const
6596/// restrict *", and "int const volatile restrict *" to the set of
6597/// pointer types. Returns true if the add of @p Ty itself succeeded,
6598/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006599///
6600/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006601bool
6602BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6603 QualType Ty) {
6604 // Insert this type.
6605 if (!MemberPointerTypes.insert(Ty))
6606 return false;
6607
John McCall8ccfcb52009-09-24 19:53:00 +00006608 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6609 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006610
John McCall8ccfcb52009-09-24 19:53:00 +00006611 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006612 // Don't add qualified variants of arrays. For one, they're not allowed
6613 // (the qualifier would sink to the element type), and for another, the
6614 // only overload situation where it matters is subscript or pointer +- int,
6615 // and those shouldn't have qualifier variants anyway.
6616 if (PointeeTy->isArrayType())
6617 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006618 const Type *ClassTy = PointerTy->getClass();
6619
6620 // Iterate through all strict supersets of the pointee type's CVR
6621 // qualifiers.
6622 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6623 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6624 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006625
John McCall8ccfcb52009-09-24 19:53:00 +00006626 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006627 MemberPointerTypes.insert(
6628 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006629 }
6630
6631 return true;
6632}
6633
Douglas Gregora11693b2008-11-12 17:17:38 +00006634/// AddTypesConvertedFrom - Add each of the types to which the type @p
6635/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006636/// primarily interested in pointer types and enumeration types. We also
6637/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006638/// AllowUserConversions is true if we should look at the conversion
6639/// functions of a class type, and AllowExplicitConversions if we
6640/// should also include the explicit conversion functions of a class
6641/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006642void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006643BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006644 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006645 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006646 bool AllowExplicitConversions,
6647 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006648 // Only deal with canonical types.
6649 Ty = Context.getCanonicalType(Ty);
6650
6651 // Look through reference types; they aren't part of the type of an
6652 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006653 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006654 Ty = RefTy->getPointeeType();
6655
John McCall33ddac02011-01-19 10:06:00 +00006656 // If we're dealing with an array type, decay to the pointer.
6657 if (Ty->isArrayType())
6658 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6659
6660 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006661 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006662
Chandler Carruth00a38332010-12-13 01:44:01 +00006663 // Flag if we ever add a non-record type.
6664 const RecordType *TyRec = Ty->getAs<RecordType>();
6665 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6666
Chandler Carruth00a38332010-12-13 01:44:01 +00006667 // Flag if we encounter an arithmetic type.
6668 HasArithmeticOrEnumeralTypes =
6669 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6670
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006671 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6672 PointerTypes.insert(Ty);
6673 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006674 // Insert our type, and its more-qualified variants, into the set
6675 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006676 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006677 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006678 } else if (Ty->isMemberPointerType()) {
6679 // Member pointers are far easier, since the pointee can't be converted.
6680 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6681 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006682 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006683 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006684 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006685 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006686 // We treat vector types as arithmetic types in many contexts as an
6687 // extension.
6688 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006689 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006690 } else if (Ty->isNullPtrType()) {
6691 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006692 } else if (AllowUserConversions && TyRec) {
6693 // No conversion functions in incomplete types.
6694 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6695 return;
Mike Stump11289f42009-09-09 15:08:12 +00006696
Chandler Carruth00a38332010-12-13 01:44:01 +00006697 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006698 std::pair<CXXRecordDecl::conversion_iterator,
6699 CXXRecordDecl::conversion_iterator>
6700 Conversions = ClassDecl->getVisibleConversionFunctions();
6701 for (CXXRecordDecl::conversion_iterator
6702 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006703 NamedDecl *D = I.getDecl();
6704 if (isa<UsingShadowDecl>(D))
6705 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006706
Chandler Carruth00a38332010-12-13 01:44:01 +00006707 // Skip conversion function templates; they don't tell us anything
6708 // about which builtin types we can convert to.
6709 if (isa<FunctionTemplateDecl>(D))
6710 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006711
Chandler Carruth00a38332010-12-13 01:44:01 +00006712 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6713 if (AllowExplicitConversions || !Conv->isExplicit()) {
6714 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6715 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006716 }
6717 }
6718 }
6719}
6720
Douglas Gregor84605ae2009-08-24 13:43:27 +00006721/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6722/// the volatile- and non-volatile-qualified assignment operators for the
6723/// given type to the candidate set.
6724static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6725 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00006726 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006727 OverloadCandidateSet &CandidateSet) {
6728 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006729
Douglas Gregor84605ae2009-08-24 13:43:27 +00006730 // T& operator=(T&, T)
6731 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6732 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006733 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006734 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006735
Douglas Gregor84605ae2009-08-24 13:43:27 +00006736 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6737 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006738 ParamTypes[0]
6739 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006740 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006741 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006742 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006743 }
6744}
Mike Stump11289f42009-09-09 15:08:12 +00006745
Sebastian Redl1054fae2009-10-25 17:03:50 +00006746/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6747/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006748static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6749 Qualifiers VRQuals;
6750 const RecordType *TyRec;
6751 if (const MemberPointerType *RHSMPType =
6752 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006753 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006754 else
6755 TyRec = ArgExpr->getType()->getAs<RecordType>();
6756 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006757 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006758 VRQuals.addVolatile();
6759 VRQuals.addRestrict();
6760 return VRQuals;
6761 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006762
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006763 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006764 if (!ClassDecl->hasDefinition())
6765 return VRQuals;
6766
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006767 std::pair<CXXRecordDecl::conversion_iterator,
6768 CXXRecordDecl::conversion_iterator>
6769 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006770
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006771 for (CXXRecordDecl::conversion_iterator
6772 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006773 NamedDecl *D = I.getDecl();
6774 if (isa<UsingShadowDecl>(D))
6775 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6776 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006777 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6778 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6779 CanTy = ResTypeRef->getPointeeType();
6780 // Need to go down the pointer/mempointer chain and add qualifiers
6781 // as see them.
6782 bool done = false;
6783 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006784 if (CanTy.isRestrictQualified())
6785 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006786 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6787 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006788 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006789 CanTy->getAs<MemberPointerType>())
6790 CanTy = ResTypeMPtr->getPointeeType();
6791 else
6792 done = true;
6793 if (CanTy.isVolatileQualified())
6794 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006795 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6796 return VRQuals;
6797 }
6798 }
6799 }
6800 return VRQuals;
6801}
John McCall52872982010-11-13 05:51:15 +00006802
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006803namespace {
John McCall52872982010-11-13 05:51:15 +00006804
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006805/// \brief Helper class to manage the addition of builtin operator overload
6806/// candidates. It provides shared state and utility methods used throughout
6807/// the process, as well as a helper method to add each group of builtin
6808/// operator overloads from the standard to a candidate set.
6809class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006810 // Common instance state available to all overload candidate addition methods.
6811 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00006812 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006813 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006814 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006815 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006816 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006817
Chandler Carruthc6586e52010-12-12 10:35:00 +00006818 // Define some constants used to index and iterate over the arithemetic types
6819 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006820 // The "promoted arithmetic types" are the arithmetic
6821 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006822 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00006823 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00006824 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00006825 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00006826 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00006827 LastPromotedArithmeticType = 11;
6828 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00006829
Chandler Carruthc6586e52010-12-12 10:35:00 +00006830 /// \brief Get the canonical type for a given arithmetic type index.
6831 CanQualType getArithmeticType(unsigned index) {
6832 assert(index < NumArithmeticTypes);
6833 static CanQualType ASTContext::* const
6834 ArithmeticTypes[NumArithmeticTypes] = {
6835 // Start of promoted types.
6836 &ASTContext::FloatTy,
6837 &ASTContext::DoubleTy,
6838 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006839
Chandler Carruthc6586e52010-12-12 10:35:00 +00006840 // Start of integral types.
6841 &ASTContext::IntTy,
6842 &ASTContext::LongTy,
6843 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006844 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006845 &ASTContext::UnsignedIntTy,
6846 &ASTContext::UnsignedLongTy,
6847 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006848 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006849 // End of promoted types.
6850
6851 &ASTContext::BoolTy,
6852 &ASTContext::CharTy,
6853 &ASTContext::WCharTy,
6854 &ASTContext::Char16Ty,
6855 &ASTContext::Char32Ty,
6856 &ASTContext::SignedCharTy,
6857 &ASTContext::ShortTy,
6858 &ASTContext::UnsignedCharTy,
6859 &ASTContext::UnsignedShortTy,
6860 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00006861 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00006862 };
6863 return S.Context.*ArithmeticTypes[index];
6864 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006865
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006866 /// \brief Gets the canonical type resulting from the usual arithemetic
6867 /// converions for the given arithmetic types.
6868 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6869 // Accelerator table for performing the usual arithmetic conversions.
6870 // The rules are basically:
6871 // - if either is floating-point, use the wider floating-point
6872 // - if same signedness, use the higher rank
6873 // - if same size, use unsigned of the higher rank
6874 // - use the larger type
6875 // These rules, together with the axiom that higher ranks are
6876 // never smaller, are sufficient to precompute all of these results
6877 // *except* when dealing with signed types of higher rank.
6878 // (we could precompute SLL x UI for all known platforms, but it's
6879 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00006880 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006881 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00006882 Dep=-1,
6883 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006884 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00006885 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006886 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00006887/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6888/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6889/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6890/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6891/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6892/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6893/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6894/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6895/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6896/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6897/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006898 };
6899
6900 assert(L < LastPromotedArithmeticType);
6901 assert(R < LastPromotedArithmeticType);
6902 int Idx = ConversionsTable[L][R];
6903
6904 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006905 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006906
6907 // Slow path: we need to compare widths.
6908 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006909 CanQualType LT = getArithmeticType(L),
6910 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006911 unsigned LW = S.Context.getIntWidth(LT),
6912 RW = S.Context.getIntWidth(RT);
6913
6914 // If they're different widths, use the signed type.
6915 if (LW > RW) return LT;
6916 else if (LW < RW) return RT;
6917
6918 // Otherwise, use the unsigned type of the signed type's rank.
6919 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6920 assert(L == SLL || R == SLL);
6921 return S.Context.UnsignedLongLongTy;
6922 }
6923
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006924 /// \brief Helper method to factor out the common pattern of adding overloads
6925 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006926 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006927 bool HasVolatile,
6928 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006929 QualType ParamTypes[2] = {
6930 S.Context.getLValueReferenceType(CandidateTy),
6931 S.Context.IntTy
6932 };
6933
6934 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00006935 if (Args.size() == 1)
6936 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006937 else
Richard Smithe54c3072013-05-05 15:51:06 +00006938 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006939
6940 // Use a heuristic to reduce number of builtin candidates in the set:
6941 // add volatile version only if there are conversions to a volatile type.
6942 if (HasVolatile) {
6943 ParamTypes[0] =
6944 S.Context.getLValueReferenceType(
6945 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00006946 if (Args.size() == 1)
6947 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006948 else
Richard Smithe54c3072013-05-05 15:51:06 +00006949 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006950 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00006951
6952 // Add restrict version only if there are conversions to a restrict type
6953 // and our candidate type is a non-restrict-qualified pointer.
6954 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6955 !CandidateTy.isRestrictQualified()) {
6956 ParamTypes[0]
6957 = S.Context.getLValueReferenceType(
6958 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00006959 if (Args.size() == 1)
6960 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006961 else
Richard Smithe54c3072013-05-05 15:51:06 +00006962 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006963
6964 if (HasVolatile) {
6965 ParamTypes[0]
6966 = S.Context.getLValueReferenceType(
6967 S.Context.getCVRQualifiedType(CandidateTy,
6968 (Qualifiers::Volatile |
6969 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00006970 if (Args.size() == 1)
6971 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006972 else
Richard Smithe54c3072013-05-05 15:51:06 +00006973 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006974 }
6975 }
6976
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006977 }
6978
6979public:
6980 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00006981 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006982 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006983 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006984 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006985 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00006986 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006987 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006988 HasArithmeticOrEnumeralCandidateType(
6989 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006990 CandidateTypes(CandidateTypes),
6991 CandidateSet(CandidateSet) {
6992 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006993 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006994 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006995 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00006996 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006997 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006998 assert(getArithmeticType(FirstPromotedArithmeticType)
6999 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007000 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007001 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007002 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007003 "Invalid last promoted arithmetic type");
7004 }
7005
7006 // C++ [over.built]p3:
7007 //
7008 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7009 // is either volatile or empty, there exist candidate operator
7010 // functions of the form
7011 //
7012 // VQ T& operator++(VQ T&);
7013 // T operator++(VQ T&, int);
7014 //
7015 // C++ [over.built]p4:
7016 //
7017 // For every pair (T, VQ), where T is an arithmetic type other
7018 // than bool, and VQ is either volatile or empty, there exist
7019 // candidate operator functions of the form
7020 //
7021 // VQ T& operator--(VQ T&);
7022 // T operator--(VQ T&, int);
7023 void addPlusPlusMinusMinusArithmeticOverloads(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 Arith = (Op == OO_PlusPlus? 0 : 1);
7028 Arith < NumArithmeticTypes; ++Arith) {
7029 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007030 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007031 VisibleTypeConversionsQuals.hasVolatile(),
7032 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007033 }
7034 }
7035
7036 // C++ [over.built]p5:
7037 //
7038 // For every pair (T, VQ), where T is a cv-qualified or
7039 // cv-unqualified object type, and VQ is either volatile or
7040 // empty, there exist candidate operator functions of the form
7041 //
7042 // T*VQ& operator++(T*VQ&);
7043 // T*VQ& operator--(T*VQ&);
7044 // T* operator++(T*VQ&, int);
7045 // T* operator--(T*VQ&, int);
7046 void addPlusPlusMinusMinusPointerOverloads() {
7047 for (BuiltinCandidateTypeSet::iterator
7048 Ptr = CandidateTypes[0].pointer_begin(),
7049 PtrEnd = CandidateTypes[0].pointer_end();
7050 Ptr != PtrEnd; ++Ptr) {
7051 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007052 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007053 continue;
7054
7055 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007056 (!(*Ptr).isVolatileQualified() &&
7057 VisibleTypeConversionsQuals.hasVolatile()),
7058 (!(*Ptr).isRestrictQualified() &&
7059 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007060 }
7061 }
7062
7063 // C++ [over.built]p6:
7064 // For every cv-qualified or cv-unqualified object type T, there
7065 // exist candidate operator functions of the form
7066 //
7067 // T& operator*(T*);
7068 //
7069 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007070 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007071 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007072 // T& operator*(T*);
7073 void addUnaryStarPointerOverloads() {
7074 for (BuiltinCandidateTypeSet::iterator
7075 Ptr = CandidateTypes[0].pointer_begin(),
7076 PtrEnd = CandidateTypes[0].pointer_end();
7077 Ptr != PtrEnd; ++Ptr) {
7078 QualType ParamTy = *Ptr;
7079 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007080 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7081 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007082
Douglas Gregor02824322011-01-26 19:30:28 +00007083 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7084 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7085 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007086
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007087 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007088 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007089 }
7090 }
7091
7092 // C++ [over.built]p9:
7093 // For every promoted arithmetic type T, there exist candidate
7094 // operator functions of the form
7095 //
7096 // T operator+(T);
7097 // T operator-(T);
7098 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007099 if (!HasArithmeticOrEnumeralCandidateType)
7100 return;
7101
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007102 for (unsigned Arith = FirstPromotedArithmeticType;
7103 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007104 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007105 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007106 }
7107
7108 // Extension: We also add these operators for vector types.
7109 for (BuiltinCandidateTypeSet::iterator
7110 Vec = CandidateTypes[0].vector_begin(),
7111 VecEnd = CandidateTypes[0].vector_end();
7112 Vec != VecEnd; ++Vec) {
7113 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007114 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007115 }
7116 }
7117
7118 // C++ [over.built]p8:
7119 // For every type T, there exist candidate operator functions of
7120 // the form
7121 //
7122 // T* operator+(T*);
7123 void addUnaryPlusPointerOverloads() {
7124 for (BuiltinCandidateTypeSet::iterator
7125 Ptr = CandidateTypes[0].pointer_begin(),
7126 PtrEnd = CandidateTypes[0].pointer_end();
7127 Ptr != PtrEnd; ++Ptr) {
7128 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007129 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007130 }
7131 }
7132
7133 // C++ [over.built]p10:
7134 // For every promoted integral type T, there exist candidate
7135 // operator functions of the form
7136 //
7137 // T operator~(T);
7138 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007139 if (!HasArithmeticOrEnumeralCandidateType)
7140 return;
7141
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007142 for (unsigned Int = FirstPromotedIntegralType;
7143 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007144 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007145 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007146 }
7147
7148 // Extension: We also add this operator for vector types.
7149 for (BuiltinCandidateTypeSet::iterator
7150 Vec = CandidateTypes[0].vector_begin(),
7151 VecEnd = CandidateTypes[0].vector_end();
7152 Vec != VecEnd; ++Vec) {
7153 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007154 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007155 }
7156 }
7157
7158 // C++ [over.match.oper]p16:
7159 // For every pointer to member type T, there exist candidate operator
7160 // functions of the form
7161 //
7162 // bool operator==(T,T);
7163 // bool operator!=(T,T);
7164 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7165 /// Set of (canonical) types that we've already handled.
7166 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7167
Richard Smithe54c3072013-05-05 15:51:06 +00007168 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007169 for (BuiltinCandidateTypeSet::iterator
7170 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7171 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7172 MemPtr != MemPtrEnd;
7173 ++MemPtr) {
7174 // Don't add the same builtin candidate twice.
7175 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7176 continue;
7177
7178 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007179 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007180 }
7181 }
7182 }
7183
7184 // C++ [over.built]p15:
7185 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007186 // For every T, where T is an enumeration type, a pointer type, or
7187 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007188 //
7189 // bool operator<(T, T);
7190 // bool operator>(T, T);
7191 // bool operator<=(T, T);
7192 // bool operator>=(T, T);
7193 // bool operator==(T, T);
7194 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007195 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007196 // C++ [over.match.oper]p3:
7197 // [...]the built-in candidates include all of the candidate operator
7198 // functions defined in 13.6 that, compared to the given operator, [...]
7199 // do not have the same parameter-type-list as any non-template non-member
7200 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007201 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007202 // Note that in practice, this only affects enumeration types because there
7203 // aren't any built-in candidates of record type, and a user-defined operator
7204 // must have an operand of record or enumeration type. Also, the only other
7205 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007206 // cannot be overloaded for enumeration types, so this is the only place
7207 // where we must suppress candidates like this.
7208 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7209 UserDefinedBinaryOperators;
7210
Richard Smithe54c3072013-05-05 15:51:06 +00007211 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007212 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7213 CandidateTypes[ArgIdx].enumeration_end()) {
7214 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7215 CEnd = CandidateSet.end();
7216 C != CEnd; ++C) {
7217 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7218 continue;
7219
Eli Friedman14f082b2012-09-18 21:52:24 +00007220 if (C->Function->isFunctionTemplateSpecialization())
7221 continue;
7222
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007223 QualType FirstParamType =
7224 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7225 QualType SecondParamType =
7226 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7227
7228 // Skip if either parameter isn't of enumeral type.
7229 if (!FirstParamType->isEnumeralType() ||
7230 !SecondParamType->isEnumeralType())
7231 continue;
7232
7233 // Add this operator to the set of known user-defined operators.
7234 UserDefinedBinaryOperators.insert(
7235 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7236 S.Context.getCanonicalType(SecondParamType)));
7237 }
7238 }
7239 }
7240
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007241 /// Set of (canonical) types that we've already handled.
7242 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7243
Richard Smithe54c3072013-05-05 15:51:06 +00007244 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007245 for (BuiltinCandidateTypeSet::iterator
7246 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7247 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7248 Ptr != PtrEnd; ++Ptr) {
7249 // Don't add the same builtin candidate twice.
7250 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7251 continue;
7252
7253 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007254 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007255 }
7256 for (BuiltinCandidateTypeSet::iterator
7257 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7258 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7259 Enum != EnumEnd; ++Enum) {
7260 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7261
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007262 // Don't add the same builtin candidate twice, or if a user defined
7263 // candidate exists.
7264 if (!AddedTypes.insert(CanonType) ||
7265 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7266 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007267 continue;
7268
7269 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007270 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007271 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007272
7273 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7274 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7275 if (AddedTypes.insert(NullPtrTy) &&
Richard Smithe54c3072013-05-05 15:51:06 +00007276 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007277 NullPtrTy))) {
7278 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007279 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007280 CandidateSet);
7281 }
7282 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007283 }
7284 }
7285
7286 // C++ [over.built]p13:
7287 //
7288 // For every cv-qualified or cv-unqualified object type T
7289 // there exist candidate operator functions of the form
7290 //
7291 // T* operator+(T*, ptrdiff_t);
7292 // T& operator[](T*, ptrdiff_t); [BELOW]
7293 // T* operator-(T*, ptrdiff_t);
7294 // T* operator+(ptrdiff_t, T*);
7295 // T& operator[](ptrdiff_t, T*); [BELOW]
7296 //
7297 // C++ [over.built]p14:
7298 //
7299 // For every T, where T is a pointer to object type, there
7300 // exist candidate operator functions of the form
7301 //
7302 // ptrdiff_t operator-(T, T);
7303 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7304 /// Set of (canonical) types that we've already handled.
7305 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7306
7307 for (int Arg = 0; Arg < 2; ++Arg) {
7308 QualType AsymetricParamTypes[2] = {
7309 S.Context.getPointerDiffType(),
7310 S.Context.getPointerDiffType(),
7311 };
7312 for (BuiltinCandidateTypeSet::iterator
7313 Ptr = CandidateTypes[Arg].pointer_begin(),
7314 PtrEnd = CandidateTypes[Arg].pointer_end();
7315 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007316 QualType PointeeTy = (*Ptr)->getPointeeType();
7317 if (!PointeeTy->isObjectType())
7318 continue;
7319
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007320 AsymetricParamTypes[Arg] = *Ptr;
7321 if (Arg == 0 || Op == OO_Plus) {
7322 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7323 // T* operator+(ptrdiff_t, T*);
Richard Smithe54c3072013-05-05 15:51:06 +00007324 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007325 }
7326 if (Op == OO_Minus) {
7327 // ptrdiff_t operator-(T, T);
7328 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7329 continue;
7330
7331 QualType ParamTypes[2] = { *Ptr, *Ptr };
7332 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007333 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007334 }
7335 }
7336 }
7337 }
7338
7339 // C++ [over.built]p12:
7340 //
7341 // For every pair of promoted arithmetic types L and R, there
7342 // exist candidate operator functions of the form
7343 //
7344 // LR operator*(L, R);
7345 // LR operator/(L, R);
7346 // LR operator+(L, R);
7347 // LR operator-(L, R);
7348 // bool operator<(L, R);
7349 // bool operator>(L, R);
7350 // bool operator<=(L, R);
7351 // bool operator>=(L, R);
7352 // bool operator==(L, R);
7353 // bool operator!=(L, R);
7354 //
7355 // where LR is the result of the usual arithmetic conversions
7356 // between types L and R.
7357 //
7358 // C++ [over.built]p24:
7359 //
7360 // For every pair of promoted arithmetic types L and R, there exist
7361 // candidate operator functions of the form
7362 //
7363 // LR operator?(bool, L, R);
7364 //
7365 // where LR is the result of the usual arithmetic conversions
7366 // between types L and R.
7367 // Our candidates ignore the first parameter.
7368 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007369 if (!HasArithmeticOrEnumeralCandidateType)
7370 return;
7371
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007372 for (unsigned Left = FirstPromotedArithmeticType;
7373 Left < LastPromotedArithmeticType; ++Left) {
7374 for (unsigned Right = FirstPromotedArithmeticType;
7375 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007376 QualType LandR[2] = { getArithmeticType(Left),
7377 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007378 QualType Result =
7379 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007380 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007381 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007382 }
7383 }
7384
7385 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7386 // conditional operator for vector types.
7387 for (BuiltinCandidateTypeSet::iterator
7388 Vec1 = CandidateTypes[0].vector_begin(),
7389 Vec1End = CandidateTypes[0].vector_end();
7390 Vec1 != Vec1End; ++Vec1) {
7391 for (BuiltinCandidateTypeSet::iterator
7392 Vec2 = CandidateTypes[1].vector_begin(),
7393 Vec2End = CandidateTypes[1].vector_end();
7394 Vec2 != Vec2End; ++Vec2) {
7395 QualType LandR[2] = { *Vec1, *Vec2 };
7396 QualType Result = S.Context.BoolTy;
7397 if (!isComparison) {
7398 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7399 Result = *Vec1;
7400 else
7401 Result = *Vec2;
7402 }
7403
Richard Smithe54c3072013-05-05 15:51:06 +00007404 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007405 }
7406 }
7407 }
7408
7409 // C++ [over.built]p17:
7410 //
7411 // For every pair of promoted integral types L and R, there
7412 // exist candidate operator functions of the form
7413 //
7414 // LR operator%(L, R);
7415 // LR operator&(L, R);
7416 // LR operator^(L, R);
7417 // LR operator|(L, R);
7418 // L operator<<(L, R);
7419 // L operator>>(L, R);
7420 //
7421 // where LR is the result of the usual arithmetic conversions
7422 // between types L and R.
7423 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007424 if (!HasArithmeticOrEnumeralCandidateType)
7425 return;
7426
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007427 for (unsigned Left = FirstPromotedIntegralType;
7428 Left < LastPromotedIntegralType; ++Left) {
7429 for (unsigned Right = FirstPromotedIntegralType;
7430 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007431 QualType LandR[2] = { getArithmeticType(Left),
7432 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007433 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7434 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007435 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007436 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007437 }
7438 }
7439 }
7440
7441 // C++ [over.built]p20:
7442 //
7443 // For every pair (T, VQ), where T is an enumeration or
7444 // pointer to member type and VQ is either volatile or
7445 // empty, there exist candidate operator functions of the form
7446 //
7447 // VQ T& operator=(VQ T&, T);
7448 void addAssignmentMemberPointerOrEnumeralOverloads() {
7449 /// Set of (canonical) types that we've already handled.
7450 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7451
7452 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7453 for (BuiltinCandidateTypeSet::iterator
7454 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7455 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7456 Enum != EnumEnd; ++Enum) {
7457 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7458 continue;
7459
Richard Smithe54c3072013-05-05 15:51:06 +00007460 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007461 }
7462
7463 for (BuiltinCandidateTypeSet::iterator
7464 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7465 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7466 MemPtr != MemPtrEnd; ++MemPtr) {
7467 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7468 continue;
7469
Richard Smithe54c3072013-05-05 15:51:06 +00007470 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007471 }
7472 }
7473 }
7474
7475 // C++ [over.built]p19:
7476 //
7477 // For every pair (T, VQ), where T is any type and VQ is either
7478 // volatile or empty, there exist candidate operator functions
7479 // of the form
7480 //
7481 // T*VQ& operator=(T*VQ&, T*);
7482 //
7483 // C++ [over.built]p21:
7484 //
7485 // For every pair (T, VQ), where T is a cv-qualified or
7486 // cv-unqualified object type and VQ is either volatile or
7487 // empty, there exist candidate operator functions of the form
7488 //
7489 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7490 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7491 void addAssignmentPointerOverloads(bool isEqualOp) {
7492 /// Set of (canonical) types that we've already handled.
7493 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7494
7495 for (BuiltinCandidateTypeSet::iterator
7496 Ptr = CandidateTypes[0].pointer_begin(),
7497 PtrEnd = CandidateTypes[0].pointer_end();
7498 Ptr != PtrEnd; ++Ptr) {
7499 // If this is operator=, keep track of the builtin candidates we added.
7500 if (isEqualOp)
7501 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007502 else if (!(*Ptr)->getPointeeType()->isObjectType())
7503 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007504
7505 // non-volatile version
7506 QualType ParamTypes[2] = {
7507 S.Context.getLValueReferenceType(*Ptr),
7508 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7509 };
Richard Smithe54c3072013-05-05 15:51:06 +00007510 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007511 /*IsAssigmentOperator=*/ isEqualOp);
7512
Douglas Gregor5bee2582012-06-04 00:15:09 +00007513 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7514 VisibleTypeConversionsQuals.hasVolatile();
7515 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007516 // volatile version
7517 ParamTypes[0] =
7518 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007519 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007520 /*IsAssigmentOperator=*/isEqualOp);
7521 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007522
7523 if (!(*Ptr).isRestrictQualified() &&
7524 VisibleTypeConversionsQuals.hasRestrict()) {
7525 // restrict version
7526 ParamTypes[0]
7527 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007528 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007529 /*IsAssigmentOperator=*/isEqualOp);
7530
7531 if (NeedVolatile) {
7532 // volatile restrict version
7533 ParamTypes[0]
7534 = S.Context.getLValueReferenceType(
7535 S.Context.getCVRQualifiedType(*Ptr,
7536 (Qualifiers::Volatile |
7537 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007538 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007539 /*IsAssigmentOperator=*/isEqualOp);
7540 }
7541 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007542 }
7543
7544 if (isEqualOp) {
7545 for (BuiltinCandidateTypeSet::iterator
7546 Ptr = CandidateTypes[1].pointer_begin(),
7547 PtrEnd = CandidateTypes[1].pointer_end();
7548 Ptr != PtrEnd; ++Ptr) {
7549 // Make sure we don't add the same candidate twice.
7550 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7551 continue;
7552
Chandler Carruth8e543b32010-12-12 08:17:55 +00007553 QualType ParamTypes[2] = {
7554 S.Context.getLValueReferenceType(*Ptr),
7555 *Ptr,
7556 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007557
7558 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007559 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007560 /*IsAssigmentOperator=*/true);
7561
Douglas Gregor5bee2582012-06-04 00:15:09 +00007562 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7563 VisibleTypeConversionsQuals.hasVolatile();
7564 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007565 // volatile version
7566 ParamTypes[0] =
7567 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007568 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7569 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007570 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007571
7572 if (!(*Ptr).isRestrictQualified() &&
7573 VisibleTypeConversionsQuals.hasRestrict()) {
7574 // restrict version
7575 ParamTypes[0]
7576 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007577 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7578 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007579
7580 if (NeedVolatile) {
7581 // volatile restrict version
7582 ParamTypes[0]
7583 = S.Context.getLValueReferenceType(
7584 S.Context.getCVRQualifiedType(*Ptr,
7585 (Qualifiers::Volatile |
7586 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007587 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7588 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007589 }
7590 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007591 }
7592 }
7593 }
7594
7595 // C++ [over.built]p18:
7596 //
7597 // For every triple (L, VQ, R), where L is an arithmetic type,
7598 // VQ is either volatile or empty, and R is a promoted
7599 // arithmetic type, there exist candidate operator functions of
7600 // the form
7601 //
7602 // VQ L& operator=(VQ L&, R);
7603 // VQ L& operator*=(VQ L&, R);
7604 // VQ L& operator/=(VQ L&, R);
7605 // VQ L& operator+=(VQ L&, R);
7606 // VQ L& operator-=(VQ L&, R);
7607 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007608 if (!HasArithmeticOrEnumeralCandidateType)
7609 return;
7610
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007611 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7612 for (unsigned Right = FirstPromotedArithmeticType;
7613 Right < LastPromotedArithmeticType; ++Right) {
7614 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007615 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007616
7617 // Add this built-in operator as a candidate (VQ is empty).
7618 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007619 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007620 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007621 /*IsAssigmentOperator=*/isEqualOp);
7622
7623 // Add this built-in operator as a candidate (VQ is 'volatile').
7624 if (VisibleTypeConversionsQuals.hasVolatile()) {
7625 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007626 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007627 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007628 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007629 /*IsAssigmentOperator=*/isEqualOp);
7630 }
7631 }
7632 }
7633
7634 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7635 for (BuiltinCandidateTypeSet::iterator
7636 Vec1 = CandidateTypes[0].vector_begin(),
7637 Vec1End = CandidateTypes[0].vector_end();
7638 Vec1 != Vec1End; ++Vec1) {
7639 for (BuiltinCandidateTypeSet::iterator
7640 Vec2 = CandidateTypes[1].vector_begin(),
7641 Vec2End = CandidateTypes[1].vector_end();
7642 Vec2 != Vec2End; ++Vec2) {
7643 QualType ParamTypes[2];
7644 ParamTypes[1] = *Vec2;
7645 // Add this built-in operator as a candidate (VQ is empty).
7646 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007647 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007648 /*IsAssigmentOperator=*/isEqualOp);
7649
7650 // Add this built-in operator as a candidate (VQ is 'volatile').
7651 if (VisibleTypeConversionsQuals.hasVolatile()) {
7652 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7653 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007654 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007655 /*IsAssigmentOperator=*/isEqualOp);
7656 }
7657 }
7658 }
7659 }
7660
7661 // C++ [over.built]p22:
7662 //
7663 // For every triple (L, VQ, R), where L is an integral type, VQ
7664 // is either volatile or empty, and R is a promoted integral
7665 // type, there exist candidate operator functions of the form
7666 //
7667 // VQ L& operator%=(VQ L&, R);
7668 // VQ L& operator<<=(VQ L&, R);
7669 // VQ L& operator>>=(VQ L&, R);
7670 // VQ L& operator&=(VQ L&, R);
7671 // VQ L& operator^=(VQ L&, R);
7672 // VQ L& operator|=(VQ L&, R);
7673 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007674 if (!HasArithmeticOrEnumeralCandidateType)
7675 return;
7676
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007677 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7678 for (unsigned Right = FirstPromotedIntegralType;
7679 Right < LastPromotedIntegralType; ++Right) {
7680 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007681 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007682
7683 // Add this built-in operator as a candidate (VQ is empty).
7684 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007685 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007686 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007687 if (VisibleTypeConversionsQuals.hasVolatile()) {
7688 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007689 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007690 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7691 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007692 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007693 }
7694 }
7695 }
7696 }
7697
7698 // C++ [over.operator]p23:
7699 //
7700 // There also exist candidate operator functions of the form
7701 //
7702 // bool operator!(bool);
7703 // bool operator&&(bool, bool);
7704 // bool operator||(bool, bool);
7705 void addExclaimOverload() {
7706 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007707 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007708 /*IsAssignmentOperator=*/false,
7709 /*NumContextualBoolArguments=*/1);
7710 }
7711 void addAmpAmpOrPipePipeOverload() {
7712 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007713 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007714 /*IsAssignmentOperator=*/false,
7715 /*NumContextualBoolArguments=*/2);
7716 }
7717
7718 // C++ [over.built]p13:
7719 //
7720 // For every cv-qualified or cv-unqualified object type T there
7721 // exist candidate operator functions of the form
7722 //
7723 // T* operator+(T*, ptrdiff_t); [ABOVE]
7724 // T& operator[](T*, ptrdiff_t);
7725 // T* operator-(T*, ptrdiff_t); [ABOVE]
7726 // T* operator+(ptrdiff_t, T*); [ABOVE]
7727 // T& operator[](ptrdiff_t, T*);
7728 void addSubscriptOverloads() {
7729 for (BuiltinCandidateTypeSet::iterator
7730 Ptr = CandidateTypes[0].pointer_begin(),
7731 PtrEnd = CandidateTypes[0].pointer_end();
7732 Ptr != PtrEnd; ++Ptr) {
7733 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7734 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007735 if (!PointeeType->isObjectType())
7736 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007737
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007738 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7739
7740 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00007741 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007742 }
7743
7744 for (BuiltinCandidateTypeSet::iterator
7745 Ptr = CandidateTypes[1].pointer_begin(),
7746 PtrEnd = CandidateTypes[1].pointer_end();
7747 Ptr != PtrEnd; ++Ptr) {
7748 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7749 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007750 if (!PointeeType->isObjectType())
7751 continue;
7752
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007753 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7754
7755 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00007756 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007757 }
7758 }
7759
7760 // C++ [over.built]p11:
7761 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7762 // C1 is the same type as C2 or is a derived class of C2, T is an object
7763 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7764 // there exist candidate operator functions of the form
7765 //
7766 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7767 //
7768 // where CV12 is the union of CV1 and CV2.
7769 void addArrowStarOverloads() {
7770 for (BuiltinCandidateTypeSet::iterator
7771 Ptr = CandidateTypes[0].pointer_begin(),
7772 PtrEnd = CandidateTypes[0].pointer_end();
7773 Ptr != PtrEnd; ++Ptr) {
7774 QualType C1Ty = (*Ptr);
7775 QualType C1;
7776 QualifierCollector Q1;
7777 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7778 if (!isa<RecordType>(C1))
7779 continue;
7780 // heuristic to reduce number of builtin candidates in the set.
7781 // Add volatile/restrict version only if there are conversions to a
7782 // volatile/restrict type.
7783 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7784 continue;
7785 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7786 continue;
7787 for (BuiltinCandidateTypeSet::iterator
7788 MemPtr = CandidateTypes[1].member_pointer_begin(),
7789 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7790 MemPtr != MemPtrEnd; ++MemPtr) {
7791 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7792 QualType C2 = QualType(mptr->getClass(), 0);
7793 C2 = C2.getUnqualifiedType();
7794 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7795 break;
7796 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7797 // build CV12 T&
7798 QualType T = mptr->getPointeeType();
7799 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7800 T.isVolatileQualified())
7801 continue;
7802 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7803 T.isRestrictQualified())
7804 continue;
7805 T = Q1.apply(S.Context, T);
7806 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00007807 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007808 }
7809 }
7810 }
7811
7812 // Note that we don't consider the first argument, since it has been
7813 // contextually converted to bool long ago. The candidates below are
7814 // therefore added as binary.
7815 //
7816 // C++ [over.built]p25:
7817 // For every type T, where T is a pointer, pointer-to-member, or scoped
7818 // enumeration type, there exist candidate operator functions of the form
7819 //
7820 // T operator?(bool, T, T);
7821 //
7822 void addConditionalOperatorOverloads() {
7823 /// Set of (canonical) types that we've already handled.
7824 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7825
7826 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7827 for (BuiltinCandidateTypeSet::iterator
7828 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7829 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7830 Ptr != PtrEnd; ++Ptr) {
7831 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7832 continue;
7833
7834 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007835 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007836 }
7837
7838 for (BuiltinCandidateTypeSet::iterator
7839 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7840 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7841 MemPtr != MemPtrEnd; ++MemPtr) {
7842 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7843 continue;
7844
7845 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007846 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007847 }
7848
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007849 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007850 for (BuiltinCandidateTypeSet::iterator
7851 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7852 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7853 Enum != EnumEnd; ++Enum) {
7854 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7855 continue;
7856
7857 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7858 continue;
7859
7860 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007861 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007862 }
7863 }
7864 }
7865 }
7866};
7867
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007868} // end anonymous namespace
7869
7870/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7871/// operator overloads to the candidate set (C++ [over.built]), based
7872/// on the operator @p Op and the arguments given. For example, if the
7873/// operator is a binary '+', this routine might add "int
7874/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00007875void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7876 SourceLocation OpLoc,
7877 ArrayRef<Expr *> Args,
7878 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007879 // Find all of the types that the arguments can convert to, but only
7880 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007881 // that make use of these types. Also record whether we encounter non-record
7882 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007883 Qualifiers VisibleTypeConversionsQuals;
7884 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00007885 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007886 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007887
7888 bool HasNonRecordCandidateType = false;
7889 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007890 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00007891 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007892 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7893 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7894 OpLoc,
7895 true,
7896 (Op == OO_Exclaim ||
7897 Op == OO_AmpAmp ||
7898 Op == OO_PipePipe),
7899 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007900 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7901 CandidateTypes[ArgIdx].hasNonRecordTypes();
7902 HasArithmeticOrEnumeralCandidateType =
7903 HasArithmeticOrEnumeralCandidateType ||
7904 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007905 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007906
Chandler Carruth00a38332010-12-13 01:44:01 +00007907 // Exit early when no non-record types have been added to the candidate set
7908 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007909 //
7910 // We can't exit early for !, ||, or &&, since there we have always have
7911 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00007912 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007913 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007914 return;
7915
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007916 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00007917 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007918 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007919 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007920 CandidateTypes, CandidateSet);
7921
7922 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007923 switch (Op) {
7924 case OO_None:
7925 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007926 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007927
Chandler Carruth5184de02010-12-12 08:51:33 +00007928 case OO_New:
7929 case OO_Delete:
7930 case OO_Array_New:
7931 case OO_Array_Delete:
7932 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007933 llvm_unreachable(
7934 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007935
7936 case OO_Comma:
7937 case OO_Arrow:
7938 // C++ [over.match.oper]p3:
7939 // -- For the operator ',', the unary operator '&', or the
7940 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007941 break;
7942
7943 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007944 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007945 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007946 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007947
7948 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007949 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007950 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007951 } else {
7952 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7953 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7954 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007955 break;
7956
Chandler Carruth5184de02010-12-12 08:51:33 +00007957 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007958 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007959 OpBuilder.addUnaryStarPointerOverloads();
7960 else
7961 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7962 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007963
Chandler Carruth5184de02010-12-12 08:51:33 +00007964 case OO_Slash:
7965 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007966 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007967
7968 case OO_PlusPlus:
7969 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007970 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7971 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007972 break;
7973
Douglas Gregor84605ae2009-08-24 13:43:27 +00007974 case OO_EqualEqual:
7975 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007976 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007977 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007978
Douglas Gregora11693b2008-11-12 17:17:38 +00007979 case OO_Less:
7980 case OO_Greater:
7981 case OO_LessEqual:
7982 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007983 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007984 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7985 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007986
Douglas Gregora11693b2008-11-12 17:17:38 +00007987 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007988 case OO_Caret:
7989 case OO_Pipe:
7990 case OO_LessLess:
7991 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007992 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007993 break;
7994
Chandler Carruth5184de02010-12-12 08:51:33 +00007995 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007996 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007997 // C++ [over.match.oper]p3:
7998 // -- For the operator ',', the unary operator '&', or the
7999 // operator '->', the built-in candidates set is empty.
8000 break;
8001
8002 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8003 break;
8004
8005 case OO_Tilde:
8006 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8007 break;
8008
Douglas Gregora11693b2008-11-12 17:17:38 +00008009 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008010 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008011 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008012
8013 case OO_PlusEqual:
8014 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008015 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008016 // Fall through.
8017
8018 case OO_StarEqual:
8019 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008020 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008021 break;
8022
8023 case OO_PercentEqual:
8024 case OO_LessLessEqual:
8025 case OO_GreaterGreaterEqual:
8026 case OO_AmpEqual:
8027 case OO_CaretEqual:
8028 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008029 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008030 break;
8031
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008032 case OO_Exclaim:
8033 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008034 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008035
Douglas Gregora11693b2008-11-12 17:17:38 +00008036 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008037 case OO_PipePipe:
8038 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008039 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008040
8041 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008042 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008043 break;
8044
8045 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008046 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008047 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008048
8049 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008050 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008051 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8052 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008053 }
8054}
8055
Douglas Gregore254f902009-02-04 00:32:51 +00008056/// \brief Add function candidates found via argument-dependent lookup
8057/// to the set of overloading candidates.
8058///
8059/// This routine performs argument-dependent name lookup based on the
8060/// given function name (which may also be an operator name) and adds
8061/// all of the overload candidates found by ADL to the overload
8062/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008063void
Douglas Gregore254f902009-02-04 00:32:51 +00008064Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00008065 bool Operator, SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008066 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008067 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008068 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008069 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008070 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008071
John McCall91f61fc2010-01-26 06:04:06 +00008072 // FIXME: This approach for uniquing ADL results (and removing
8073 // redundant candidates from the set) relies on pointer-equality,
8074 // which means we need to key off the canonical decl. However,
8075 // always going back to the canonical decl might not get us the
8076 // right set of default arguments. What default arguments are
8077 // we supposed to consider on ADL candidates, anyway?
8078
Douglas Gregorcabea402009-09-22 15:41:20 +00008079 // FIXME: Pass in the explicit template arguments?
Richard Smithb6626742012-10-18 17:56:02 +00008080 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008081
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008082 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008083 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8084 CandEnd = CandidateSet.end();
8085 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008086 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008087 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008088 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008089 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008090 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008091
8092 // For each of the ADL candidates we found, add it to the overload
8093 // set.
John McCall8fe68082010-01-26 07:16:45 +00008094 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008095 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008096 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008097 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008098 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008099
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008100 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8101 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008102 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008103 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008104 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008105 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00008106 }
Douglas Gregore254f902009-02-04 00:32:51 +00008107}
8108
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008109/// isBetterOverloadCandidate - Determines whether the first overload
8110/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00008111bool
John McCall5c32be02010-08-24 20:38:10 +00008112isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008113 const OverloadCandidate &Cand1,
8114 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008115 SourceLocation Loc,
8116 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008117 // Define viable functions to be better candidates than non-viable
8118 // functions.
8119 if (!Cand2.Viable)
8120 return Cand1.Viable;
8121 else if (!Cand1.Viable)
8122 return false;
8123
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008124 // C++ [over.match.best]p1:
8125 //
8126 // -- if F is a static member function, ICS1(F) is defined such
8127 // that ICS1(F) is neither better nor worse than ICS1(G) for
8128 // any function G, and, symmetrically, ICS1(G) is neither
8129 // better nor worse than ICS1(F).
8130 unsigned StartArg = 0;
8131 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8132 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008133
Douglas Gregord3cb3562009-07-07 23:38:56 +00008134 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008135 // A viable function F1 is defined to be a better function than another
8136 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008137 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008138 unsigned NumArgs = Cand1.NumConversions;
8139 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008140 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008141 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008142 switch (CompareImplicitConversionSequences(S,
8143 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008144 Cand2.Conversions[ArgIdx])) {
8145 case ImplicitConversionSequence::Better:
8146 // Cand1 has a better conversion sequence.
8147 HasBetterConversion = true;
8148 break;
8149
8150 case ImplicitConversionSequence::Worse:
8151 // Cand1 can't be better than Cand2.
8152 return false;
8153
8154 case ImplicitConversionSequence::Indistinguishable:
8155 // Do nothing.
8156 break;
8157 }
8158 }
8159
Mike Stump11289f42009-09-09 15:08:12 +00008160 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008161 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008162 if (HasBetterConversion)
8163 return true;
8164
Mike Stump11289f42009-09-09 15:08:12 +00008165 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00008166 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00008167 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00008168 Cand2.Function && Cand2.Function->getPrimaryTemplate())
8169 return true;
Mike Stump11289f42009-09-09 15:08:12 +00008170
8171 // -- F1 and F2 are function template specializations, and the function
8172 // template for F1 is more specialized than the template for F2
8173 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00008174 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00008175 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00008176 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00008177 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00008178 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8179 Cand2.Function->getPrimaryTemplate(),
8180 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008181 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00008182 : TPOC_Call,
Richard Smithe5b52202013-09-11 00:52:39 +00008183 Cand1.ExplicitCallArguments,
8184 Cand2.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00008185 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00008186 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008187
Douglas Gregora1f013e2008-11-07 22:36:19 +00008188 // -- the context is an initialization by user-defined conversion
8189 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8190 // from the return type of F1 to the destination type (i.e.,
8191 // the type of the entity being initialized) is a better
8192 // conversion sequence than the standard conversion sequence
8193 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008194 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008195 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008196 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008197 // First check whether we prefer one of the conversion functions over the
8198 // other. This only distinguishes the results in non-standard, extension
8199 // cases such as the conversion from a lambda closure type to a function
8200 // pointer or block.
8201 ImplicitConversionSequence::CompareKind FuncResult
8202 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8203 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
8204 return FuncResult;
8205
John McCall5c32be02010-08-24 20:38:10 +00008206 switch (CompareStandardConversionSequences(S,
8207 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00008208 Cand2.FinalConversion)) {
8209 case ImplicitConversionSequence::Better:
8210 // Cand1 has a better conversion sequence.
8211 return true;
8212
8213 case ImplicitConversionSequence::Worse:
8214 // Cand1 can't be better than Cand2.
8215 return false;
8216
8217 case ImplicitConversionSequence::Indistinguishable:
8218 // Do nothing
8219 break;
8220 }
8221 }
8222
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008223 // Check for enable_if value-based overload resolution.
8224 if (Cand1.Function && Cand2.Function &&
8225 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8226 Cand2.Function->hasAttr<EnableIfAttr>())) {
8227 // FIXME: The next several lines are just
8228 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8229 // instead of reverse order which is how they're stored in the AST.
8230 AttrVec Cand1Attrs;
8231 AttrVec::iterator Cand1E = Cand1Attrs.end();
8232 if (Cand1.Function->hasAttrs()) {
8233 Cand1Attrs = Cand1.Function->getAttrs();
8234 Cand1E = std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8235 IsNotEnableIfAttr);
8236 std::reverse(Cand1Attrs.begin(), Cand1E);
8237 }
8238
8239 AttrVec Cand2Attrs;
8240 AttrVec::iterator Cand2E = Cand2Attrs.end();
8241 if (Cand2.Function->hasAttrs()) {
8242 Cand2Attrs = Cand2.Function->getAttrs();
8243 Cand2E = std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8244 IsNotEnableIfAttr);
8245 std::reverse(Cand2Attrs.begin(), Cand2E);
8246 }
8247 for (AttrVec::iterator
8248 Cand1I = Cand1Attrs.begin(), Cand2I = Cand2Attrs.begin();
8249 Cand1I != Cand1E || Cand2I != Cand2E; ++Cand1I, ++Cand2I) {
8250 if (Cand1I == Cand1E)
8251 return false;
8252 if (Cand2I == Cand2E)
8253 return true;
8254 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8255 cast<EnableIfAttr>(*Cand1I)->getCond()->Profile(Cand1ID,
8256 S.getASTContext(), true);
8257 cast<EnableIfAttr>(*Cand2I)->getCond()->Profile(Cand2ID,
8258 S.getASTContext(), true);
8259 if (!(Cand1ID == Cand2ID))
8260 return false;
8261 }
8262 }
8263
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008264 return false;
8265}
8266
Mike Stump11289f42009-09-09 15:08:12 +00008267/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008268/// within an overload candidate set.
8269///
James Dennettffad8b72012-06-22 08:10:18 +00008270/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008271/// which overload resolution occurs.
8272///
James Dennettffad8b72012-06-22 08:10:18 +00008273/// \param Best If overload resolution was successful or found a deleted
8274/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008275///
8276/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008277OverloadingResult
8278OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008279 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008280 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008281 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008282 Best = end();
8283 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8284 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008285 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008286 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008287 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008288 }
8289
8290 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008291 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008292 return OR_No_Viable_Function;
8293
8294 // Make sure that this function is better than every other viable
8295 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008296 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008297 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008298 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008299 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008300 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00008301 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008302 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008303 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008304 }
Mike Stump11289f42009-09-09 15:08:12 +00008305
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008306 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008307 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008308 (Best->Function->isDeleted() ||
8309 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008310 return OR_Deleted;
8311
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008312 return OR_Success;
8313}
8314
John McCall53262c92010-01-12 02:15:36 +00008315namespace {
8316
8317enum OverloadCandidateKind {
8318 oc_function,
8319 oc_method,
8320 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008321 oc_function_template,
8322 oc_method_template,
8323 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008324 oc_implicit_default_constructor,
8325 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008326 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008327 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008328 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008329 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008330};
8331
John McCalle1ac8d12010-01-13 00:25:19 +00008332OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8333 FunctionDecl *Fn,
8334 std::string &Description) {
8335 bool isTemplate = false;
8336
8337 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8338 isTemplate = true;
8339 Description = S.getTemplateArgumentBindingsText(
8340 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8341 }
John McCallfd0b2f82010-01-06 09:43:14 +00008342
8343 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008344 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008345 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008346
Sebastian Redl08905022011-02-05 19:23:19 +00008347 if (Ctor->getInheritedConstructor())
8348 return oc_implicit_inherited_constructor;
8349
Alexis Hunt119c10e2011-05-25 23:16:36 +00008350 if (Ctor->isDefaultConstructor())
8351 return oc_implicit_default_constructor;
8352
8353 if (Ctor->isMoveConstructor())
8354 return oc_implicit_move_constructor;
8355
8356 assert(Ctor->isCopyConstructor() &&
8357 "unexpected sort of implicit constructor");
8358 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008359 }
8360
8361 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8362 // This actually gets spelled 'candidate function' for now, but
8363 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008364 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008365 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008366
Alexis Hunt119c10e2011-05-25 23:16:36 +00008367 if (Meth->isMoveAssignmentOperator())
8368 return oc_implicit_move_assignment;
8369
Douglas Gregor12695102012-02-10 08:36:38 +00008370 if (Meth->isCopyAssignmentOperator())
8371 return oc_implicit_copy_assignment;
8372
8373 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8374 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008375 }
8376
John McCalle1ac8d12010-01-13 00:25:19 +00008377 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008378}
8379
Larisse Voufo98b20f12013-07-19 23:00:19 +00008380void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008381 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8382 if (!Ctor) return;
8383
8384 Ctor = Ctor->getInheritedConstructor();
8385 if (!Ctor) return;
8386
8387 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8388}
8389
John McCall53262c92010-01-12 02:15:36 +00008390} // end anonymous namespace
8391
8392// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00008393void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00008394 std::string FnDesc;
8395 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008396 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8397 << (unsigned) K << FnDesc;
8398 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8399 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008400 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008401}
8402
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008403// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008404// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00008405void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008406 assert(OverloadedExpr->getType() == Context.OverloadTy);
8407
8408 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8409 OverloadExpr *OvlExpr = Ovl.Expression;
8410
8411 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8412 IEnd = OvlExpr->decls_end();
8413 I != IEnd; ++I) {
8414 if (FunctionTemplateDecl *FunTmpl =
8415 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008416 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008417 } else if (FunctionDecl *Fun
8418 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008419 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008420 }
8421 }
8422}
8423
John McCall0d1da222010-01-12 00:44:57 +00008424/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8425/// "lead" diagnostic; it will be given two arguments, the source and
8426/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008427void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8428 Sema &S,
8429 SourceLocation CaretLoc,
8430 const PartialDiagnostic &PDiag) const {
8431 S.Diag(CaretLoc, PDiag)
8432 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008433 // FIXME: The note limiting machinery is borrowed from
8434 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8435 // refactoring here.
8436 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8437 unsigned CandsShown = 0;
8438 AmbiguousConversionSequence::const_iterator I, E;
8439 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8440 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8441 break;
8442 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008443 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008444 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008445 if (I != E)
8446 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008447}
8448
John McCall0d1da222010-01-12 00:44:57 +00008449namespace {
8450
John McCall6a61b522010-01-13 09:16:55 +00008451void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8452 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8453 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008454 assert(Cand->Function && "for now, candidate must be a function");
8455 FunctionDecl *Fn = Cand->Function;
8456
8457 // There's a conversion slot for the object argument if this is a
8458 // non-constructor method. Note that 'I' corresponds the
8459 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008460 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008461 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008462 if (I == 0)
8463 isObjectArgument = true;
8464 else
8465 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008466 }
8467
John McCalle1ac8d12010-01-13 00:25:19 +00008468 std::string FnDesc;
8469 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8470
John McCall6a61b522010-01-13 09:16:55 +00008471 Expr *FromExpr = Conv.Bad.FromExpr;
8472 QualType FromTy = Conv.Bad.getFromType();
8473 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008474
John McCallfb7ad0f2010-02-02 02:42:52 +00008475 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008476 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008477 Expr *E = FromExpr->IgnoreParens();
8478 if (isa<UnaryOperator>(E))
8479 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008480 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008481
8482 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8483 << (unsigned) FnKind << FnDesc
8484 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8485 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008486 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008487 return;
8488 }
8489
John McCall6d174642010-01-23 08:10:49 +00008490 // Do some hand-waving analysis to see if the non-viability is due
8491 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008492 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8493 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8494 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8495 CToTy = RT->getPointeeType();
8496 else {
8497 // TODO: detect and diagnose the full richness of const mismatches.
8498 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8499 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8500 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8501 }
8502
8503 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8504 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008505 Qualifiers FromQs = CFromTy.getQualifiers();
8506 Qualifiers ToQs = CToTy.getQualifiers();
8507
8508 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8509 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8510 << (unsigned) FnKind << FnDesc
8511 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8512 << FromTy
8513 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8514 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008515 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008516 return;
8517 }
8518
John McCall31168b02011-06-15 23:02:42 +00008519 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008520 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008521 << (unsigned) FnKind << FnDesc
8522 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8523 << FromTy
8524 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8525 << (unsigned) isObjectArgument << I+1;
8526 MaybeEmitInheritedConstructorNote(S, Fn);
8527 return;
8528 }
8529
Douglas Gregoraec25842011-04-26 23:16:46 +00008530 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8531 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8532 << (unsigned) FnKind << FnDesc
8533 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8534 << FromTy
8535 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8536 << (unsigned) isObjectArgument << I+1;
8537 MaybeEmitInheritedConstructorNote(S, Fn);
8538 return;
8539 }
8540
John McCall47000992010-01-14 03:28:57 +00008541 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8542 assert(CVR && "unexpected qualifiers mismatch");
8543
8544 if (isObjectArgument) {
8545 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8546 << (unsigned) FnKind << FnDesc
8547 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8548 << FromTy << (CVR - 1);
8549 } else {
8550 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8551 << (unsigned) FnKind << FnDesc
8552 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8553 << FromTy << (CVR - 1) << I+1;
8554 }
Sebastian Redl08905022011-02-05 19:23:19 +00008555 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008556 return;
8557 }
8558
Sebastian Redla72462c2011-09-24 17:48:32 +00008559 // Special diagnostic for failure to convert an initializer list, since
8560 // telling the user that it has type void is not useful.
8561 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8562 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8563 << (unsigned) FnKind << FnDesc
8564 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8565 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8566 MaybeEmitInheritedConstructorNote(S, Fn);
8567 return;
8568 }
8569
John McCall6d174642010-01-23 08:10:49 +00008570 // Diagnose references or pointers to incomplete types differently,
8571 // since it's far from impossible that the incompleteness triggered
8572 // the failure.
8573 QualType TempFromTy = FromTy.getNonReferenceType();
8574 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8575 TempFromTy = PTy->getPointeeType();
8576 if (TempFromTy->isIncompleteType()) {
8577 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8578 << (unsigned) FnKind << FnDesc
8579 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8580 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008581 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008582 return;
8583 }
8584
Douglas Gregor56f2e342010-06-30 23:01:39 +00008585 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008586 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008587 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8588 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8589 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8590 FromPtrTy->getPointeeType()) &&
8591 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8592 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008593 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008594 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008595 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008596 }
8597 } else if (const ObjCObjectPointerType *FromPtrTy
8598 = FromTy->getAs<ObjCObjectPointerType>()) {
8599 if (const ObjCObjectPointerType *ToPtrTy
8600 = ToTy->getAs<ObjCObjectPointerType>())
8601 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8602 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8603 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8604 FromPtrTy->getPointeeType()) &&
8605 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008606 BaseToDerivedConversion = 2;
8607 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008608 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8609 !FromTy->isIncompleteType() &&
8610 !ToRefTy->getPointeeType()->isIncompleteType() &&
8611 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8612 BaseToDerivedConversion = 3;
8613 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8614 ToTy.getNonReferenceType().getCanonicalType() ==
8615 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008616 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8617 << (unsigned) FnKind << FnDesc
8618 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8619 << (unsigned) isObjectArgument << I + 1;
8620 MaybeEmitInheritedConstructorNote(S, Fn);
8621 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008622 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008623 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008624
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008625 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008626 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008627 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008628 << (unsigned) FnKind << FnDesc
8629 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008630 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008631 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008632 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008633 return;
8634 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008635
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008636 if (isa<ObjCObjectPointerType>(CFromTy) &&
8637 isa<PointerType>(CToTy)) {
8638 Qualifiers FromQs = CFromTy.getQualifiers();
8639 Qualifiers ToQs = CToTy.getQualifiers();
8640 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8641 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8642 << (unsigned) FnKind << FnDesc
8643 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8644 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8645 MaybeEmitInheritedConstructorNote(S, Fn);
8646 return;
8647 }
8648 }
8649
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008650 // Emit the generic diagnostic and, optionally, add the hints to it.
8651 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8652 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008653 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008654 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8655 << (unsigned) (Cand->Fix.Kind);
8656
8657 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008658 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8659 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008660 FDiag << *HI;
8661 S.Diag(Fn->getLocation(), FDiag);
8662
Sebastian Redl08905022011-02-05 19:23:19 +00008663 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008664}
8665
Larisse Voufo98b20f12013-07-19 23:00:19 +00008666/// Additional arity mismatch diagnosis specific to a function overload
8667/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8668/// over a candidate in any candidate set.
8669bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8670 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00008671 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00008672 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008673
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008674 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00008675 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008676 // right number of arguments, because only overloaded operators have
8677 // the weird behavior of overloading member and non-member functions.
8678 // Just don't report anything.
8679 if (Fn->isInvalidDecl() &&
8680 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008681 return true;
8682
8683 if (NumArgs < MinParams) {
8684 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8685 (Cand->FailureKind == ovl_fail_bad_deduction &&
8686 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8687 } else {
8688 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8689 (Cand->FailureKind == ovl_fail_bad_deduction &&
8690 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8691 }
8692
8693 return false;
8694}
8695
8696/// General arity mismatch diagnosis over a candidate in a candidate set.
8697void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8698 assert(isa<FunctionDecl>(D) &&
8699 "The templated declaration should at least be a function"
8700 " when diagnosing bad template argument deduction due to too many"
8701 " or too few arguments");
8702
8703 FunctionDecl *Fn = cast<FunctionDecl>(D);
8704
8705 // TODO: treat calls to a missing default constructor as a special case
8706 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8707 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008708
John McCall6a61b522010-01-13 09:16:55 +00008709 // at least / at most / exactly
8710 unsigned mode, modeCount;
8711 if (NumFormalArgs < MinParams) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008712 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00008713 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008714 mode = 0; // "at least"
8715 else
8716 mode = 2; // "exactly"
8717 modeCount = MinParams;
8718 } else {
John McCall6a61b522010-01-13 09:16:55 +00008719 if (MinParams != FnTy->getNumArgs())
8720 mode = 1; // "at most"
8721 else
8722 mode = 2; // "exactly"
8723 modeCount = FnTy->getNumArgs();
8724 }
8725
8726 std::string Description;
8727 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8728
Richard Smith10ff50d2012-05-11 05:16:41 +00008729 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8730 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8731 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8732 << Fn->getParamDecl(0) << NumFormalArgs;
8733 else
8734 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8735 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8736 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008737 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008738}
8739
Larisse Voufo98b20f12013-07-19 23:00:19 +00008740/// Arity mismatch diagnosis specific to a function overload candidate.
8741void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8742 unsigned NumFormalArgs) {
8743 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8744 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8745}
Larisse Voufo47c08452013-07-19 22:53:23 +00008746
Larisse Voufo98b20f12013-07-19 23:00:19 +00008747TemplateDecl *getDescribedTemplate(Decl *Templated) {
8748 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8749 return FD->getDescribedFunctionTemplate();
8750 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8751 return RD->getDescribedClassTemplate();
8752
8753 llvm_unreachable("Unsupported: Getting the described template declaration"
8754 " for bad deduction diagnosis");
8755}
8756
8757/// Diagnose a failed template-argument deduction.
8758void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8759 DeductionFailureInfo &DeductionFailure,
8760 unsigned NumArgs) {
8761 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008762 NamedDecl *ParamD;
8763 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8764 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8765 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00008766 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00008767 case Sema::TDK_Success:
8768 llvm_unreachable("TDK_success while diagnosing bad deduction");
8769
8770 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008771 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00008772 S.Diag(Templated->getLocation(),
8773 diag::note_ovl_candidate_incomplete_deduction)
8774 << ParamD->getDeclName();
8775 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008776 return;
8777 }
8778
John McCall42d7d192010-08-05 09:05:08 +00008779 case Sema::TDK_Underqualified: {
8780 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8781 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8782
Larisse Voufo98b20f12013-07-19 23:00:19 +00008783 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008784
8785 // Param will have been canonicalized, but it should just be a
8786 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008787 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008788 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008789 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008790 assert(S.Context.hasSameType(Param, NonCanonParam));
8791
8792 // Arg has also been canonicalized, but there's nothing we can do
8793 // about that. It also doesn't matter as much, because it won't
8794 // have any template parameters in it (because deduction isn't
8795 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00008796 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008797
Larisse Voufo98b20f12013-07-19 23:00:19 +00008798 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8799 << ParamD->getDeclName() << Arg << NonCanonParam;
8800 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00008801 return;
8802 }
8803
8804 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008805 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008806 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008807 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008808 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008809 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008810 which = 1;
8811 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008812 which = 2;
8813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008814
Larisse Voufo98b20f12013-07-19 23:00:19 +00008815 S.Diag(Templated->getLocation(),
8816 diag::note_ovl_candidate_inconsistent_deduction)
8817 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8818 << *DeductionFailure.getSecondArg();
8819 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008820 return;
8821 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008822
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008823 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008824 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008825 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00008826 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008827 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008828 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008829 else {
8830 int index = 0;
8831 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8832 index = TTP->getIndex();
8833 else if (NonTypeTemplateParmDecl *NTTP
8834 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8835 index = NTTP->getIndex();
8836 else
8837 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008838 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008839 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008840 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008841 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00008842 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008843 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008844
Douglas Gregor02eb4832010-05-08 18:13:28 +00008845 case Sema::TDK_TooManyArguments:
8846 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008847 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00008848 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008849
8850 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008851 S.Diag(Templated->getLocation(),
8852 diag::note_ovl_candidate_instantiation_depth);
8853 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00008854 return;
8855
8856 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00008857 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008858 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00008859 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00008860 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00008861 TemplateArgString = " ";
8862 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00008863 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00008864 }
8865
Richard Smith6f8d2c62012-05-09 05:17:00 +00008866 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008867 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008868 if (PDiag && PDiag->second.getDiagID() ==
8869 diag::err_typename_nested_not_found_enable_if) {
8870 // FIXME: Use the source range of the condition, and the fully-qualified
8871 // name of the enable_if template. These are both present in PDiag.
8872 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8873 << "'enable_if'" << TemplateArgString;
8874 return;
8875 }
8876
Richard Smith9ca64612012-05-07 09:03:25 +00008877 // Format the SFINAE diagnostic into the argument string.
8878 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8879 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008880 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00008881 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008882 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00008883 SFINAEArgString = ": ";
8884 R = SourceRange(PDiag->first, PDiag->first);
8885 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8886 }
8887
Larisse Voufo98b20f12013-07-19 23:00:19 +00008888 S.Diag(Templated->getLocation(),
8889 diag::note_ovl_candidate_substitution_failure)
8890 << TemplateArgString << SFINAEArgString << R;
8891 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00008892 return;
8893 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008894
Richard Smith8c6eeb92013-01-31 04:03:12 +00008895 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008896 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8897 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00008898 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008899 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00008900 return;
8901 }
8902
Richard Trieue3732352013-04-08 21:11:40 +00008903 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00008904 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008905 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8906 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00008907 if (FirstTA.getKind() == TemplateArgument::Template &&
8908 SecondTA.getKind() == TemplateArgument::Template) {
8909 TemplateName FirstTN = FirstTA.getAsTemplate();
8910 TemplateName SecondTN = SecondTA.getAsTemplate();
8911 if (FirstTN.getKind() == TemplateName::Template &&
8912 SecondTN.getKind() == TemplateName::Template) {
8913 if (FirstTN.getAsTemplateDecl()->getName() ==
8914 SecondTN.getAsTemplateDecl()->getName()) {
8915 // FIXME: This fixes a bad diagnostic where both templates are named
8916 // the same. This particular case is a bit difficult since:
8917 // 1) It is passed as a string to the diagnostic printer.
8918 // 2) The diagnostic printer only attempts to find a better
8919 // name for types, not decls.
8920 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008921 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00008922 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8923 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8924 return;
8925 }
8926 }
8927 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00008928 // FIXME: For generic lambda parameters, check if the function is a lambda
8929 // call operator, and if so, emit a prettier and more informative
8930 // diagnostic that mentions 'auto' and lambda in addition to
8931 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008932 S.Diag(Templated->getLocation(),
8933 diag::note_ovl_candidate_non_deduced_mismatch)
8934 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00008935 return;
Richard Trieue3732352013-04-08 21:11:40 +00008936 }
John McCall8b9ed552010-02-01 18:53:26 +00008937 // TODO: diagnose these individually, then kill off
8938 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00008939 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008940 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
8941 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008942 return;
8943 }
8944}
8945
Larisse Voufo98b20f12013-07-19 23:00:19 +00008946/// Diagnose a failed template-argument deduction, for function calls.
8947void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
8948 unsigned TDK = Cand->DeductionFailure.Result;
8949 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
8950 if (CheckArityMismatch(S, Cand, NumArgs))
8951 return;
8952 }
8953 DiagnoseBadDeduction(S, Cand->Function, // pattern
8954 Cand->DeductionFailure, NumArgs);
8955}
8956
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008957/// CUDA: diagnose an invalid call across targets.
8958void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8959 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8960 FunctionDecl *Callee = Cand->Function;
8961
8962 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8963 CalleeTarget = S.IdentifyCUDATarget(Callee);
8964
8965 std::string FnDesc;
8966 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8967
8968 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8969 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8970}
8971
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008972void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
8973 FunctionDecl *Callee = Cand->Function;
8974 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
8975
8976 S.Diag(Callee->getLocation(),
8977 diag::note_ovl_candidate_disabled_by_enable_if_attr)
8978 << Attr->getCond()->getSourceRange() << Attr->getMessage();
8979}
8980
John McCall8b9ed552010-02-01 18:53:26 +00008981/// Generates a 'note' diagnostic for an overload candidate. We've
8982/// already generated a primary error at the call site.
8983///
8984/// It really does need to be a single diagnostic with its caret
8985/// pointed at the candidate declaration. Yes, this creates some
8986/// major challenges of technical writing. Yes, this makes pointing
8987/// out problems with specific arguments quite awkward. It's still
8988/// better than generating twenty screens of text for every failed
8989/// overload.
8990///
8991/// It would be great to be able to express per-candidate problems
8992/// more richly for those diagnostic clients that cared, but we'd
8993/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00008994void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008995 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00008996 FunctionDecl *Fn = Cand->Function;
8997
John McCall12f97bc2010-01-08 04:41:39 +00008998 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008999 if (Cand->Viable && (Fn->isDeleted() ||
9000 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009001 std::string FnDesc;
9002 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009003
9004 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009005 << FnKind << FnDesc
9006 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009007 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009008 return;
John McCall12f97bc2010-01-08 04:41:39 +00009009 }
9010
John McCalle1ac8d12010-01-13 00:25:19 +00009011 // We don't really have anything else to say about viable candidates.
9012 if (Cand->Viable) {
9013 S.NoteOverloadCandidate(Fn);
9014 return;
9015 }
John McCall0d1da222010-01-12 00:44:57 +00009016
John McCall6a61b522010-01-13 09:16:55 +00009017 switch (Cand->FailureKind) {
9018 case ovl_fail_too_many_arguments:
9019 case ovl_fail_too_few_arguments:
9020 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009021
John McCall6a61b522010-01-13 09:16:55 +00009022 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009023 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009024
John McCallfe796dd2010-01-23 05:17:32 +00009025 case ovl_fail_trivial_conversion:
9026 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009027 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009028 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009029
John McCall65eb8792010-02-25 01:37:24 +00009030 case ovl_fail_bad_conversion: {
9031 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009032 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009033 if (Cand->Conversions[I].isBad())
9034 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009035
John McCall6a61b522010-01-13 09:16:55 +00009036 // FIXME: this currently happens when we're called from SemaInit
9037 // when user-conversion overload fails. Figure out how to handle
9038 // those conditions and diagnose them well.
9039 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009040 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009041
9042 case ovl_fail_bad_target:
9043 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009044
9045 case ovl_fail_enable_if:
9046 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009047 }
John McCalld3224162010-01-08 00:58:21 +00009048}
9049
9050void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9051 // Desugar the type of the surrogate down to a function type,
9052 // retaining as many typedefs as possible while still showing
9053 // the function type (and, therefore, its parameter types).
9054 QualType FnType = Cand->Surrogate->getConversionType();
9055 bool isLValueReference = false;
9056 bool isRValueReference = false;
9057 bool isPointer = false;
9058 if (const LValueReferenceType *FnTypeRef =
9059 FnType->getAs<LValueReferenceType>()) {
9060 FnType = FnTypeRef->getPointeeType();
9061 isLValueReference = true;
9062 } else if (const RValueReferenceType *FnTypeRef =
9063 FnType->getAs<RValueReferenceType>()) {
9064 FnType = FnTypeRef->getPointeeType();
9065 isRValueReference = true;
9066 }
9067 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9068 FnType = FnTypePtr->getPointeeType();
9069 isPointer = true;
9070 }
9071 // Desugar down to a function type.
9072 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9073 // Reconstruct the pointer/reference as appropriate.
9074 if (isPointer) FnType = S.Context.getPointerType(FnType);
9075 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9076 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9077
9078 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9079 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009080 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009081}
9082
9083void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie1d202a62012-10-08 01:11:04 +00009084 StringRef Opc,
John McCalld3224162010-01-08 00:58:21 +00009085 SourceLocation OpLoc,
9086 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009087 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009088 std::string TypeStr("operator");
9089 TypeStr += Opc;
9090 TypeStr += "(";
9091 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009092 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009093 TypeStr += ")";
9094 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9095 } else {
9096 TypeStr += ", ";
9097 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9098 TypeStr += ")";
9099 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9100 }
9101}
9102
9103void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9104 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009105 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009106 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9107 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009108 if (ICS.isBad()) break; // all meaningless after first invalid
9109 if (!ICS.isAmbiguous()) continue;
9110
John McCall5c32be02010-08-24 20:38:10 +00009111 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009112 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009113 }
9114}
9115
Larisse Voufo98b20f12013-07-19 23:00:19 +00009116static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009117 if (Cand->Function)
9118 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009119 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009120 return Cand->Surrogate->getLocation();
9121 return SourceLocation();
9122}
9123
Larisse Voufo98b20f12013-07-19 23:00:19 +00009124static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009125 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009126 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009127 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009128
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009129 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009130 case Sema::TDK_Incomplete:
9131 return 1;
9132
9133 case Sema::TDK_Underqualified:
9134 case Sema::TDK_Inconsistent:
9135 return 2;
9136
9137 case Sema::TDK_SubstitutionFailure:
9138 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009139 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009140 return 3;
9141
9142 case Sema::TDK_InstantiationDepth:
9143 case Sema::TDK_FailedOverloadResolution:
9144 return 4;
9145
9146 case Sema::TDK_InvalidExplicitArguments:
9147 return 5;
9148
9149 case Sema::TDK_TooManyArguments:
9150 case Sema::TDK_TooFewArguments:
9151 return 6;
9152 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009153 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009154}
9155
John McCallad2587a2010-01-12 00:48:53 +00009156struct CompareOverloadCandidatesForDisplay {
9157 Sema &S;
9158 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00009159
9160 bool operator()(const OverloadCandidate *L,
9161 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009162 // Fast-path this check.
9163 if (L == R) return false;
9164
John McCall12f97bc2010-01-08 04:41:39 +00009165 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009166 if (L->Viable) {
9167 if (!R->Viable) return true;
9168
9169 // TODO: introduce a tri-valued comparison for overload
9170 // candidates. Would be more worthwhile if we had a sort
9171 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009172 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9173 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009174 } else if (R->Viable)
9175 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009176
John McCall3712d9e2010-01-15 23:32:50 +00009177 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009178
John McCall3712d9e2010-01-15 23:32:50 +00009179 // Criteria by which we can sort non-viable candidates:
9180 if (!L->Viable) {
9181 // 1. Arity mismatches come after other candidates.
9182 if (L->FailureKind == ovl_fail_too_many_arguments ||
9183 L->FailureKind == ovl_fail_too_few_arguments)
9184 return false;
9185 if (R->FailureKind == ovl_fail_too_many_arguments ||
9186 R->FailureKind == ovl_fail_too_few_arguments)
9187 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009188
John McCallfe796dd2010-01-23 05:17:32 +00009189 // 2. Bad conversions come first and are ordered by the number
9190 // of bad conversions and quality of good conversions.
9191 if (L->FailureKind == ovl_fail_bad_conversion) {
9192 if (R->FailureKind != ovl_fail_bad_conversion)
9193 return true;
9194
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009195 // The conversion that can be fixed with a smaller number of changes,
9196 // comes first.
9197 unsigned numLFixes = L->Fix.NumConversionsFixed;
9198 unsigned numRFixes = R->Fix.NumConversionsFixed;
9199 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9200 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009201 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009202 if (numLFixes < numRFixes)
9203 return true;
9204 else
9205 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009206 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009207
John McCallfe796dd2010-01-23 05:17:32 +00009208 // If there's any ordering between the defined conversions...
9209 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009210 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009211
9212 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009213 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009214 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009215 switch (CompareImplicitConversionSequences(S,
9216 L->Conversions[I],
9217 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009218 case ImplicitConversionSequence::Better:
9219 leftBetter++;
9220 break;
9221
9222 case ImplicitConversionSequence::Worse:
9223 leftBetter--;
9224 break;
9225
9226 case ImplicitConversionSequence::Indistinguishable:
9227 break;
9228 }
9229 }
9230 if (leftBetter > 0) return true;
9231 if (leftBetter < 0) return false;
9232
9233 } else if (R->FailureKind == ovl_fail_bad_conversion)
9234 return false;
9235
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009236 if (L->FailureKind == ovl_fail_bad_deduction) {
9237 if (R->FailureKind != ovl_fail_bad_deduction)
9238 return true;
9239
9240 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9241 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009242 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009243 } else if (R->FailureKind == ovl_fail_bad_deduction)
9244 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009245
John McCall3712d9e2010-01-15 23:32:50 +00009246 // TODO: others?
9247 }
9248
9249 // Sort everything else by location.
9250 SourceLocation LLoc = GetLocationForCandidate(L);
9251 SourceLocation RLoc = GetLocationForCandidate(R);
9252
9253 // Put candidates without locations (e.g. builtins) at the end.
9254 if (LLoc.isInvalid()) return false;
9255 if (RLoc.isInvalid()) return true;
9256
9257 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009258 }
9259};
9260
John McCallfe796dd2010-01-23 05:17:32 +00009261/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009262/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00009263void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009264 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009265 assert(!Cand->Viable);
9266
9267 // Don't do anything on failures other than bad conversion.
9268 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9269
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009270 // We only want the FixIts if all the arguments can be corrected.
9271 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009272 // Use a implicit copy initialization to check conversion fixes.
9273 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009274
John McCallfe796dd2010-01-23 05:17:32 +00009275 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009276 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009277 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009278 while (true) {
9279 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9280 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009281 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009282 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009283 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009284 }
John McCallfe796dd2010-01-23 05:17:32 +00009285 }
9286
9287 if (ConvIdx == ConvCount)
9288 return;
9289
John McCall65eb8792010-02-25 01:37:24 +00009290 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9291 "remaining conversion is initialized?");
9292
Douglas Gregoradc7a702010-04-16 17:45:54 +00009293 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009294 // operation somehow.
9295 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009296
9297 const FunctionProtoType* Proto;
9298 unsigned ArgIdx = ConvIdx;
9299
9300 if (Cand->IsSurrogate) {
9301 QualType ConvType
9302 = Cand->Surrogate->getConversionType().getNonReferenceType();
9303 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9304 ConvType = ConvPtrType->getPointeeType();
9305 Proto = ConvType->getAs<FunctionProtoType>();
9306 ArgIdx--;
9307 } else if (Cand->Function) {
9308 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9309 if (isa<CXXMethodDecl>(Cand->Function) &&
9310 !isa<CXXConstructorDecl>(Cand->Function))
9311 ArgIdx--;
9312 } else {
9313 // Builtin binary operator with a bad first conversion.
9314 assert(ConvCount <= 3);
9315 for (; ConvIdx != ConvCount; ++ConvIdx)
9316 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009317 = TryCopyInitialization(S, Args[ConvIdx],
9318 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009319 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009320 /*InOverloadResolution*/ true,
9321 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009322 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009323 return;
9324 }
9325
9326 // Fill in the rest of the conversions.
9327 unsigned NumArgsInProto = Proto->getNumArgs();
9328 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009329 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00009330 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009331 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009332 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009333 /*InOverloadResolution=*/true,
9334 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009335 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009336 // Store the FixIt in the candidate if it exists.
9337 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009338 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009339 }
John McCallfe796dd2010-01-23 05:17:32 +00009340 else
9341 Cand->Conversions[ConvIdx].setEllipsis();
9342 }
9343}
9344
John McCalld3224162010-01-08 00:58:21 +00009345} // end anonymous namespace
9346
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009347/// PrintOverloadCandidates - When overload resolution fails, prints
9348/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009349/// set.
John McCall5c32be02010-08-24 20:38:10 +00009350void OverloadCandidateSet::NoteCandidates(Sema &S,
9351 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009352 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009353 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009354 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009355 // Sort the candidates by viability and position. Sorting directly would
9356 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009357 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009358 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9359 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009360 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009361 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009362 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009363 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009364 if (Cand->Function || Cand->IsSurrogate)
9365 Cands.push_back(Cand);
9366 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9367 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009368 }
9369 }
9370
John McCallad2587a2010-01-12 00:48:53 +00009371 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00009372 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009373
John McCall0d1da222010-01-12 00:44:57 +00009374 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009375
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009376 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009377 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009378 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009379 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9380 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009381
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009382 // Set an arbitrary limit on the number of candidate functions we'll spam
9383 // the user with. FIXME: This limit should depend on details of the
9384 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009385 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009386 break;
9387 }
9388 ++CandsShown;
9389
John McCalld3224162010-01-08 00:58:21 +00009390 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009391 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009392 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009393 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009394 else {
9395 assert(Cand->Viable &&
9396 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009397 // Generally we only see ambiguities including viable builtin
9398 // operators if overload resolution got screwed up by an
9399 // ambiguous user-defined conversion.
9400 //
9401 // FIXME: It's quite possible for different conversions to see
9402 // different ambiguities, though.
9403 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009404 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009405 ReportedAmbiguousConversions = true;
9406 }
John McCalld3224162010-01-08 00:58:21 +00009407
John McCall0d1da222010-01-12 00:44:57 +00009408 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009409 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009410 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009411 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009412
9413 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009414 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009415}
9416
Larisse Voufo98b20f12013-07-19 23:00:19 +00009417static SourceLocation
9418GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9419 return Cand->Specialization ? Cand->Specialization->getLocation()
9420 : SourceLocation();
9421}
9422
9423struct CompareTemplateSpecCandidatesForDisplay {
9424 Sema &S;
9425 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9426
9427 bool operator()(const TemplateSpecCandidate *L,
9428 const TemplateSpecCandidate *R) {
9429 // Fast-path this check.
9430 if (L == R)
9431 return false;
9432
9433 // Assuming that both candidates are not matches...
9434
9435 // Sort by the ranking of deduction failures.
9436 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9437 return RankDeductionFailure(L->DeductionFailure) <
9438 RankDeductionFailure(R->DeductionFailure);
9439
9440 // Sort everything else by location.
9441 SourceLocation LLoc = GetLocationForCandidate(L);
9442 SourceLocation RLoc = GetLocationForCandidate(R);
9443
9444 // Put candidates without locations (e.g. builtins) at the end.
9445 if (LLoc.isInvalid())
9446 return false;
9447 if (RLoc.isInvalid())
9448 return true;
9449
9450 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9451 }
9452};
9453
9454/// Diagnose a template argument deduction failure.
9455/// We are treating these failures as overload failures due to bad
9456/// deductions.
9457void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9458 DiagnoseBadDeduction(S, Specialization, // pattern
9459 DeductionFailure, /*NumArgs=*/0);
9460}
9461
9462void TemplateSpecCandidateSet::destroyCandidates() {
9463 for (iterator i = begin(), e = end(); i != e; ++i) {
9464 i->DeductionFailure.Destroy();
9465 }
9466}
9467
9468void TemplateSpecCandidateSet::clear() {
9469 destroyCandidates();
9470 Candidates.clear();
9471}
9472
9473/// NoteCandidates - When no template specialization match is found, prints
9474/// diagnostic messages containing the non-matching specializations that form
9475/// the candidate set.
9476/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9477/// OCD == OCD_AllCandidates and Cand->Viable == false.
9478void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9479 // Sort the candidates by position (assuming no candidate is a match).
9480 // Sorting directly would be prohibitive, so we make a set of pointers
9481 // and sort those.
9482 SmallVector<TemplateSpecCandidate *, 32> Cands;
9483 Cands.reserve(size());
9484 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9485 if (Cand->Specialization)
9486 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009487 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009488 // in general, want to list every possible builtin candidate.
9489 }
9490
9491 std::sort(Cands.begin(), Cands.end(),
9492 CompareTemplateSpecCandidatesForDisplay(S));
9493
9494 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9495 // for generalization purposes (?).
9496 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9497
9498 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9499 unsigned CandsShown = 0;
9500 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9501 TemplateSpecCandidate *Cand = *I;
9502
9503 // Set an arbitrary limit on the number of candidates we'll spam
9504 // the user with. FIXME: This limit should depend on details of the
9505 // candidate list.
9506 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9507 break;
9508 ++CandsShown;
9509
9510 assert(Cand->Specialization &&
9511 "Non-matching built-in candidates are not added to Cands.");
9512 Cand->NoteDeductionFailure(S);
9513 }
9514
9515 if (I != E)
9516 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9517}
9518
Douglas Gregorb491ed32011-02-19 21:32:49 +00009519// [PossiblyAFunctionType] --> [Return]
9520// NonFunctionType --> NonFunctionType
9521// R (A) --> R(A)
9522// R (*)(A) --> R (A)
9523// R (&)(A) --> R (A)
9524// R (S::*)(A) --> R (A)
9525QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9526 QualType Ret = PossiblyAFunctionType;
9527 if (const PointerType *ToTypePtr =
9528 PossiblyAFunctionType->getAs<PointerType>())
9529 Ret = ToTypePtr->getPointeeType();
9530 else if (const ReferenceType *ToTypeRef =
9531 PossiblyAFunctionType->getAs<ReferenceType>())
9532 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009533 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009534 PossiblyAFunctionType->getAs<MemberPointerType>())
9535 Ret = MemTypePtr->getPointeeType();
9536 Ret =
9537 Context.getCanonicalType(Ret).getUnqualifiedType();
9538 return Ret;
9539}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009540
Douglas Gregorb491ed32011-02-19 21:32:49 +00009541// A helper class to help with address of function resolution
9542// - allows us to avoid passing around all those ugly parameters
9543class AddressOfFunctionResolver
9544{
9545 Sema& S;
9546 Expr* SourceExpr;
9547 const QualType& TargetType;
9548 QualType TargetFunctionType; // Extracted function type from target type
9549
9550 bool Complain;
9551 //DeclAccessPair& ResultFunctionAccessPair;
9552 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009553
Douglas Gregorb491ed32011-02-19 21:32:49 +00009554 bool TargetTypeIsNonStaticMemberFunction;
9555 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009556 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009557
Douglas Gregorb491ed32011-02-19 21:32:49 +00009558 OverloadExpr::FindResult OvlExprInfo;
9559 OverloadExpr *OvlExpr;
9560 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009561 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009562 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009563
Douglas Gregorb491ed32011-02-19 21:32:49 +00009564public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009565 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9566 const QualType &TargetType, bool Complain)
9567 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9568 Complain(Complain), Context(S.getASTContext()),
9569 TargetTypeIsNonStaticMemberFunction(
9570 !!TargetType->getAs<MemberPointerType>()),
9571 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009572 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009573 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9574 OvlExpr(OvlExprInfo.Expression),
9575 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009576 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009577
David Majnemera4f7c7a2013-08-01 06:13:59 +00009578 if (TargetFunctionType->isFunctionType()) {
9579 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9580 if (!UME->isImplicitAccess() &&
9581 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9582 StaticMemberFunctionFromBoundPointer = true;
9583 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9584 DeclAccessPair dap;
9585 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9586 OvlExpr, false, &dap)) {
9587 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9588 if (!Method->isStatic()) {
9589 // If the target type is a non-function type and the function found
9590 // is a non-static member function, pretend as if that was the
9591 // target, it's the only possible type to end up with.
9592 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +00009593
David Majnemera4f7c7a2013-08-01 06:13:59 +00009594 // And skip adding the function if its not in the proper form.
9595 // We'll diagnose this due to an empty set of functions.
9596 if (!OvlExprInfo.HasFormOfMemberPointer)
9597 return;
Chandler Carruthffce2452011-03-29 08:08:18 +00009598 }
9599
David Majnemera4f7c7a2013-08-01 06:13:59 +00009600 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +00009601 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009602 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00009603 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009604
9605 if (OvlExpr->hasExplicitTemplateArgs())
9606 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00009607
Douglas Gregorb491ed32011-02-19 21:32:49 +00009608 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9609 // C++ [over.over]p4:
9610 // If more than one function is selected, [...]
9611 if (Matches.size() > 1) {
9612 if (FoundNonTemplateFunction)
9613 EliminateAllTemplateMatches();
9614 else
9615 EliminateAllExceptMostSpecializedTemplate();
9616 }
9617 }
9618 }
9619
9620private:
9621 bool isTargetTypeAFunction() const {
9622 return TargetFunctionType->isFunctionType();
9623 }
9624
9625 // [ToType] [Return]
9626
9627 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9628 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9629 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9630 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9631 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9632 }
9633
9634 // return true if any matching specializations were found
9635 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9636 const DeclAccessPair& CurAccessFunPair) {
9637 if (CXXMethodDecl *Method
9638 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9639 // Skip non-static function templates when converting to pointer, and
9640 // static when converting to member pointer.
9641 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9642 return false;
9643 }
9644 else if (TargetTypeIsNonStaticMemberFunction)
9645 return false;
9646
9647 // C++ [over.over]p2:
9648 // If the name is a function template, template argument deduction is
9649 // done (14.8.2.2), and if the argument deduction succeeds, the
9650 // resulting template argument list is used to generate a single
9651 // function template specialization, which is added to the set of
9652 // overloaded functions considered.
9653 FunctionDecl *Specialization = 0;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009654 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009655 if (Sema::TemplateDeductionResult Result
9656 = S.DeduceTemplateArguments(FunctionTemplate,
9657 &OvlExplicitTemplateArgs,
9658 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009659 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009660 // Make a note of the failed deduction for diagnostics.
9661 FailedCandidates.addCandidate()
9662 .set(FunctionTemplate->getTemplatedDecl(),
9663 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009664 return false;
9665 }
9666
Douglas Gregor19a41f12013-04-17 08:45:07 +00009667 // Template argument deduction ensures that we have an exact match or
9668 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009669 // This function template specicalization works.
9670 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +00009671 assert(S.isSameOrCompatibleFunctionType(
9672 Context.getCanonicalType(Specialization->getType()),
9673 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009674 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9675 return true;
9676 }
9677
9678 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9679 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009680 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009681 // Skip non-static functions when converting to pointer, and static
9682 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009683 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9684 return false;
9685 }
9686 else if (TargetTypeIsNonStaticMemberFunction)
9687 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009688
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009689 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009690 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009691 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9692 if (S.CheckCUDATarget(Caller, FunDecl))
9693 return false;
9694
Richard Smith2a7d4812013-05-04 07:00:32 +00009695 // If any candidate has a placeholder return type, trigger its deduction
9696 // now.
9697 if (S.getLangOpts().CPlusPlus1y &&
9698 FunDecl->getResultType()->isUndeducedType() &&
9699 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9700 return false;
9701
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009702 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009703 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9704 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009705 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9706 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009707 Matches.push_back(std::make_pair(CurAccessFunPair,
9708 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009709 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009710 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009711 }
Mike Stump11289f42009-09-09 15:08:12 +00009712 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009713
9714 return false;
9715 }
9716
9717 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9718 bool Ret = false;
9719
9720 // If the overload expression doesn't have the form of a pointer to
9721 // member, don't try to convert it to a pointer-to-member type.
9722 if (IsInvalidFormOfPointerToMemberFunction())
9723 return false;
9724
9725 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9726 E = OvlExpr->decls_end();
9727 I != E; ++I) {
9728 // Look through any using declarations to find the underlying function.
9729 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9730
9731 // C++ [over.over]p3:
9732 // Non-member functions and static member functions match
9733 // targets of type "pointer-to-function" or "reference-to-function."
9734 // Nonstatic member functions match targets of
9735 // type "pointer-to-member-function."
9736 // Note that according to DR 247, the containing class does not matter.
9737 if (FunctionTemplateDecl *FunctionTemplate
9738 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9739 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9740 Ret = true;
9741 }
9742 // If we have explicit template arguments supplied, skip non-templates.
9743 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9744 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9745 Ret = true;
9746 }
9747 assert(Ret || Matches.empty());
9748 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009749 }
9750
Douglas Gregorb491ed32011-02-19 21:32:49 +00009751 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00009752 // [...] and any given function template specialization F1 is
9753 // eliminated if the set contains a second function template
9754 // specialization whose function template is more specialized
9755 // than the function template of F1 according to the partial
9756 // ordering rules of 14.5.5.2.
9757
9758 // The algorithm specified above is quadratic. We instead use a
9759 // two-pass algorithm (similar to the one used to identify the
9760 // best viable function in an overload set) that identifies the
9761 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00009762
9763 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9764 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9765 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009766
Larisse Voufo98b20f12013-07-19 23:00:19 +00009767 // TODO: It looks like FailedCandidates does not serve much purpose
9768 // here, since the no_viable diagnostic has index 0.
9769 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00009770 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009771 SourceExpr->getLocStart(), S.PDiag(),
9772 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9773 .second->getDeclName(),
9774 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9775 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009776
Douglas Gregorb491ed32011-02-19 21:32:49 +00009777 if (Result != MatchesCopy.end()) {
9778 // Make it the first and only element
9779 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9780 Matches[0].second = cast<FunctionDecl>(*Result);
9781 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00009782 }
9783 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009784
Douglas Gregorb491ed32011-02-19 21:32:49 +00009785 void EliminateAllTemplateMatches() {
9786 // [...] any function template specializations in the set are
9787 // eliminated if the set also contains a non-template function, [...]
9788 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9789 if (Matches[I].second->getPrimaryTemplate() == 0)
9790 ++I;
9791 else {
9792 Matches[I] = Matches[--N];
9793 Matches.set_size(N);
9794 }
9795 }
9796 }
9797
9798public:
9799 void ComplainNoMatchesFound() const {
9800 assert(Matches.empty());
9801 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9802 << OvlExpr->getName() << TargetFunctionType
9803 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +00009804 if (FailedCandidates.empty())
9805 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9806 else {
9807 // We have some deduction failure messages. Use them to diagnose
9808 // the function templates, and diagnose the non-template candidates
9809 // normally.
9810 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9811 IEnd = OvlExpr->decls_end();
9812 I != IEnd; ++I)
9813 if (FunctionDecl *Fun =
9814 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9815 S.NoteOverloadCandidate(Fun, TargetFunctionType);
9816 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9817 }
9818 }
9819
Douglas Gregorb491ed32011-02-19 21:32:49 +00009820 bool IsInvalidFormOfPointerToMemberFunction() const {
9821 return TargetTypeIsNonStaticMemberFunction &&
9822 !OvlExprInfo.HasFormOfMemberPointer;
9823 }
David Majnemera4f7c7a2013-08-01 06:13:59 +00009824
Douglas Gregorb491ed32011-02-19 21:32:49 +00009825 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9826 // TODO: Should we condition this on whether any functions might
9827 // have matched, or is it more appropriate to do that in callers?
9828 // TODO: a fixit wouldn't hurt.
9829 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9830 << TargetType << OvlExpr->getSourceRange();
9831 }
David Majnemera4f7c7a2013-08-01 06:13:59 +00009832
9833 bool IsStaticMemberFunctionFromBoundPointer() const {
9834 return StaticMemberFunctionFromBoundPointer;
9835 }
9836
9837 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9838 S.Diag(OvlExpr->getLocStart(),
9839 diag::err_invalid_form_pointer_member_function)
9840 << OvlExpr->getSourceRange();
9841 }
9842
Douglas Gregorb491ed32011-02-19 21:32:49 +00009843 void ComplainOfInvalidConversion() const {
9844 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9845 << OvlExpr->getName() << TargetType;
9846 }
9847
9848 void ComplainMultipleMatchesFound() const {
9849 assert(Matches.size() > 1);
9850 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9851 << OvlExpr->getName()
9852 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009853 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009854 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009855
9856 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9857
Douglas Gregorb491ed32011-02-19 21:32:49 +00009858 int getNumMatches() const { return Matches.size(); }
9859
9860 FunctionDecl* getMatchingFunctionDecl() const {
9861 if (Matches.size() != 1) return 0;
9862 return Matches[0].second;
9863 }
9864
9865 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9866 if (Matches.size() != 1) return 0;
9867 return &Matches[0].first;
9868 }
9869};
9870
9871/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9872/// an overloaded function (C++ [over.over]), where @p From is an
9873/// expression with overloaded function type and @p ToType is the type
9874/// we're trying to resolve to. For example:
9875///
9876/// @code
9877/// int f(double);
9878/// int f(int);
9879///
9880/// int (*pfd)(double) = f; // selects f(double)
9881/// @endcode
9882///
9883/// This routine returns the resulting FunctionDecl if it could be
9884/// resolved, and NULL otherwise. When @p Complain is true, this
9885/// routine will emit diagnostics if there is an error.
9886FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009887Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9888 QualType TargetType,
9889 bool Complain,
9890 DeclAccessPair &FoundResult,
9891 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009892 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009893
9894 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9895 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009896 int NumMatches = Resolver.getNumMatches();
9897 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009898 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009899 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9900 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9901 else
9902 Resolver.ComplainNoMatchesFound();
9903 }
9904 else if (NumMatches > 1 && Complain)
9905 Resolver.ComplainMultipleMatchesFound();
9906 else if (NumMatches == 1) {
9907 Fn = Resolver.getMatchingFunctionDecl();
9908 assert(Fn);
9909 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +00009910 if (Complain) {
9911 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
9912 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
9913 else
9914 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9915 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00009916 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009917
9918 if (pHadMultipleCandidates)
9919 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009920 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009921}
9922
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009923/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009924/// resolve that overloaded function expression down to a single function.
9925///
9926/// This routine can only resolve template-ids that refer to a single function
9927/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009928/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009929/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +00009930///
9931/// If no template-ids are found, no diagnostics are emitted and NULL is
9932/// returned.
John McCall0009fcc2011-04-26 20:42:42 +00009933FunctionDecl *
9934Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9935 bool Complain,
9936 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009937 // C++ [over.over]p1:
9938 // [...] [Note: any redundant set of parentheses surrounding the
9939 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009940 // C++ [over.over]p1:
9941 // [...] The overloaded function name can be preceded by the &
9942 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009943
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009944 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009945 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009946 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009947
9948 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009949 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009950 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009951
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009952 // Look through all of the overloaded functions, searching for one
9953 // whose type matches exactly.
9954 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009955 for (UnresolvedSetIterator I = ovl->decls_begin(),
9956 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009957 // C++0x [temp.arg.explicit]p3:
9958 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009959 // where deduction is not done, if a template argument list is
9960 // specified and it, along with any default template arguments,
9961 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009962 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009963 FunctionTemplateDecl *FunctionTemplate
9964 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009965
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009966 // C++ [over.over]p2:
9967 // If the name is a function template, template argument deduction is
9968 // done (14.8.2.2), and if the argument deduction succeeds, the
9969 // resulting template argument list is used to generate a single
9970 // function template specialization, which is added to the set of
9971 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009972 FunctionDecl *Specialization = 0;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009973 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009974 if (TemplateDeductionResult Result
9975 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009976 Specialization, Info,
9977 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009978 // Make a note of the failed deduction for diagnostics.
9979 // TODO: Actually use the failed-deduction info?
9980 FailedCandidates.addCandidate()
9981 .set(FunctionTemplate->getTemplatedDecl(),
9982 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009983 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009984 }
9985
John McCall0009fcc2011-04-26 20:42:42 +00009986 assert(Specialization && "no specialization and no error?");
9987
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009988 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009989 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009990 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00009991 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9992 << ovl->getName();
9993 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009994 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009995 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00009996 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009997
John McCall0009fcc2011-04-26 20:42:42 +00009998 Matched = Specialization;
9999 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010000 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010001
Richard Smith2a7d4812013-05-04 07:00:32 +000010002 if (Matched && getLangOpts().CPlusPlus1y &&
10003 Matched->getResultType()->isUndeducedType() &&
10004 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10005 return 0;
10006
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010007 return Matched;
10008}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010009
Douglas Gregor1beec452011-03-12 01:48:56 +000010010
10011
10012
John McCall50a2c2c2011-10-11 23:14:30 +000010013// Resolve and fix an overloaded expression that can be resolved
10014// because it identifies a single function template specialization.
10015//
Douglas Gregor1beec452011-03-12 01:48:56 +000010016// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010017//
10018// Return true if it was logically possible to so resolve the
10019// expression, regardless of whether or not it succeeded. Always
10020// returns true if 'complain' is set.
10021bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10022 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10023 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010024 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010025 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010026 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010027
John McCall50a2c2c2011-10-11 23:14:30 +000010028 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010029
John McCall0009fcc2011-04-26 20:42:42 +000010030 DeclAccessPair found;
10031 ExprResult SingleFunctionExpression;
10032 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10033 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010034 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010035 SrcExpr = ExprError();
10036 return true;
10037 }
John McCall0009fcc2011-04-26 20:42:42 +000010038
10039 // It is only correct to resolve to an instance method if we're
10040 // resolving a form that's permitted to be a pointer to member.
10041 // Otherwise we'll end up making a bound member expression, which
10042 // is illegal in all the contexts we resolve like this.
10043 if (!ovl.HasFormOfMemberPointer &&
10044 isa<CXXMethodDecl>(fn) &&
10045 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010046 if (!complain) return false;
10047
10048 Diag(ovl.Expression->getExprLoc(),
10049 diag::err_bound_member_function)
10050 << 0 << ovl.Expression->getSourceRange();
10051
10052 // TODO: I believe we only end up here if there's a mix of
10053 // static and non-static candidates (otherwise the expression
10054 // would have 'bound member' type, not 'overload' type).
10055 // Ideally we would note which candidate was chosen and why
10056 // the static candidates were rejected.
10057 SrcExpr = ExprError();
10058 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010059 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010060
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010061 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010062 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +000010063 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +000010064
10065 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010066 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010067 SingleFunctionExpression =
10068 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +000010069 if (SingleFunctionExpression.isInvalid()) {
10070 SrcExpr = ExprError();
10071 return true;
10072 }
10073 }
John McCall0009fcc2011-04-26 20:42:42 +000010074 }
10075
10076 if (!SingleFunctionExpression.isUsable()) {
10077 if (complain) {
10078 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10079 << ovl.Expression->getName()
10080 << DestTypeForComplaining
10081 << OpRangeForComplaining
10082 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010083 NoteAllOverloadCandidates(SrcExpr.get());
10084
10085 SrcExpr = ExprError();
10086 return true;
10087 }
10088
10089 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010090 }
10091
John McCall50a2c2c2011-10-11 23:14:30 +000010092 SrcExpr = SingleFunctionExpression;
10093 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010094}
10095
Douglas Gregorcabea402009-09-22 15:41:20 +000010096/// \brief Add a single candidate to the overload set.
10097static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010098 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010099 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010100 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010101 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010102 bool PartialOverloading,
10103 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010104 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010105 if (isa<UsingShadowDecl>(Callee))
10106 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10107
Douglas Gregorcabea402009-09-22 15:41:20 +000010108 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010109 if (ExplicitTemplateArgs) {
10110 assert(!KnownValid && "Explicit template arguments?");
10111 return;
10112 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010113 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
10114 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010115 return;
John McCalld14a8642009-11-21 08:51:07 +000010116 }
10117
10118 if (FunctionTemplateDecl *FuncTemplate
10119 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010120 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010121 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +000010122 return;
10123 }
10124
Richard Smith95ce4f62011-06-26 22:19:54 +000010125 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010126}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010127
Douglas Gregorcabea402009-09-22 15:41:20 +000010128/// \brief Add the overload candidates named by callee and/or found by argument
10129/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010130void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010131 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010132 OverloadCandidateSet &CandidateSet,
10133 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010134
10135#ifndef NDEBUG
10136 // Verify that ArgumentDependentLookup is consistent with the rules
10137 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010138 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010139 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10140 // and let Y be the lookup set produced by argument dependent
10141 // lookup (defined as follows). If X contains
10142 //
10143 // -- a declaration of a class member, or
10144 //
10145 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010146 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010147 //
10148 // -- a declaration that is neither a function or a function
10149 // template
10150 //
10151 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010152
John McCall57500772009-12-16 12:17:52 +000010153 if (ULE->requiresADL()) {
10154 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10155 E = ULE->decls_end(); I != E; ++I) {
10156 assert(!(*I)->getDeclContext()->isRecord());
10157 assert(isa<UsingShadowDecl>(*I) ||
10158 !(*I)->getDeclContext()->isFunctionOrMethod());
10159 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010160 }
10161 }
10162#endif
10163
John McCall57500772009-12-16 12:17:52 +000010164 // It would be nice to avoid this copy.
10165 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +000010166 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +000010167 if (ULE->hasExplicitTemplateArgs()) {
10168 ULE->copyTemplateArgumentsInto(TABuffer);
10169 ExplicitTemplateArgs = &TABuffer;
10170 }
10171
10172 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10173 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010174 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10175 CandidateSet, PartialOverloading,
10176 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010177
John McCall57500772009-12-16 12:17:52 +000010178 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +000010179 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +000010180 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010181 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010182 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010183}
John McCalld681c392009-12-16 08:11:27 +000010184
Richard Smith0603bbb2013-06-12 22:56:54 +000010185/// Determine whether a declaration with the specified name could be moved into
10186/// a different namespace.
10187static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10188 switch (Name.getCXXOverloadedOperator()) {
10189 case OO_New: case OO_Array_New:
10190 case OO_Delete: case OO_Array_Delete:
10191 return false;
10192
10193 default:
10194 return true;
10195 }
10196}
10197
Richard Smith998a5912011-06-05 22:42:48 +000010198/// Attempt to recover from an ill-formed use of a non-dependent name in a
10199/// template, where the non-dependent name was declared after the template
10200/// was defined. This is common in code written for a compilers which do not
10201/// correctly implement two-stage name lookup.
10202///
10203/// Returns true if a viable candidate was found and a diagnostic was issued.
10204static bool
10205DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10206 const CXXScopeSpec &SS, LookupResult &R,
10207 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010208 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010209 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10210 return false;
10211
10212 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010213 if (DC->isTransparentContext())
10214 continue;
10215
Richard Smith998a5912011-06-05 22:42:48 +000010216 SemaRef.LookupQualifiedName(R, DC);
10217
10218 if (!R.empty()) {
10219 R.suppressDiagnostics();
10220
10221 if (isa<CXXRecordDecl>(DC)) {
10222 // Don't diagnose names we find in classes; we get much better
10223 // diagnostics for these from DiagnoseEmptyLookup.
10224 R.clear();
10225 return false;
10226 }
10227
10228 OverloadCandidateSet Candidates(FnLoc);
10229 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10230 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010231 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010232 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010233
10234 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010235 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010236 // No viable functions. Don't bother the user with notes for functions
10237 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010238 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010239 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010240 }
Richard Smith998a5912011-06-05 22:42:48 +000010241
10242 // Find the namespaces where ADL would have looked, and suggest
10243 // declaring the function there instead.
10244 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10245 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010246 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010247 AssociatedNamespaces,
10248 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010249 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010250 if (canBeDeclaredInNamespace(R.getLookupName())) {
10251 DeclContext *Std = SemaRef.getStdNamespace();
10252 for (Sema::AssociatedNamespaceSet::iterator
10253 it = AssociatedNamespaces.begin(),
10254 end = AssociatedNamespaces.end(); it != end; ++it) {
10255 // Never suggest declaring a function within namespace 'std'.
10256 if (Std && Std->Encloses(*it))
10257 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010258
Richard Smith0603bbb2013-06-12 22:56:54 +000010259 // Never suggest declaring a function within a namespace with a
10260 // reserved name, like __gnu_cxx.
10261 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10262 if (NS &&
10263 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10264 continue;
10265
10266 SuggestedNamespaces.insert(*it);
10267 }
Richard Smith998a5912011-06-05 22:42:48 +000010268 }
10269
10270 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10271 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010272 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010273 SemaRef.Diag(Best->Function->getLocation(),
10274 diag::note_not_found_by_two_phase_lookup)
10275 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010276 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010277 SemaRef.Diag(Best->Function->getLocation(),
10278 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010279 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010280 } else {
10281 // FIXME: It would be useful to list the associated namespaces here,
10282 // but the diagnostics infrastructure doesn't provide a way to produce
10283 // a localized representation of a list of items.
10284 SemaRef.Diag(Best->Function->getLocation(),
10285 diag::note_not_found_by_two_phase_lookup)
10286 << R.getLookupName() << 2;
10287 }
10288
10289 // Try to recover by calling this function.
10290 return true;
10291 }
10292
10293 R.clear();
10294 }
10295
10296 return false;
10297}
10298
10299/// Attempt to recover from ill-formed use of a non-dependent operator in a
10300/// template, where the non-dependent operator was declared after the template
10301/// was defined.
10302///
10303/// Returns true if a viable candidate was found and a diagnostic was issued.
10304static bool
10305DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10306 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010307 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010308 DeclarationName OpName =
10309 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10310 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10311 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010312 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010313}
10314
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010315namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010316class BuildRecoveryCallExprRAII {
10317 Sema &SemaRef;
10318public:
10319 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10320 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10321 SemaRef.IsBuildingRecoveryCallExpr = true;
10322 }
10323
10324 ~BuildRecoveryCallExprRAII() {
10325 SemaRef.IsBuildingRecoveryCallExpr = false;
10326 }
10327};
10328
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010329}
10330
John McCalld681c392009-12-16 08:11:27 +000010331/// Attempts to recover from a call where no functions were found.
10332///
10333/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010334static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010335BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010336 UnresolvedLookupExpr *ULE,
10337 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010338 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010339 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010340 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010341 // Do not try to recover if it is already building a recovery call.
10342 // This stops infinite loops for template instantiations like
10343 //
10344 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10345 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10346 //
10347 if (SemaRef.IsBuildingRecoveryCallExpr)
10348 return ExprError();
10349 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010350
10351 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010352 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010353 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010354
John McCall57500772009-12-16 12:17:52 +000010355 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +000010356 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +000010357 if (ULE->hasExplicitTemplateArgs()) {
10358 ULE->copyTemplateArgumentsInto(TABuffer);
10359 ExplicitTemplateArgs = &TABuffer;
10360 }
10361
John McCalld681c392009-12-16 08:11:27 +000010362 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10363 Sema::LookupOrdinaryName);
Kaelyn Uhrain53e72192013-07-08 23:13:39 +000010364 FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10365 ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010366 NoTypoCorrectionCCC RejectAll;
10367 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10368 (CorrectionCandidateCallback*)&Validator :
10369 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +000010370 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010371 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +000010372 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010373 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010374 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010375 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010376
John McCall57500772009-12-16 12:17:52 +000010377 assert(!R.empty() && "lookup results empty despite recovery");
10378
10379 // Build an implicit member call if appropriate. Just drop the
10380 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010381 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010382 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010383 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10384 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010385 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010386 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010387 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010388 else
10389 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10390
10391 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010392 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010393
10394 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010395 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010396 // end up here.
John McCallb268a282010-08-23 23:25:46 +000010397 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010398 MultiExprArg(Args.data(), Args.size()),
10399 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010400}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010401
Sam Panzer0f384432012-08-21 00:52:01 +000010402/// \brief Constructs and populates an OverloadedCandidateSet from
10403/// the given function.
10404/// \returns true when an the ExprResult output parameter has been set.
10405bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10406 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010407 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010408 SourceLocation RParenLoc,
10409 OverloadCandidateSet *CandidateSet,
10410 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010411#ifndef NDEBUG
10412 if (ULE->requiresADL()) {
10413 // To do ADL, we must have found an unqualified name.
10414 assert(!ULE->getQualifier() && "qualified name with ADL");
10415
10416 // We don't perform ADL for implicit declarations of builtins.
10417 // Verify that this was correctly set up.
10418 FunctionDecl *F;
10419 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10420 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10421 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010422 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010423
John McCall57500772009-12-16 12:17:52 +000010424 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010425 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010426 }
John McCall57500772009-12-16 12:17:52 +000010427#endif
10428
John McCall4124c492011-10-17 18:40:02 +000010429 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010430 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010431 *Result = ExprError();
10432 return true;
10433 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010434
John McCall57500772009-12-16 12:17:52 +000010435 // Add the functions denoted by the callee to the set of candidate
10436 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010437 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010438
10439 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +000010440 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10441 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +000010442 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010443 // In Microsoft mode, if we are inside a template class member function then
10444 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +000010445 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010446 // classes.
Alp Tokerbfa39342014-01-14 12:51:41 +000010447 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +000010448 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010449 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010450 Context.DependentTy, VK_RValue,
10451 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010452 CE->setTypeDependent(true);
Sam Panzer0f384432012-08-21 00:52:01 +000010453 *Result = Owned(CE);
10454 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010455 }
Sam Panzer0f384432012-08-21 00:52:01 +000010456 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +000010457 }
John McCalld681c392009-12-16 08:11:27 +000010458
John McCall4124c492011-10-17 18:40:02 +000010459 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010460 return false;
10461}
John McCall4124c492011-10-17 18:40:02 +000010462
Sam Panzer0f384432012-08-21 00:52:01 +000010463/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10464/// the completed call expression. If overload resolution fails, emits
10465/// diagnostics and returns ExprError()
10466static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10467 UnresolvedLookupExpr *ULE,
10468 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010469 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010470 SourceLocation RParenLoc,
10471 Expr *ExecConfig,
10472 OverloadCandidateSet *CandidateSet,
10473 OverloadCandidateSet::iterator *Best,
10474 OverloadingResult OverloadResult,
10475 bool AllowTypoCorrection) {
10476 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010477 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010478 RParenLoc, /*EmptyLookup=*/true,
10479 AllowTypoCorrection);
10480
10481 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010482 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010483 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010484 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010485 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10486 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010487 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010488 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10489 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010490 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010491
Richard Smith998a5912011-06-05 22:42:48 +000010492 case OR_No_Viable_Function: {
10493 // Try to recover by looking for viable functions which the user might
10494 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010495 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010496 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010497 /*EmptyLookup=*/false,
10498 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010499 if (!Recovery.isInvalid())
10500 return Recovery;
10501
Sam Panzer0f384432012-08-21 00:52:01 +000010502 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010503 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000010504 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010505 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010506 break;
Richard Smith998a5912011-06-05 22:42:48 +000010507 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010508
10509 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000010510 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000010511 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010512 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010513 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010514
Sam Panzer0f384432012-08-21 00:52:01 +000010515 case OR_Deleted: {
10516 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10517 << (*Best)->Function->isDeleted()
10518 << ULE->getName()
10519 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10520 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010521 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000010522
Sam Panzer0f384432012-08-21 00:52:01 +000010523 // We emitted an error for the unvailable/deleted function call but keep
10524 // the call in the AST.
10525 FunctionDecl *FDecl = (*Best)->Function;
10526 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010527 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10528 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000010529 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010530 }
10531
Douglas Gregorb412e172010-07-25 18:17:45 +000010532 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000010533 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010534}
10535
Sam Panzer0f384432012-08-21 00:52:01 +000010536/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10537/// (which eventually refers to the declaration Func) and the call
10538/// arguments Args/NumArgs, attempt to resolve the function call down
10539/// to a specific function. If overload resolution succeeds, returns
10540/// the call expression produced by overload resolution.
10541/// Otherwise, emits diagnostics and returns ExprError.
10542ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10543 UnresolvedLookupExpr *ULE,
10544 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010545 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010546 SourceLocation RParenLoc,
10547 Expr *ExecConfig,
10548 bool AllowTypoCorrection) {
10549 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10550 ExprResult result;
10551
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010552 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10553 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000010554 return result;
10555
10556 OverloadCandidateSet::iterator Best;
10557 OverloadingResult OverloadResult =
10558 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10559
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010560 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010561 RParenLoc, ExecConfig, &CandidateSet,
10562 &Best, OverloadResult,
10563 AllowTypoCorrection);
10564}
10565
John McCall4c4c1df2010-01-26 03:27:55 +000010566static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000010567 return Functions.size() > 1 ||
10568 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10569}
10570
Douglas Gregor084d8552009-03-13 23:49:33 +000010571/// \brief Create a unary operation that may resolve to an overloaded
10572/// operator.
10573///
10574/// \param OpLoc The location of the operator itself (e.g., '*').
10575///
10576/// \param OpcIn The UnaryOperator::Opcode that describes this
10577/// operator.
10578///
James Dennett18348b62012-06-22 08:52:37 +000010579/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000010580/// considered by overload resolution. The caller needs to build this
10581/// set based on the context using, e.g.,
10582/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10583/// set should not contain any member functions; those will be added
10584/// by CreateOverloadedUnaryOp().
10585///
James Dennett91738ff2012-06-22 10:32:46 +000010586/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000010587ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000010588Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10589 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000010590 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010591 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000010592
10593 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10594 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10595 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010596 // TODO: provide better source location info.
10597 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010598
John McCall4124c492011-10-17 18:40:02 +000010599 if (checkPlaceholderForOverload(*this, Input))
10600 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010601
Douglas Gregor084d8552009-03-13 23:49:33 +000010602 Expr *Args[2] = { Input, 0 };
10603 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000010604
Douglas Gregor084d8552009-03-13 23:49:33 +000010605 // For post-increment and post-decrement, add the implicit '0' as
10606 // the second argument, so that we know this is a post-increment or
10607 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000010608 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010609 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010610 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10611 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000010612 NumArgs = 2;
10613 }
10614
Richard Smithe54c3072013-05-05 15:51:06 +000010615 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10616
Douglas Gregor084d8552009-03-13 23:49:33 +000010617 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000010618 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +000010619 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010620 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +000010621 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010622 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +000010623 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010624
John McCall58cc69d2010-01-27 01:50:18 +000010625 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010626 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010627 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010628 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010629 /*ADL*/ true, IsOverloaded(Fns),
10630 Fns.begin(), Fns.end());
Richard Smithe54c3072013-05-05 15:51:06 +000010631 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
Douglas Gregor084d8552009-03-13 23:49:33 +000010632 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010633 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000010634 OpLoc, false));
Douglas Gregor084d8552009-03-13 23:49:33 +000010635 }
10636
10637 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010638 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010639
10640 // Add the candidates from the given function set.
Richard Smithe54c3072013-05-05 15:51:06 +000010641 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010642
10643 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010644 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010645
John McCall4c4c1df2010-01-26 03:27:55 +000010646 // Add candidates from ADL.
Richard Smithe54c3072013-05-05 15:51:06 +000010647 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10648 ArgsArray, /*ExplicitTemplateArgs*/ 0,
John McCall4c4c1df2010-01-26 03:27:55 +000010649 CandidateSet);
10650
Douglas Gregor084d8552009-03-13 23:49:33 +000010651 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010652 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010653
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010654 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10655
Douglas Gregor084d8552009-03-13 23:49:33 +000010656 // Perform overload resolution.
10657 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010658 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010659 case OR_Success: {
10660 // We found a built-in operator or an overloaded operator.
10661 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010662
Douglas Gregor084d8552009-03-13 23:49:33 +000010663 if (FnDecl) {
10664 // We matched an overloaded operator. Build a call to that
10665 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010666
Douglas Gregor084d8552009-03-13 23:49:33 +000010667 // Convert the arguments.
10668 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +000010669 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010670
John Wiegley01296292011-04-08 18:41:53 +000010671 ExprResult InputRes =
10672 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10673 Best->FoundDecl, Method);
10674 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010675 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010676 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010677 } else {
10678 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010679 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010680 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010681 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010682 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010683 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010684 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010685 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010686 return ExprError();
John McCallb268a282010-08-23 23:25:46 +000010687 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010688 }
10689
Douglas Gregor084d8552009-03-13 23:49:33 +000010690 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000010691 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010692 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010693 if (FnExpr.isInvalid())
10694 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000010695
Richard Smithc1564702013-11-15 02:58:23 +000010696 // Determine the result type.
10697 QualType ResultTy = FnDecl->getResultType();
10698 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10699 ResultTy = ResultTy.getNonLValueExprType(Context);
10700
Eli Friedman030eee42009-11-18 03:58:17 +000010701 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000010702 CallExpr *TheCall =
Richard Smithe54c3072013-05-05 15:51:06 +000010703 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000010704 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000010705
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010706 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +000010707 FnDecl))
10708 return ExprError();
10709
John McCallb268a282010-08-23 23:25:46 +000010710 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000010711 } else {
10712 // We matched a built-in operator. Convert the arguments, then
10713 // break out so that we will build the appropriate built-in
10714 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010715 ExprResult InputRes =
10716 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10717 Best->Conversions[0], AA_Passing);
10718 if (InputRes.isInvalid())
10719 return ExprError();
10720 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010721 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000010722 }
John Wiegley01296292011-04-08 18:41:53 +000010723 }
10724
10725 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000010726 // This is an erroneous use of an operator which can be overloaded by
10727 // a non-member function. Check for non-member operators which were
10728 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010729 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000010730 // FIXME: Recover by calling the found function.
10731 return ExprError();
10732
John Wiegley01296292011-04-08 18:41:53 +000010733 // No viable function; fall through to handling this as a
10734 // built-in operator, which will produce an error message for us.
10735 break;
10736
10737 case OR_Ambiguous:
10738 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10739 << UnaryOperator::getOpcodeStr(Opc)
10740 << Input->getType()
10741 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010742 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000010743 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10744 return ExprError();
10745
10746 case OR_Deleted:
10747 Diag(OpLoc, diag::err_ovl_deleted_oper)
10748 << Best->Function->isDeleted()
10749 << UnaryOperator::getOpcodeStr(Opc)
10750 << getDeletedOrUnavailableSuffix(Best->Function)
10751 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010752 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010753 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010754 return ExprError();
10755 }
Douglas Gregor084d8552009-03-13 23:49:33 +000010756
10757 // Either we found no viable overloaded operator or we matched a
10758 // built-in operator. In either case, fall through to trying to
10759 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000010760 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000010761}
10762
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010763/// \brief Create a binary operation that may resolve to an overloaded
10764/// operator.
10765///
10766/// \param OpLoc The location of the operator itself (e.g., '+').
10767///
10768/// \param OpcIn The BinaryOperator::Opcode that describes this
10769/// operator.
10770///
James Dennett18348b62012-06-22 08:52:37 +000010771/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010772/// considered by overload resolution. The caller needs to build this
10773/// set based on the context using, e.g.,
10774/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10775/// set should not contain any member functions; those will be added
10776/// by CreateOverloadedBinOp().
10777///
10778/// \param LHS Left-hand argument.
10779/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000010780ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010781Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000010782 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000010783 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010784 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010785 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +000010786 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010787
10788 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10789 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10790 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10791
10792 // If either side is type-dependent, create an appropriate dependent
10793 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000010794 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000010795 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010796 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000010797 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000010798 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +000010799 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +000010800 Context.DependentTy,
10801 VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +000010802 OpLoc,
10803 FPFeatures.fp_contract));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010804
Douglas Gregor5287f092009-11-05 00:51:44 +000010805 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10806 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010807 VK_LValue,
10808 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +000010809 Context.DependentTy,
10810 Context.DependentTy,
Lang Hames5de91cc2012-10-02 04:45:10 +000010811 OpLoc,
10812 FPFeatures.fp_contract));
Douglas Gregor5287f092009-11-05 00:51:44 +000010813 }
John McCall4c4c1df2010-01-26 03:27:55 +000010814
10815 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +000010816 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010817 // TODO: provide better source location info in DNLoc component.
10818 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000010819 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000010820 = UnresolvedLookupExpr::Create(Context, NamingClass,
10821 NestedNameSpecifierLoc(), OpNameInfo,
10822 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010823 Fns.begin(), Fns.end());
Lang Hames5de91cc2012-10-02 04:45:10 +000010824 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10825 Context.DependentTy, VK_RValue,
10826 OpLoc, FPFeatures.fp_contract));
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010827 }
10828
John McCall4124c492011-10-17 18:40:02 +000010829 // Always do placeholder-like conversions on the RHS.
10830 if (checkPlaceholderForOverload(*this, Args[1]))
10831 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010832
John McCall526ab472011-10-25 17:37:35 +000010833 // Do placeholder-like conversion on the LHS; note that we should
10834 // not get here with a PseudoObject LHS.
10835 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000010836 if (checkPlaceholderForOverload(*this, Args[0]))
10837 return ExprError();
10838
Sebastian Redl6a96bf72009-11-18 23:10:33 +000010839 // If this is the assignment operator, we only perform overload resolution
10840 // if the left-hand side is a class or enumeration type. This is actually
10841 // a hack. The standard requires that we do overload resolution between the
10842 // various built-in candidates, but as DR507 points out, this can lead to
10843 // problems. So we do it this way, which pretty much follows what GCC does.
10844 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000010845 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000010846 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010847
John McCalle26a8722010-12-04 08:14:53 +000010848 // If this is the .* operator, which is not overloadable, just
10849 // create a built-in binary operator.
10850 if (Opc == BO_PtrMemD)
10851 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10852
Douglas Gregor084d8552009-03-13 23:49:33 +000010853 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010854 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010855
10856 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010857 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010858
10859 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010860 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010861
John McCall4c4c1df2010-01-26 03:27:55 +000010862 // Add candidates from ADL.
10863 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010864 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +000010865 /*ExplicitTemplateArgs*/ 0,
10866 CandidateSet);
10867
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010868 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010869 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010870
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010871 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10872
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010873 // Perform overload resolution.
10874 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010875 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000010876 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010877 // We found a built-in operator or an overloaded operator.
10878 FunctionDecl *FnDecl = Best->Function;
10879
10880 if (FnDecl) {
10881 // We matched an overloaded operator. Build a call to that
10882 // operator.
10883
10884 // Convert the arguments.
10885 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000010886 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000010887 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010888
Chandler Carruth8e543b32010-12-12 08:17:55 +000010889 ExprResult Arg1 =
10890 PerformCopyInitialization(
10891 InitializedEntity::InitializeParameter(Context,
10892 FnDecl->getParamDecl(0)),
10893 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010894 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010895 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010896
John Wiegley01296292011-04-08 18:41:53 +000010897 ExprResult Arg0 =
10898 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10899 Best->FoundDecl, Method);
10900 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010901 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010902 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010903 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010904 } else {
10905 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000010906 ExprResult Arg0 = PerformCopyInitialization(
10907 InitializedEntity::InitializeParameter(Context,
10908 FnDecl->getParamDecl(0)),
10909 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010910 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010911 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010912
Chandler Carruth8e543b32010-12-12 08:17:55 +000010913 ExprResult Arg1 =
10914 PerformCopyInitialization(
10915 InitializedEntity::InitializeParameter(Context,
10916 FnDecl->getParamDecl(1)),
10917 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010918 if (Arg1.isInvalid())
10919 return ExprError();
10920 Args[0] = LHS = Arg0.takeAs<Expr>();
10921 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010922 }
10923
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010924 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010925 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000010926 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010927 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010928 if (FnExpr.isInvalid())
10929 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010930
Richard Smithc1564702013-11-15 02:58:23 +000010931 // Determine the result type.
10932 QualType ResultTy = FnDecl->getResultType();
10933 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10934 ResultTy = ResultTy.getNonLValueExprType(Context);
10935
John McCallb268a282010-08-23 23:25:46 +000010936 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010937 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000010938 Args, ResultTy, VK, OpLoc,
10939 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010940
10941 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010942 FnDecl))
10943 return ExprError();
10944
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000010945 ArrayRef<const Expr *> ArgsArray(Args, 2);
10946 // Cut off the implicit 'this'.
10947 if (isa<CXXMethodDecl>(FnDecl))
10948 ArgsArray = ArgsArray.slice(1);
10949 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10950 TheCall->getSourceRange(), VariadicDoesNotApply);
10951
John McCallb268a282010-08-23 23:25:46 +000010952 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010953 } else {
10954 // We matched a built-in operator. Convert the arguments, then
10955 // break out so that we will build the appropriate built-in
10956 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010957 ExprResult ArgsRes0 =
10958 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10959 Best->Conversions[0], AA_Passing);
10960 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010961 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010962 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010963
John Wiegley01296292011-04-08 18:41:53 +000010964 ExprResult ArgsRes1 =
10965 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10966 Best->Conversions[1], AA_Passing);
10967 if (ArgsRes1.isInvalid())
10968 return ExprError();
10969 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010970 break;
10971 }
10972 }
10973
Douglas Gregor66950a32009-09-30 21:46:01 +000010974 case OR_No_Viable_Function: {
10975 // C++ [over.match.oper]p9:
10976 // If the operator is the operator , [...] and there are no
10977 // viable functions, then the operator is assumed to be the
10978 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000010979 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000010980 break;
10981
Chandler Carruth8e543b32010-12-12 08:17:55 +000010982 // For class as left operand for assignment or compound assigment
10983 // operator do not fall through to handling in built-in, but report that
10984 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000010985 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010986 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000010987 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000010988 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10989 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000010990 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000010991 if (Args[0]->getType()->isIncompleteType()) {
10992 Diag(OpLoc, diag::note_assign_lhs_incomplete)
10993 << Args[0]->getType()
10994 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10995 }
Douglas Gregor66950a32009-09-30 21:46:01 +000010996 } else {
Richard Smith998a5912011-06-05 22:42:48 +000010997 // This is an erroneous use of an operator which can be overloaded by
10998 // a non-member function. Check for non-member operators which were
10999 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011000 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011001 // FIXME: Recover by calling the found function.
11002 return ExprError();
11003
Douglas Gregor66950a32009-09-30 21:46:01 +000011004 // No viable function; try to create a built-in operation, which will
11005 // produce an error. Then, show the non-viable candidates.
11006 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011008 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011009 "C++ binary operator overloading is missing candidates!");
11010 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011011 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011012 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011013 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011014 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011015
11016 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011017 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011018 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011019 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011020 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011021 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011022 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011023 return ExprError();
11024
11025 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011026 if (isImplicitlyDeleted(Best->Function)) {
11027 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11028 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011029 << Context.getRecordType(Method->getParent())
11030 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011031
Richard Smithde1a4872012-12-28 12:23:24 +000011032 // The user probably meant to call this special member. Just
11033 // explain why it's deleted.
11034 NoteDeletedFunction(Method);
11035 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011036 } else {
11037 Diag(OpLoc, diag::err_ovl_deleted_oper)
11038 << Best->Function->isDeleted()
11039 << BinaryOperator::getOpcodeStr(Opc)
11040 << getDeletedOrUnavailableSuffix(Best->Function)
11041 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11042 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011043 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011044 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011045 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011046 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011047
Douglas Gregor66950a32009-09-30 21:46:01 +000011048 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011049 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011050}
11051
John McCalldadc5752010-08-24 06:29:42 +000011052ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011053Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11054 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011055 Expr *Base, Expr *Idx) {
11056 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011057 DeclarationName OpName =
11058 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11059
11060 // If either side is type-dependent, create an appropriate dependent
11061 // expression.
11062 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11063
John McCall58cc69d2010-01-27 01:50:18 +000011064 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011065 // CHECKME: no 'operator' keyword?
11066 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11067 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011068 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011069 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011070 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011071 /*ADL*/ true, /*Overloaded*/ false,
11072 UnresolvedSetIterator(),
11073 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011074 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011075
Sebastian Redladba46e2009-10-29 20:17:01 +000011076 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +000011077 Args,
Sebastian Redladba46e2009-10-29 20:17:01 +000011078 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000011079 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000011080 RLoc, false));
Sebastian Redladba46e2009-10-29 20:17:01 +000011081 }
11082
John McCall4124c492011-10-17 18:40:02 +000011083 // Handle placeholders on both operands.
11084 if (checkPlaceholderForOverload(*this, Args[0]))
11085 return ExprError();
11086 if (checkPlaceholderForOverload(*this, Args[1]))
11087 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011088
Sebastian Redladba46e2009-10-29 20:17:01 +000011089 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000011090 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011091
11092 // Subscript can only be overloaded as a member function.
11093
11094 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011095 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011096
11097 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011098 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011099
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011100 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11101
Sebastian Redladba46e2009-10-29 20:17:01 +000011102 // Perform overload resolution.
11103 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011104 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011105 case OR_Success: {
11106 // We found a built-in operator or an overloaded operator.
11107 FunctionDecl *FnDecl = Best->Function;
11108
11109 if (FnDecl) {
11110 // We matched an overloaded operator. Build a call to that
11111 // operator.
11112
John McCalla0296f72010-03-19 07:35:19 +000011113 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011114
Sebastian Redladba46e2009-10-29 20:17:01 +000011115 // Convert the arguments.
11116 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011117 ExprResult Arg0 =
11118 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
11119 Best->FoundDecl, Method);
11120 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011121 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011122 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000011123
Anders Carlssona68e51e2010-01-29 18:37:50 +000011124 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011125 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011126 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011127 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011128 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011129 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000011130 Owned(Args[1]));
11131 if (InputInit.isInvalid())
11132 return ExprError();
11133
11134 Args[1] = InputInit.takeAs<Expr>();
11135
Sebastian Redladba46e2009-10-29 20:17:01 +000011136 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011137 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11138 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011139 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011140 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011141 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011142 OpLocInfo.getLoc(),
11143 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011144 if (FnExpr.isInvalid())
11145 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011146
Richard Smithc1564702013-11-15 02:58:23 +000011147 // Determine the result type
11148 QualType ResultTy = FnDecl->getResultType();
11149 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11150 ResultTy = ResultTy.getNonLValueExprType(Context);
11151
John McCallb268a282010-08-23 23:25:46 +000011152 CXXOperatorCallExpr *TheCall =
11153 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramerc215e762012-08-24 11:54:20 +000011154 FnExpr.take(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011155 ResultTy, VK, RLoc,
11156 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011157
John McCallb268a282010-08-23 23:25:46 +000011158 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000011159 FnDecl))
11160 return ExprError();
11161
John McCallb268a282010-08-23 23:25:46 +000011162 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011163 } else {
11164 // We matched a built-in operator. Convert the arguments, then
11165 // break out so that we will build the appropriate built-in
11166 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011167 ExprResult ArgsRes0 =
11168 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11169 Best->Conversions[0], AA_Passing);
11170 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011171 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011172 Args[0] = ArgsRes0.take();
11173
11174 ExprResult ArgsRes1 =
11175 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11176 Best->Conversions[1], AA_Passing);
11177 if (ArgsRes1.isInvalid())
11178 return ExprError();
11179 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000011180
11181 break;
11182 }
11183 }
11184
11185 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011186 if (CandidateSet.empty())
11187 Diag(LLoc, diag::err_ovl_no_oper)
11188 << Args[0]->getType() << /*subscript*/ 0
11189 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11190 else
11191 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11192 << Args[0]->getType()
11193 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011194 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011195 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011196 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011197 }
11198
11199 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011200 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011201 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011202 << Args[0]->getType() << Args[1]->getType()
11203 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011204 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011205 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011206 return ExprError();
11207
11208 case OR_Deleted:
11209 Diag(LLoc, diag::err_ovl_deleted_oper)
11210 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011211 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011212 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011213 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011214 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011215 return ExprError();
11216 }
11217
11218 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011219 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011220}
11221
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011222/// BuildCallToMemberFunction - Build a call to a member
11223/// function. MemExpr is the expression that refers to the member
11224/// function (and includes the object parameter), Args/NumArgs are the
11225/// arguments to the function call (not including the object
11226/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011227/// expression refers to a non-static member function or an overloaded
11228/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011229ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011230Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011231 SourceLocation LParenLoc,
11232 MultiExprArg Args,
11233 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011234 assert(MemExprE->getType() == Context.BoundMemberTy ||
11235 MemExprE->getType() == Context.OverloadTy);
11236
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011237 // Dig out the member expression. This holds both the object
11238 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011239 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011240
John McCall0009fcc2011-04-26 20:42:42 +000011241 // Determine whether this is a call to a pointer-to-member function.
11242 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11243 assert(op->getType() == Context.BoundMemberTy);
11244 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11245
11246 QualType fnType =
11247 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11248
11249 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11250 QualType resultType = proto->getCallResultType(Context);
11251 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
11252
11253 // Check that the object type isn't more qualified than the
11254 // member function we're calling.
11255 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11256
11257 QualType objectType = op->getLHS()->getType();
11258 if (op->getOpcode() == BO_PtrMemI)
11259 objectType = objectType->castAs<PointerType>()->getPointeeType();
11260 Qualifiers objectQuals = objectType.getQualifiers();
11261
11262 Qualifiers difference = objectQuals - funcQuals;
11263 difference.removeObjCGCAttr();
11264 difference.removeAddressSpace();
11265 if (difference) {
11266 std::string qualsString = difference.getAsString();
11267 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11268 << fnType.getUnqualifiedType()
11269 << qualsString
11270 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11271 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011272
John McCall0009fcc2011-04-26 20:42:42 +000011273 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011274 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011275 resultType, valueKind, RParenLoc);
11276
11277 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011278 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000011279 call, 0))
11280 return ExprError();
11281
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011282 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011283 return ExprError();
11284
Richard Trieu9be9c682013-06-22 02:30:38 +000011285 if (CheckOtherCall(call, proto))
11286 return ExprError();
11287
John McCall0009fcc2011-04-26 20:42:42 +000011288 return MaybeBindToTemporary(call);
11289 }
11290
John McCall4124c492011-10-17 18:40:02 +000011291 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011292 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011293 return ExprError();
11294
John McCall10eae182009-11-30 22:42:35 +000011295 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011296 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000011297 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011298 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000011299 if (isa<MemberExpr>(NakedMemExpr)) {
11300 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011301 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011302 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011303 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011304 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011305 } else {
11306 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011307 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011308
John McCall6e9f8f62009-12-03 04:06:58 +000011309 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011310 Expr::Classification ObjectClassification
11311 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11312 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011313
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011314 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000011315 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000011316
John McCall2d74de92009-12-01 22:10:20 +000011317 // FIXME: avoid copy.
11318 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11319 if (UnresExpr->hasExplicitTemplateArgs()) {
11320 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11321 TemplateArgs = &TemplateArgsBuffer;
11322 }
11323
John McCall10eae182009-11-30 22:42:35 +000011324 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11325 E = UnresExpr->decls_end(); I != E; ++I) {
11326
John McCall6e9f8f62009-12-03 04:06:58 +000011327 NamedDecl *Func = *I;
11328 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11329 if (isa<UsingShadowDecl>(Func))
11330 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11331
Douglas Gregor02824322011-01-26 19:30:28 +000011332
Francois Pichet64225792011-01-18 05:04:39 +000011333 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011334 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011335 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011336 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011337 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011338 // If explicit template arguments were provided, we can't call a
11339 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011340 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011341 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011342
John McCalla0296f72010-03-19 07:35:19 +000011343 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011344 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011345 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011346 } else {
John McCall10eae182009-11-30 22:42:35 +000011347 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011348 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011349 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011350 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011351 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011352 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011353 }
Mike Stump11289f42009-09-09 15:08:12 +000011354
John McCall10eae182009-11-30 22:42:35 +000011355 DeclarationName DeclName = UnresExpr->getMemberName();
11356
John McCall4124c492011-10-17 18:40:02 +000011357 UnbridgedCasts.restore();
11358
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011359 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011360 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011361 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011362 case OR_Success:
11363 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011364 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011365 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011366 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11367 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011368 // If FoundDecl is different from Method (such as if one is a template
11369 // and the other a specialization), make sure DiagnoseUseOfDecl is
11370 // called on both.
11371 // FIXME: This would be more comprehensively addressed by modifying
11372 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11373 // being used.
11374 if (Method != FoundDecl.getDecl() &&
11375 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11376 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011377 break;
11378
11379 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011380 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011381 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011382 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011383 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011384 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011385 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011386
11387 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011388 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011389 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011390 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011391 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011392 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011393
11394 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011395 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011396 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011397 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011398 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011399 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011400 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011401 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011402 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011403 }
11404
John McCall16df1e52010-03-30 21:47:33 +000011405 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011406
John McCall2d74de92009-12-01 22:10:20 +000011407 // If overload resolution picked a static member, build a
11408 // non-member call based on that function.
11409 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011410 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11411 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011412 }
11413
John McCall10eae182009-11-30 22:42:35 +000011414 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011415 }
11416
John McCall7decc9e2010-11-18 06:31:45 +000011417 QualType ResultType = Method->getResultType();
11418 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11419 ResultType = ResultType.getNonLValueExprType(Context);
11420
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011421 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011422 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011423 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011424 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011425
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011426 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011427 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011428 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011429 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011430
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011431 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011432 // We only need to do this if there was actually an overload; otherwise
11433 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011434 if (!Method->isStatic()) {
11435 ExprResult ObjectArg =
11436 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11437 FoundDecl, Method);
11438 if (ObjectArg.isInvalid())
11439 return ExprError();
11440 MemExpr->setBase(ObjectArg.take());
11441 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011442
11443 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011444 const FunctionProtoType *Proto =
11445 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011446 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011447 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011448 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011449
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011450 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011451
Richard Smith55ce3522012-06-25 20:30:08 +000011452 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011453 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011454
Anders Carlsson47061ee2011-05-06 14:25:31 +000011455 if ((isa<CXXConstructorDecl>(CurContext) ||
11456 isa<CXXDestructorDecl>(CurContext)) &&
11457 TheCall->getMethodDecl()->isPure()) {
11458 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11459
Chandler Carruth59259262011-06-27 08:31:58 +000011460 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000011461 Diag(MemExpr->getLocStart(),
11462 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11463 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11464 << MD->getParent()->getDeclName();
11465
11466 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011467 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011468 }
John McCallb268a282010-08-23 23:25:46 +000011469 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011470}
11471
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011472/// BuildCallToObjectOfClassType - Build a call to an object of class
11473/// type (C++ [over.call.object]), which can end up invoking an
11474/// overloaded function call operator (@c operator()) or performing a
11475/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000011476ExprResult
John Wiegley01296292011-04-08 18:41:53 +000011477Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000011478 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011479 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011480 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000011481 if (checkPlaceholderForOverload(*this, Obj))
11482 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011483 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000011484
11485 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011486 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011487 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011488
John Wiegley01296292011-04-08 18:41:53 +000011489 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11490 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000011491
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011492 // C++ [over.call.object]p1:
11493 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000011494 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011495 // candidate functions includes at least the function call
11496 // operators of T. The function call operators of T are obtained by
11497 // ordinary lookup of the name operator() in the context of
11498 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000011499 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000011500 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011501
John Wiegley01296292011-04-08 18:41:53 +000011502 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011503 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011504 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011505
John McCall27b18f82009-11-17 02:14:36 +000011506 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11507 LookupQualifiedName(R, Record->getDecl());
11508 R.suppressDiagnostics();
11509
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011510 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000011511 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000011512 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011513 Object.get()->Classify(Context),
11514 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000011515 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000011516 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011517
Douglas Gregorab7897a2008-11-19 22:57:39 +000011518 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011519 // In addition, for each (non-explicit in C++0x) conversion function
11520 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000011521 //
11522 // operator conversion-type-id () cv-qualifier;
11523 //
11524 // where cv-qualifier is the same cv-qualification as, or a
11525 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000011526 // denotes the type "pointer to function of (P1,...,Pn) returning
11527 // R", or the type "reference to pointer to function of
11528 // (P1,...,Pn) returning R", or the type "reference to function
11529 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000011530 // is also considered as a candidate function. Similarly,
11531 // surrogate call functions are added to the set of candidate
11532 // functions for each conversion function declared in an
11533 // accessible base class provided the function is not hidden
11534 // within T by another intervening declaration.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011535 std::pair<CXXRecordDecl::conversion_iterator,
11536 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000011537 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011538 for (CXXRecordDecl::conversion_iterator
11539 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000011540 NamedDecl *D = *I;
11541 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11542 if (isa<UsingShadowDecl>(D))
11543 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011544
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011545 // Skip over templated conversion functions; they aren't
11546 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000011547 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011548 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000011549
John McCall6e9f8f62009-12-03 04:06:58 +000011550 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011551 if (!Conv->isExplicit()) {
11552 // Strip the reference type (if any) and then the pointer type (if
11553 // any) to get down to what might be a function type.
11554 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11555 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11556 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000011557
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011558 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11559 {
11560 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011561 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011562 }
11563 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000011564 }
Mike Stump11289f42009-09-09 15:08:12 +000011565
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011566 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11567
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011568 // Perform overload resolution.
11569 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000011570 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000011571 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011572 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000011573 // Overload resolution succeeded; we'll build the appropriate call
11574 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011575 break;
11576
11577 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000011578 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011579 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000011580 << Object.get()->getType() << /*call*/ 1
11581 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000011582 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011583 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000011584 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011585 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011586 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011587 break;
11588
11589 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011590 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011591 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011592 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011593 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011594 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011595
11596 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011597 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000011598 diag::err_ovl_deleted_object_call)
11599 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000011600 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011601 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000011602 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011603 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011604 break;
Mike Stump11289f42009-09-09 15:08:12 +000011605 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011606
Douglas Gregorb412e172010-07-25 18:17:45 +000011607 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011608 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011609
John McCall4124c492011-10-17 18:40:02 +000011610 UnbridgedCasts.restore();
11611
Douglas Gregorab7897a2008-11-19 22:57:39 +000011612 if (Best->Function == 0) {
11613 // Since there is no function declaration, this is one of the
11614 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000011615 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000011616 = cast<CXXConversionDecl>(
11617 Best->Conversions[0].UserDefined.ConversionFunction);
11618
John Wiegley01296292011-04-08 18:41:53 +000011619 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011620 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11621 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011622 assert(Conv == Best->FoundDecl.getDecl() &&
11623 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000011624 // We selected one of the surrogate functions that converts the
11625 // object parameter to a function pointer. Perform the conversion
11626 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011627
Fariborz Jahanian774cf792009-09-28 18:35:46 +000011628 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000011629 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011630 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11631 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011632 if (Call.isInvalid())
11633 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011634 // Record usage of conversion in an implicit cast.
11635 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11636 CK_UserDefinedConversion,
11637 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011638
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011639 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011640 }
11641
John Wiegley01296292011-04-08 18:41:53 +000011642 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000011643
Douglas Gregorab7897a2008-11-19 22:57:39 +000011644 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11645 // that calls this method, using Object for the implicit object
11646 // parameter and passing along the remaining arguments.
11647 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011648
11649 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011650 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011651 return ExprError();
11652
Chandler Carruth8e543b32010-12-12 08:17:55 +000011653 const FunctionProtoType *Proto =
11654 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011655
11656 unsigned NumArgsInProto = Proto->getNumArgs();
Mike Stump11289f42009-09-09 15:08:12 +000011657
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011658 DeclarationNameInfo OpLocInfo(
11659 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11660 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000011661 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011662 HadMultipleCandidates,
11663 OpLocInfo.getLoc(),
11664 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011665 if (NewFn.isInvalid())
11666 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011667
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011668 // Build the full argument list for the method call (the implicit object
11669 // parameter is placed at the beginning of the list).
11670 llvm::OwningArrayPtr<Expr *> MethodArgs(new Expr*[Args.size() + 1]);
11671 MethodArgs[0] = Object.get();
11672 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11673
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011674 // Once we've built TheCall, all of the expressions are properly
11675 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000011676 QualType ResultTy = Method->getResultType();
11677 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11678 ResultTy = ResultTy.getNonLValueExprType(Context);
11679
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011680 CXXOperatorCallExpr *TheCall = new (Context)
11681 CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11682 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11683 ResultTy, VK, RParenLoc, false);
11684 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011685
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011686 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000011687 Method))
11688 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011689
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011690 // We may have default arguments. If so, we need to allocate more
11691 // slots in the call for them.
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011692 if (Args.size() < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000011693 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011694
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011695 bool IsError = false;
11696
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011697 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000011698 ExprResult ObjRes =
11699 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11700 Best->FoundDecl, Method);
11701 if (ObjRes.isInvalid())
11702 IsError = true;
11703 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011704 Object = ObjRes;
John Wiegley01296292011-04-08 18:41:53 +000011705 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011706
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011707 // Check the argument types.
Benjamin Kramer3c529ca2013-10-05 10:03:01 +000011708 for (unsigned i = 0; i != NumArgsInProto; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011709 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011710 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011711 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000011712
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011713 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011714
John McCalldadc5752010-08-24 06:29:42 +000011715 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011716 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011717 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011718 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000011719 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011720
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011721 IsError |= InputInit.isInvalid();
11722 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011723 } else {
John McCalldadc5752010-08-24 06:29:42 +000011724 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011725 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11726 if (DefArg.isInvalid()) {
11727 IsError = true;
11728 break;
11729 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011730
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011731 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011732 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011733
11734 TheCall->setArg(i + 1, Arg);
11735 }
11736
11737 // If this is a variadic call, handle args passed through "...".
11738 if (Proto->isVariadic()) {
11739 // Promote the arguments (C99 6.5.2.2p7).
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011740 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
John Wiegley01296292011-04-08 18:41:53 +000011741 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11742 IsError |= Arg.isInvalid();
11743 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011744 }
11745 }
11746
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011747 if (IsError) return true;
11748
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011749 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011750
Richard Smith55ce3522012-06-25 20:30:08 +000011751 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000011752 return true;
11753
John McCalle172be52010-08-24 06:09:16 +000011754 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011755}
11756
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011757/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000011758/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011759/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000011760ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000011761Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11762 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000011763 assert(Base->getType()->isRecordType() &&
11764 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000011765
John McCall4124c492011-10-17 18:40:02 +000011766 if (checkPlaceholderForOverload(*this, Base))
11767 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011768
John McCallbc077cf2010-02-08 23:07:23 +000011769 SourceLocation Loc = Base->getExprLoc();
11770
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011771 // C++ [over.ref]p1:
11772 //
11773 // [...] An expression x->m is interpreted as (x.operator->())->m
11774 // for a class object x of type T if T::operator->() exists and if
11775 // the operator is selected as the best match function by the
11776 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000011777 DeclarationName OpName =
11778 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000011779 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011780 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000011781
John McCallbc077cf2010-02-08 23:07:23 +000011782 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011783 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000011784 return ExprError();
11785
John McCall27b18f82009-11-17 02:14:36 +000011786 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11787 LookupQualifiedName(R, BaseRecord->getDecl());
11788 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000011789
11790 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000011791 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000011792 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000011793 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000011794 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011795
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011796 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11797
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011798 // Perform overload resolution.
11799 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011800 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011801 case OR_Success:
11802 // Overload resolution succeeded; we'll build the call below.
11803 break;
11804
11805 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011806 if (CandidateSet.empty()) {
11807 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000011808 if (NoArrowOperatorFound) {
11809 // Report this specific error to the caller instead of emitting a
11810 // diagnostic, as requested.
11811 *NoArrowOperatorFound = true;
11812 return ExprError();
11813 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000011814 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11815 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011816 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000011817 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011818 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011819 }
11820 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011821 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000011822 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011823 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011824 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011825
11826 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011827 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11828 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011829 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011830 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011831
11832 case OR_Deleted:
11833 Diag(OpLoc, diag::err_ovl_deleted_oper)
11834 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011835 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011836 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011837 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011838 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011839 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011840 }
11841
John McCalla0296f72010-03-19 07:35:19 +000011842 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11843
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011844 // Convert the object parameter.
11845 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000011846 ExprResult BaseResult =
11847 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11848 Best->FoundDecl, Method);
11849 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000011850 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011851 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000011852
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011853 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000011854 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011855 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011856 if (FnExpr.isInvalid())
11857 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011858
John McCall7decc9e2010-11-18 06:31:45 +000011859 QualType ResultTy = Method->getResultType();
11860 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11861 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000011862 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011863 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011864 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011865
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011866 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011867 Method))
11868 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000011869
11870 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011871}
11872
Richard Smithbcc22fc2012-03-09 08:00:36 +000011873/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11874/// a literal operator described by the provided lookup results.
11875ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11876 DeclarationNameInfo &SuffixInfo,
11877 ArrayRef<Expr*> Args,
11878 SourceLocation LitEndLoc,
11879 TemplateArgumentListInfo *TemplateArgs) {
11880 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000011881
Richard Smithbcc22fc2012-03-09 08:00:36 +000011882 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11883 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11884 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000011885
Richard Smithbcc22fc2012-03-09 08:00:36 +000011886 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11887
Richard Smithbcc22fc2012-03-09 08:00:36 +000011888 // Perform overload resolution. This will usually be trivial, but might need
11889 // to perform substitutions for a literal operator template.
11890 OverloadCandidateSet::iterator Best;
11891 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11892 case OR_Success:
11893 case OR_Deleted:
11894 break;
11895
11896 case OR_No_Viable_Function:
11897 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11898 << R.getLookupName();
11899 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11900 return ExprError();
11901
11902 case OR_Ambiguous:
11903 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11904 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11905 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000011906 }
11907
Richard Smithbcc22fc2012-03-09 08:00:36 +000011908 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000011909 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11910 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000011911 SuffixInfo.getLoc(),
11912 SuffixInfo.getInfo());
11913 if (Fn.isInvalid())
11914 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000011915
11916 // Check the argument types. This should almost always be a no-op, except
11917 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000011918 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000011919 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000011920 ExprResult InputInit = PerformCopyInitialization(
11921 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11922 SourceLocation(), Args[ArgIdx]);
11923 if (InputInit.isInvalid())
11924 return true;
11925 ConvArgs[ArgIdx] = InputInit.take();
11926 }
11927
Richard Smithc67fdd42012-03-07 08:35:16 +000011928 QualType ResultTy = FD->getResultType();
11929 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11930 ResultTy = ResultTy.getNonLValueExprType(Context);
11931
Richard Smithc67fdd42012-03-07 08:35:16 +000011932 UserDefinedLiteral *UDL =
Benjamin Kramerc215e762012-08-24 11:54:20 +000011933 new (Context) UserDefinedLiteral(Context, Fn.take(),
11934 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000011935 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11936
11937 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11938 return ExprError();
11939
Richard Smith55ce3522012-06-25 20:30:08 +000011940 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smithc67fdd42012-03-07 08:35:16 +000011941 return ExprError();
11942
11943 return MaybeBindToTemporary(UDL);
11944}
11945
Sam Panzer0f384432012-08-21 00:52:01 +000011946/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11947/// given LookupResult is non-empty, it is assumed to describe a member which
11948/// will be invoked. Otherwise, the function will be found via argument
11949/// dependent lookup.
11950/// CallExpr is set to a valid expression and FRS_Success returned on success,
11951/// otherwise CallExpr is set to ExprError() and some non-success value
11952/// is returned.
11953Sema::ForRangeStatus
11954Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11955 SourceLocation RangeLoc, VarDecl *Decl,
11956 BeginEndFunction BEF,
11957 const DeclarationNameInfo &NameInfo,
11958 LookupResult &MemberLookup,
11959 OverloadCandidateSet *CandidateSet,
11960 Expr *Range, ExprResult *CallExpr) {
11961 CandidateSet->clear();
11962 if (!MemberLookup.empty()) {
11963 ExprResult MemberRef =
11964 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11965 /*IsPtr=*/false, CXXScopeSpec(),
11966 /*TemplateKWLoc=*/SourceLocation(),
11967 /*FirstQualifierInScope=*/0,
11968 MemberLookup,
11969 /*TemplateArgs=*/0);
11970 if (MemberRef.isInvalid()) {
11971 *CallExpr = ExprError();
11972 Diag(Range->getLocStart(), diag::note_in_for_range)
11973 << RangeLoc << BEF << Range->getType();
11974 return FRS_DiagnosticIssued;
11975 }
Dmitri Gribenko78852e92013-05-05 20:40:26 +000011976 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
Sam Panzer0f384432012-08-21 00:52:01 +000011977 if (CallExpr->isInvalid()) {
11978 *CallExpr = ExprError();
11979 Diag(Range->getLocStart(), diag::note_in_for_range)
11980 << RangeLoc << BEF << Range->getType();
11981 return FRS_DiagnosticIssued;
11982 }
11983 } else {
11984 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000011985 UnresolvedLookupExpr *Fn =
11986 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11987 NestedNameSpecifierLoc(), NameInfo,
11988 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000011989 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000011990
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011991 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000011992 CandidateSet, CallExpr);
11993 if (CandidateSet->empty() || CandidateSetError) {
11994 *CallExpr = ExprError();
11995 return FRS_NoViableFunction;
11996 }
11997 OverloadCandidateSet::iterator Best;
11998 OverloadingResult OverloadResult =
11999 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12000
12001 if (OverloadResult == OR_No_Viable_Function) {
12002 *CallExpr = ExprError();
12003 return FRS_NoViableFunction;
12004 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012005 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Sam Panzer0f384432012-08-21 00:52:01 +000012006 Loc, 0, CandidateSet, &Best,
12007 OverloadResult,
12008 /*AllowTypoCorrection=*/false);
12009 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12010 *CallExpr = ExprError();
12011 Diag(Range->getLocStart(), diag::note_in_for_range)
12012 << RangeLoc << BEF << Range->getType();
12013 return FRS_DiagnosticIssued;
12014 }
12015 }
12016 return FRS_Success;
12017}
12018
12019
Douglas Gregorcd695e52008-11-10 20:40:00 +000012020/// FixOverloadedFunctionReference - E is an expression that refers to
12021/// a C++ overloaded function (possibly with some parentheses and
12022/// perhaps a '&' around it). We have resolved the overloaded function
12023/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012024/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012025Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012026 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012027 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012028 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12029 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012030 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012031 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012032
Douglas Gregor51c538b2009-11-20 19:42:02 +000012033 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012034 }
12035
Douglas Gregor51c538b2009-11-20 19:42:02 +000012036 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012037 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12038 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012039 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012040 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012041 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012042 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012043 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012044 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012045
12046 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012047 ICE->getCastKind(),
12048 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000012049 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012050 }
12051
Douglas Gregor51c538b2009-11-20 19:42:02 +000012052 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012053 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012054 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012055 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12056 if (Method->isStatic()) {
12057 // Do nothing: static member functions aren't any different
12058 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012059 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012060 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012061 // UnresolvedLookupExpr holding an overloaded member function
12062 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012063 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12064 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012065 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012066 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012067
John McCalld14a8642009-11-21 08:51:07 +000012068 assert(isa<DeclRefExpr>(SubExpr)
12069 && "fixed to something other than a decl ref");
12070 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12071 && "fixed to a member ref with no nested name qualifier");
12072
12073 // We have taken the address of a pointer to member
12074 // function. Perform the computation here so that we get the
12075 // appropriate pointer to member type.
12076 QualType ClassType
12077 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12078 QualType MemPtrType
12079 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12080
John McCall7decc9e2010-11-18 06:31:45 +000012081 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12082 VK_RValue, OK_Ordinary,
12083 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012084 }
12085 }
John McCall16df1e52010-03-30 21:47:33 +000012086 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12087 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012088 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012089 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012090
John McCalle3027922010-08-25 11:45:40 +000012091 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012092 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012093 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012094 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012095 }
John McCalld14a8642009-11-21 08:51:07 +000012096
12097 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012098 // FIXME: avoid copy.
12099 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000012100 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012101 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12102 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012103 }
12104
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012105 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12106 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012107 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012108 Fn,
John McCall113bee02012-03-10 09:33:50 +000012109 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012110 ULE->getNameLoc(),
12111 Fn->getType(),
12112 VK_LValue,
12113 Found.getDecl(),
12114 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012115 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012116 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12117 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012118 }
12119
John McCall10eae182009-11-30 22:42:35 +000012120 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012121 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000012122 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
12123 if (MemExpr->hasExplicitTemplateArgs()) {
12124 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12125 TemplateArgs = &TemplateArgsBuffer;
12126 }
John McCall6b51f282009-11-23 01:53:49 +000012127
John McCall2d74de92009-12-01 22:10:20 +000012128 Expr *Base;
12129
John McCall7decc9e2010-11-18 06:31:45 +000012130 // If we're filling in a static method where we used to have an
12131 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012132 if (MemExpr->isImplicitAccess()) {
12133 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012134 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12135 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012136 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012137 Fn,
John McCall113bee02012-03-10 09:33:50 +000012138 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012139 MemExpr->getMemberLoc(),
12140 Fn->getType(),
12141 VK_LValue,
12142 Found.getDecl(),
12143 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012144 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012145 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12146 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012147 } else {
12148 SourceLocation Loc = MemExpr->getMemberLoc();
12149 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012150 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012151 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012152 Base = new (Context) CXXThisExpr(Loc,
12153 MemExpr->getBaseType(),
12154 /*isImplicit=*/true);
12155 }
John McCall2d74de92009-12-01 22:10:20 +000012156 } else
John McCallc3007a22010-10-26 07:05:15 +000012157 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012158
John McCall4adb38c2011-04-27 00:36:17 +000012159 ExprValueKind valueKind;
12160 QualType type;
12161 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12162 valueKind = VK_LValue;
12163 type = Fn->getType();
12164 } else {
12165 valueKind = VK_RValue;
12166 type = Context.BoundMemberTy;
12167 }
12168
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012169 MemberExpr *ME = MemberExpr::Create(Context, Base,
12170 MemExpr->isArrow(),
12171 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012172 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012173 Fn,
12174 Found,
12175 MemExpr->getMemberNameInfo(),
12176 TemplateArgs,
12177 type, valueKind, OK_Ordinary);
12178 ME->setHadMultipleCandidates(true);
Richard Smith4f6a2c42012-11-14 07:06:31 +000012179 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012180 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012181 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012182
John McCallc3007a22010-10-26 07:05:15 +000012183 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012184}
12185
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012186ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012187 DeclAccessPair Found,
12188 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000012189 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012190}
12191
Douglas Gregor5251f1b2008-10-21 16:13:35 +000012192} // end namespace clang