blob: e3355e7ccc3197b0d85308a588acb7edc0257e17 [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"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000023#include "clang/Basic/DiagnosticOptions.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
David Majnemerc729b0b2013-09-16 22:44:20 +000025#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#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>
David Blaikie8ad22e62014-05-01 23:01:41 +000036#include <cstdlib>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000037
Richard Smith17c00b42014-11-12 01:24:00 +000038using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000039using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000040
Nick Lewycky134af912013-02-07 05:08:22 +000041/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000042static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000043CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
44 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000045 SourceLocation Loc = SourceLocation(),
46 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000047 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000048 return ExprError();
49 // If FoundDecl is different from Fn (such as if one is a template
50 // and the other a specialization), make sure DiagnoseUseOfDecl is
51 // called on both.
52 // FIXME: This would be more comprehensively addressed by modifying
53 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
54 // being used.
55 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000056 return ExprError();
John McCall113bee02012-03-10 09:33:50 +000057 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000058 VK_LValue, Loc, LocInfo);
59 if (HadMultipleCandidates)
60 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000061
62 S.MarkDeclRefReferenced(DRE);
Nick Lewycky134af912013-02-07 05:08:22 +000063
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000064 ExprResult E = DRE;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000065 E = S.DefaultFunctionArrayConversion(E.get());
John Wiegley01296292011-04-08 18:41:53 +000066 if (E.isInvalid())
67 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +000068 return E;
John McCall7decc9e2010-11-18 06:31:45 +000069}
70
John McCall5c32be02010-08-24 20:38:10 +000071static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
72 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000073 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000074 bool CStyle,
75 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000076
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000077static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
78 QualType &ToType,
79 bool InOverloadResolution,
80 StandardConversionSequence &SCS,
81 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000082static OverloadingResult
83IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
84 UserDefinedConversionSequence& User,
85 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000086 bool AllowExplicit,
87 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000088
89
90static ImplicitConversionSequence::CompareKind
91CompareStandardConversionSequences(Sema &S,
92 const StandardConversionSequence& SCS1,
93 const StandardConversionSequence& SCS2);
94
95static ImplicitConversionSequence::CompareKind
96CompareQualificationConversions(Sema &S,
97 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
99
100static ImplicitConversionSequence::CompareKind
101CompareDerivedToBaseConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
104
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000105/// GetConversionRank - Retrieve the implicit conversion rank
106/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000107ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 static const ImplicitConversionRank
109 Rank[(int)ICK_Num_Conversion_Kinds] = {
110 ICR_Exact_Match,
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000115 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000116 ICR_Promotion,
117 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000118 ICR_Promotion,
119 ICR_Conversion,
120 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000121 ICR_Conversion,
122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000126 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000127 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000128 ICR_Conversion,
129 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000130 ICR_Complex_Real_Conversion,
131 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000132 ICR_Conversion,
133 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000134 };
135 return Rank[(int)Kind];
136}
137
138/// GetImplicitConversionName - Return the name of this kind of
139/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000140static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000141 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000142 "No conversion",
143 "Lvalue-to-rvalue",
144 "Array-to-pointer",
145 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000146 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 "Qualification",
148 "Integral promotion",
149 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000150 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151 "Integral conversion",
152 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000153 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000154 "Floating-integral conversion",
155 "Pointer conversion",
156 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000157 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000158 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000159 "Derived-to-base conversion",
160 "Vector conversion",
161 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000162 "Complex-real conversion",
163 "Block Pointer conversion",
164 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000165 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000166 };
167 return Name[Kind];
168}
169
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000170/// StandardConversionSequence - Set the standard conversion
171/// sequence to the identity conversion.
172void StandardConversionSequence::setAsIdentityConversion() {
173 First = ICK_Identity;
174 Second = ICK_Identity;
175 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000176 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000177 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000178 ReferenceBinding = false;
179 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000180 IsLvalueReference = true;
181 BindsToFunctionLvalue = false;
182 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000183 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000184 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000186}
187
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000188/// getRank - Retrieve the rank of this standard conversion sequence
189/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
190/// implicit conversions.
191ImplicitConversionRank StandardConversionSequence::getRank() const {
192 ImplicitConversionRank Rank = ICR_Exact_Match;
193 if (GetConversionRank(First) > Rank)
194 Rank = GetConversionRank(First);
195 if (GetConversionRank(Second) > Rank)
196 Rank = GetConversionRank(Second);
197 if (GetConversionRank(Third) > Rank)
198 Rank = GetConversionRank(Third);
199 return Rank;
200}
201
202/// isPointerConversionToBool - Determines whether this conversion is
203/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000204/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000206bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000207 // Note that FromType has not necessarily been transformed by the
208 // array-to-pointer or function-to-pointer implicit conversions, so
209 // check for their presence as well as checking whether FromType is
210 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000211 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000212 (getFromType()->isPointerType() ||
213 getFromType()->isObjCObjectPointerType() ||
214 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000215 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000216 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
217 return true;
218
219 return false;
220}
221
Douglas Gregor5c407d92008-10-23 00:40:37 +0000222/// isPointerConversionToVoidPointer - Determines whether this
223/// conversion is a conversion of a pointer to a void pointer. This is
224/// used as part of the ranking of standard conversion sequences (C++
225/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000226bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000227StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000228isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000229 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000230 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000231
232 // Note that FromType has not necessarily been transformed by the
233 // array-to-pointer implicit conversion, so check for its presence
234 // and redo the conversion to get a pointer.
235 if (First == ICK_Array_To_Pointer)
236 FromType = Context.getArrayDecayedType(FromType);
237
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000238 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000239 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000240 return ToPtrType->getPointeeType()->isVoidType();
241
242 return false;
243}
244
Richard Smith66e05fe2012-01-18 05:21:49 +0000245/// Skip any implicit casts which could be either part of a narrowing conversion
246/// or after one in an implicit conversion.
247static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
248 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
249 switch (ICE->getCastKind()) {
250 case CK_NoOp:
251 case CK_IntegralCast:
252 case CK_IntegralToBoolean:
253 case CK_IntegralToFloating:
254 case CK_FloatingToIntegral:
255 case CK_FloatingToBoolean:
256 case CK_FloatingCast:
257 Converted = ICE->getSubExpr();
258 continue;
259
260 default:
261 return Converted;
262 }
263 }
264
265 return Converted;
266}
267
268/// Check if this standard conversion sequence represents a narrowing
269/// conversion, according to C++11 [dcl.init.list]p7.
270///
271/// \param Ctx The AST context.
272/// \param Converted The result of applying this standard conversion sequence.
273/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
274/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000275/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
276/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000277NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000278StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
279 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000280 APValue &ConstantValue,
281 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000282 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000283
284 // C++11 [dcl.init.list]p7:
285 // A narrowing conversion is an implicit conversion ...
286 QualType FromType = getToType(0);
287 QualType ToType = getToType(1);
288 switch (Second) {
289 // -- from a floating-point type to an integer type, or
290 //
291 // -- from an integer type or unscoped enumeration type to a floating-point
292 // type, except where the source is a constant expression and the actual
293 // value after conversion will fit into the target type and will produce
294 // the original value when converted back to the original type, or
295 case ICK_Floating_Integral:
296 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
297 return NK_Type_Narrowing;
298 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
299 llvm::APSInt IntConstantValue;
300 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
301 if (Initializer &&
302 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
303 // Convert the integer to the floating type.
304 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
305 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
306 llvm::APFloat::rmNearestTiesToEven);
307 // And back.
308 llvm::APSInt ConvertedValue = IntConstantValue;
309 bool ignored;
310 Result.convertToInteger(ConvertedValue,
311 llvm::APFloat::rmTowardZero, &ignored);
312 // If the resulting value is different, this was a narrowing conversion.
313 if (IntConstantValue != ConvertedValue) {
314 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000315 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000316 return NK_Constant_Narrowing;
317 }
318 } else {
319 // Variables are always narrowings.
320 return NK_Variable_Narrowing;
321 }
322 }
323 return NK_Not_Narrowing;
324
325 // -- from long double to double or float, or from double to float, except
326 // where the source is a constant expression and the actual value after
327 // conversion is within the range of values that can be represented (even
328 // if it cannot be represented exactly), or
329 case ICK_Floating_Conversion:
330 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
331 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
332 // FromType is larger than ToType.
333 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
334 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
335 // Constant!
336 assert(ConstantValue.isFloat());
337 llvm::APFloat FloatVal = ConstantValue.getFloat();
338 // Convert the source value into the target type.
339 bool ignored;
340 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
341 Ctx.getFloatTypeSemantics(ToType),
342 llvm::APFloat::rmNearestTiesToEven, &ignored);
343 // If there was no overflow, the source value is within the range of
344 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000345 if (ConvertStatus & llvm::APFloat::opOverflow) {
346 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000347 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000348 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000349 } else {
350 return NK_Variable_Narrowing;
351 }
352 }
353 return NK_Not_Narrowing;
354
355 // -- from an integer type or unscoped enumeration type to an integer type
356 // that cannot represent all the values of the original type, except where
357 // the source is a constant expression and the actual value after
358 // conversion will fit into the target type and will produce the original
359 // value when converted back to the original type.
360 case ICK_Boolean_Conversion: // Bools are integers too.
361 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
362 // Boolean conversions can be from pointers and pointers to members
363 // [conv.bool], and those aren't considered narrowing conversions.
364 return NK_Not_Narrowing;
365 } // Otherwise, fall through to the integral case.
366 case ICK_Integral_Conversion: {
367 assert(FromType->isIntegralOrUnscopedEnumerationType());
368 assert(ToType->isIntegralOrUnscopedEnumerationType());
369 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
370 const unsigned FromWidth = Ctx.getIntWidth(FromType);
371 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
372 const unsigned ToWidth = Ctx.getIntWidth(ToType);
373
374 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000375 (FromWidth == ToWidth && FromSigned != ToSigned) ||
376 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000377 // Not all values of FromType can be represented in ToType.
378 llvm::APSInt InitializerValue;
379 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000380 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
381 // Such conversions on variables are always narrowing.
382 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000383 }
384 bool Narrowing = false;
385 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000386 // Negative -> unsigned is narrowing. Otherwise, more bits is never
387 // narrowing.
388 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000389 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000390 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000391 // Add a bit to the InitializerValue so we don't have to worry about
392 // signed vs. unsigned comparisons.
393 InitializerValue = InitializerValue.extend(
394 InitializerValue.getBitWidth() + 1);
395 // Convert the initializer to and from the target width and signed-ness.
396 llvm::APSInt ConvertedValue = InitializerValue;
397 ConvertedValue = ConvertedValue.trunc(ToWidth);
398 ConvertedValue.setIsSigned(ToSigned);
399 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
400 ConvertedValue.setIsSigned(InitializerValue.isSigned());
401 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000402 if (ConvertedValue != InitializerValue)
403 Narrowing = true;
404 }
405 if (Narrowing) {
406 ConstantType = Initializer->getType();
407 ConstantValue = APValue(InitializerValue);
408 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000409 }
410 }
411 return NK_Not_Narrowing;
412 }
413
414 default:
415 // Other kinds of conversions are not narrowings.
416 return NK_Not_Narrowing;
417 }
418}
419
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000420/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000421/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000422void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000423 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000424 bool PrintedSomething = false;
425 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000426 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000427 PrintedSomething = true;
428 }
429
430 if (Second != ICK_Identity) {
431 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000432 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000433 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000434 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000435
436 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000437 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000438 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000439 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000440 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000441 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000442 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000443 PrintedSomething = true;
444 }
445
446 if (Third != ICK_Identity) {
447 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000448 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000449 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000450 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000451 PrintedSomething = true;
452 }
453
454 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000455 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000456 }
457}
458
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000459/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000460/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000461void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000462 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000463 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000464 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000465 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000466 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000467 if (ConversionFunction)
468 OS << '\'' << *ConversionFunction << '\'';
469 else
470 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000471 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000472 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000473 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474 }
475}
476
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000477/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000478/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000479void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000480 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000481 if (isStdInitializerListElement())
482 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000483 switch (ConversionKind) {
484 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000485 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000486 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000487 break;
488 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000489 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000490 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491 break;
492 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000493 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000494 break;
John McCall0d1da222010-01-12 00:44:57 +0000495 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000496 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000497 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000499 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000500 break;
501 }
502
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000503 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504}
505
John McCall0d1da222010-01-12 00:44:57 +0000506void AmbiguousConversionSequence::construct() {
507 new (&conversions()) ConversionSet();
508}
509
510void AmbiguousConversionSequence::destruct() {
511 conversions().~ConversionSet();
512}
513
514void
515AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
516 FromTypePtr = O.FromTypePtr;
517 ToTypePtr = O.ToTypePtr;
518 new (&conversions()) ConversionSet(O.conversions());
519}
520
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000521namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000522 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000523 // template argument information.
524 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000525 TemplateArgument FirstArg;
526 TemplateArgument SecondArg;
527 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000528 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000529 // template parameter and template argument information.
530 struct DFIParamWithArguments : DFIArguments {
531 TemplateParameter Param;
532 };
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000533}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000534
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000535/// \brief Convert from Sema's representation of template deduction information
536/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000537DeductionFailureInfo
538clang::MakeDeductionFailureInfo(ASTContext &Context,
539 Sema::TemplateDeductionResult TDK,
540 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000541 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000542 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000543 Result.HasDiagnostic = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000544 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000545 switch (TDK) {
546 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000547 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000548 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000549 case Sema::TDK_TooManyArguments:
550 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000551 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000552
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000553 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000554 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000555 Result.Data = Info.Param.getOpaqueValue();
556 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000557
Richard Smith44ecdbd2013-01-31 05:19:49 +0000558 case Sema::TDK_NonDeducedMismatch: {
559 // FIXME: Should allocate from normal heap so that we can free this later.
560 DFIArguments *Saved = new (Context) DFIArguments;
561 Saved->FirstArg = Info.FirstArg;
562 Saved->SecondArg = Info.SecondArg;
563 Result.Data = Saved;
564 break;
565 }
566
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000568 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000569 // FIXME: Should allocate from normal heap so that we can free this later.
570 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000571 Saved->Param = Info.Param;
572 Saved->FirstArg = Info.FirstArg;
573 Saved->SecondArg = Info.SecondArg;
574 Result.Data = Saved;
575 break;
576 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000577
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000578 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000579 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000580 if (Info.hasSFINAEDiagnostic()) {
581 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
582 SourceLocation(), PartialDiagnostic::NullDiagnostic());
583 Info.takeSFINAEDiagnostic(*Diag);
584 Result.HasDiagnostic = true;
585 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000586 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000587
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000588 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000589 Result.Data = Info.Expression;
590 break;
591
Richard Smith44ecdbd2013-01-31 05:19:49 +0000592 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000596 return Result;
597}
John McCall0d1da222010-01-12 00:44:57 +0000598
Larisse Voufo98b20f12013-07-19 23:00:19 +0000599void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
601 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000602 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000603 case Sema::TDK_InstantiationDepth:
604 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000605 case Sema::TDK_TooManyArguments:
606 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000607 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000608 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000609 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000610
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000611 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000612 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000613 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000614 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000615 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000616 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000617
618 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000619 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000620 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000621 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
622 Diag->~PartialDiagnosticAt();
623 HasDiagnostic = false;
624 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000625 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626
Douglas Gregor461761d2010-05-08 18:20:53 +0000627 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000628 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000629 break;
630 }
631}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000632
Larisse Voufo98b20f12013-07-19 23:00:19 +0000633PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000634 if (HasDiagnostic)
635 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000636 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000637}
638
Larisse Voufo98b20f12013-07-19 23:00:19 +0000639TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000640 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
641 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000642 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000643 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000644 case Sema::TDK_TooManyArguments:
645 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000646 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000647 case Sema::TDK_NonDeducedMismatch:
648 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000649 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000650
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000651 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000652 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000653 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000654
655 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000656 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000657 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000659 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000660 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000661 break;
662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000663
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000664 return TemplateParameter();
665}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000666
Larisse Voufo98b20f12013-07-19 23:00:19 +0000667TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000668 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000669 case Sema::TDK_Success:
670 case Sema::TDK_Invalid:
671 case Sema::TDK_InstantiationDepth:
672 case Sema::TDK_TooManyArguments:
673 case Sema::TDK_TooFewArguments:
674 case Sema::TDK_Incomplete:
675 case Sema::TDK_InvalidExplicitArguments:
676 case Sema::TDK_Inconsistent:
677 case Sema::TDK_Underqualified:
678 case Sema::TDK_NonDeducedMismatch:
679 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000680 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000681
Richard Smith44ecdbd2013-01-31 05:19:49 +0000682 case Sema::TDK_SubstitutionFailure:
683 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000684
Richard Smith44ecdbd2013-01-31 05:19:49 +0000685 // Unhandled
686 case Sema::TDK_MiscellaneousDeductionFailure:
687 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000688 }
689
Craig Topperc3ec1492014-05-26 06:22:03 +0000690 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000691}
692
Larisse Voufo98b20f12013-07-19 23:00:19 +0000693const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000694 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
695 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000696 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000697 case Sema::TDK_InstantiationDepth:
698 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000699 case Sema::TDK_TooManyArguments:
700 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000701 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000702 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000703 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000704 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000705
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000706 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000707 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000708 case Sema::TDK_NonDeducedMismatch:
709 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000710
Douglas Gregor461761d2010-05-08 18:20:53 +0000711 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000712 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000713 break;
714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000715
Craig Topperc3ec1492014-05-26 06:22:03 +0000716 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000717}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000718
Larisse Voufo98b20f12013-07-19 23:00:19 +0000719const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000720 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
721 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000722 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000723 case Sema::TDK_InstantiationDepth:
724 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000725 case Sema::TDK_TooManyArguments:
726 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000727 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000728 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000729 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000730 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000731
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000732 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000733 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000734 case Sema::TDK_NonDeducedMismatch:
735 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000736
Douglas Gregor461761d2010-05-08 18:20:53 +0000737 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000738 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000739 break;
740 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000741
Craig Topperc3ec1492014-05-26 06:22:03 +0000742 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000743}
744
Larisse Voufo98b20f12013-07-19 23:00:19 +0000745Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000746 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
747 Sema::TDK_FailedOverloadResolution)
748 return static_cast<Expr*>(Data);
749
Craig Topperc3ec1492014-05-26 06:22:03 +0000750 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000751}
752
Benjamin Kramer97e59492012-10-09 15:52:25 +0000753void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000754 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000755 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
756 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000757 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
758 i->DeductionFailure.Destroy();
759 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000760}
761
762void OverloadCandidateSet::clear() {
763 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000764 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000765 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000766 Functions.clear();
767}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000768
John McCall4124c492011-10-17 18:40:02 +0000769namespace {
770 class UnbridgedCastsSet {
771 struct Entry {
772 Expr **Addr;
773 Expr *Saved;
774 };
775 SmallVector<Entry, 2> Entries;
776
777 public:
778 void save(Sema &S, Expr *&E) {
779 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
780 Entry entry = { &E, E };
781 Entries.push_back(entry);
782 E = S.stripARCUnbridgedCast(E);
783 }
784
785 void restore() {
786 for (SmallVectorImpl<Entry>::iterator
787 i = Entries.begin(), e = Entries.end(); i != e; ++i)
788 *i->Addr = i->Saved;
789 }
790 };
791}
792
793/// checkPlaceholderForOverload - Do any interesting placeholder-like
794/// preprocessing on the given expression.
795///
796/// \param unbridgedCasts a collection to which to add unbridged casts;
797/// without this, they will be immediately diagnosed as errors
798///
799/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000800static bool
801checkPlaceholderForOverload(Sema &S, Expr *&E,
802 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000803 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
804 // We can't handle overloaded expressions here because overload
805 // resolution might reasonably tweak them.
806 if (placeholder->getKind() == BuiltinType::Overload) return false;
807
808 // If the context potentially accepts unbridged ARC casts, strip
809 // the unbridged cast and add it to the collection for later restoration.
810 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
811 unbridgedCasts) {
812 unbridgedCasts->save(S, E);
813 return false;
814 }
815
816 // Go ahead and check everything else.
817 ExprResult result = S.CheckPlaceholderExpr(E);
818 if (result.isInvalid())
819 return true;
820
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000821 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000822 return false;
823 }
824
825 // Nothing to do.
826 return false;
827}
828
829/// checkArgPlaceholdersForOverload - Check a set of call operands for
830/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000831static bool checkArgPlaceholdersForOverload(Sema &S,
832 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000833 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000834 for (unsigned i = 0, e = Args.size(); i != e; ++i)
835 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000836 return true;
837
838 return false;
839}
840
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000841// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000842// overload of the declarations in Old. This routine returns false if
843// New and Old cannot be overloaded, e.g., if New has the same
844// signature as some function in Old (C++ 1.3.10) or if the Old
845// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000846// it does return false, MatchedDecl will point to the decl that New
847// cannot be overloaded with. This decl may be a UsingShadowDecl on
848// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000849//
850// Example: Given the following input:
851//
852// void f(int, float); // #1
853// void f(int, int); // #2
854// int f(int, int); // #3
855//
856// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000857// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000858//
John McCall3d988d92009-12-02 08:47:38 +0000859// When we process #2, Old contains only the FunctionDecl for #1. By
860// comparing the parameter types, we see that #1 and #2 are overloaded
861// (since they have different signatures), so this routine returns
862// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000863//
John McCall3d988d92009-12-02 08:47:38 +0000864// When we process #3, Old is an overload set containing #1 and #2. We
865// compare the signatures of #3 to #1 (they're overloaded, so we do
866// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
867// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000868// signature), IsOverload returns false and MatchedDecl will be set to
869// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000870//
871// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
872// into a class by a using declaration. The rules for whether to hide
873// shadow declarations ignore some properties which otherwise figure
874// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000875Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000876Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
877 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000878 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000879 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000880 NamedDecl *OldD = *I;
881
882 bool OldIsUsingDecl = false;
883 if (isa<UsingShadowDecl>(OldD)) {
884 OldIsUsingDecl = true;
885
886 // We can always introduce two using declarations into the same
887 // context, even if they have identical signatures.
888 if (NewIsUsingDecl) continue;
889
890 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
891 }
892
893 // If either declaration was introduced by a using declaration,
894 // we'll need to use slightly different rules for matching.
895 // Essentially, these rules are the normal rules, except that
896 // function templates hide function templates with different
897 // return types or template parameter lists.
898 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000899 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
900 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000901
Alp Tokera2794f92014-01-22 07:29:52 +0000902 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000903 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
904 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
905 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
906 continue;
907 }
908
Alp Tokera2794f92014-01-22 07:29:52 +0000909 if (!isa<FunctionTemplateDecl>(OldD) &&
910 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000911 continue;
912
John McCalldaa3d6b2009-12-09 03:35:25 +0000913 Match = *I;
914 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000915 }
John McCalla8987a2942010-11-10 03:01:53 +0000916 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000917 // We can overload with these, which can show up when doing
918 // redeclaration checks for UsingDecls.
919 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000920 } else if (isa<TagDecl>(OldD)) {
921 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000922 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
923 // Optimistically assume that an unresolved using decl will
924 // overload; if it doesn't, we'll have to diagnose during
925 // template instantiation.
926 } else {
John McCall1f82f242009-11-18 22:49:29 +0000927 // (C++ 13p1):
928 // Only function declarations can be overloaded; object and type
929 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000930 Match = *I;
931 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000932 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000933 }
John McCall1f82f242009-11-18 22:49:29 +0000934
John McCalldaa3d6b2009-12-09 03:35:25 +0000935 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000936}
937
Richard Smithac974a32013-06-30 09:48:50 +0000938bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
939 bool UseUsingDeclRules) {
940 // C++ [basic.start.main]p2: This function shall not be overloaded.
941 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000942 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000943
David Majnemerc729b0b2013-09-16 22:44:20 +0000944 // MSVCRT user defined entry points cannot be overloaded.
945 if (New->isMSVCRTEntryPoint())
946 return false;
947
John McCall1f82f242009-11-18 22:49:29 +0000948 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
949 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
950
951 // C++ [temp.fct]p2:
952 // A function template can be overloaded with other function templates
953 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +0000954 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +0000955 return true;
956
957 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000958 QualType OldQType = Context.getCanonicalType(Old->getType());
959 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +0000960
961 // Compare the signatures (C++ 1.3.10) of the two functions to
962 // determine whether they are overloads. If we find any mismatch
963 // in the signature, they are overloads.
964
965 // If either of these functions is a K&R-style function (no
966 // prototype), then we consider them to have matching signatures.
967 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
968 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
969 return false;
970
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000971 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
972 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000973
974 // The signature of a function includes the types of its
975 // parameters (C++ 1.3.10), which includes the presence or absence
976 // of the ellipsis; see C++ DR 357).
977 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +0000978 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +0000979 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +0000980 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000981 return true;
982
983 // C++ [temp.over.link]p4:
984 // The signature of a function template consists of its function
985 // signature, its return type and its template parameter list. The names
986 // of the template parameters are significant only for establishing the
987 // relationship between the template parameters and the rest of the
988 // signature.
989 //
990 // We check the return type and template parameter lists for function
991 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000992 //
993 // However, we don't consider either of these when deciding whether
994 // a member introduced by a shadow declaration is hidden.
995 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +0000996 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
997 OldTemplate->getTemplateParameters(),
998 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +0000999 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001000 return true;
1001
1002 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001003 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001004 //
1005 // As part of this, also check whether one of the member functions
1006 // is static, in which case they are not overloads (C++
1007 // 13.1p2). While not part of the definition of the signature,
1008 // this check is important to determine whether these functions
1009 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001010 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1011 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001012 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001013 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1014 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1015 if (!UseUsingDeclRules &&
1016 (OldMethod->getRefQualifier() == RQ_None ||
1017 NewMethod->getRefQualifier() == RQ_None)) {
1018 // C++0x [over.load]p2:
1019 // - Member function declarations with the same name and the same
1020 // parameter-type-list as well as member function template
1021 // declarations with the same name, the same parameter-type-list, and
1022 // the same template parameter lists cannot be overloaded if any of
1023 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001024 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001025 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001026 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001027 }
1028 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001029 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001030
Richard Smith574f4f62013-01-14 05:37:29 +00001031 // We may not have applied the implicit const for a constexpr member
1032 // function yet (because we haven't yet resolved whether this is a static
1033 // or non-static member function). Add it now, on the assumption that this
1034 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001035 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001036 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001037 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001038 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001039 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001040
1041 // We do not allow overloading based off of '__restrict'.
1042 OldQuals &= ~Qualifiers::Restrict;
1043 NewQuals &= ~Qualifiers::Restrict;
1044 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001045 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001046 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001047
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001048 // enable_if attributes are an order-sensitive part of the signature.
1049 for (specific_attr_iterator<EnableIfAttr>
1050 NewI = New->specific_attr_begin<EnableIfAttr>(),
1051 NewE = New->specific_attr_end<EnableIfAttr>(),
1052 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1053 OldE = Old->specific_attr_end<EnableIfAttr>();
1054 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1055 if (NewI == NewE || OldI == OldE)
1056 return true;
1057 llvm::FoldingSetNodeID NewID, OldID;
1058 NewI->getCond()->Profile(NewID, Context, true);
1059 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001060 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001061 return true;
1062 }
1063
John McCall1f82f242009-11-18 22:49:29 +00001064 // The signatures match; this is not an overload.
1065 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001066}
1067
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001068/// \brief Checks availability of the function depending on the current
1069/// function context. Inside an unavailable function, unavailability is ignored.
1070///
1071/// \returns true if \arg FD is unavailable and current context is inside
1072/// an available function, false otherwise.
1073bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1074 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1075}
1076
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001077/// \brief Tries a user-defined conversion from From to ToType.
1078///
1079/// Produces an implicit conversion sequence for when a standard conversion
1080/// is not an option. See TryImplicitConversion for more information.
1081static ImplicitConversionSequence
1082TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1083 bool SuppressUserConversions,
1084 bool AllowExplicit,
1085 bool InOverloadResolution,
1086 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001087 bool AllowObjCWritebackConversion,
1088 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001089 ImplicitConversionSequence ICS;
1090
1091 if (SuppressUserConversions) {
1092 // We're not in the case above, so there is no conversion that
1093 // we can perform.
1094 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1095 return ICS;
1096 }
1097
1098 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001099 OverloadCandidateSet Conversions(From->getExprLoc(),
1100 OverloadCandidateSet::CSK_Normal);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001101 OverloadingResult UserDefResult
1102 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001103 AllowExplicit, AllowObjCConversionOnExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001104
1105 if (UserDefResult == OR_Success) {
1106 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001107 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001108 // C++ [over.ics.user]p4:
1109 // A conversion of an expression of class type to the same class
1110 // type is given Exact Match rank, and a conversion of an
1111 // expression of class type to a base class of that type is
1112 // given Conversion rank, in spite of the fact that a copy
1113 // constructor (i.e., a user-defined conversion function) is
1114 // called for those cases.
1115 if (CXXConstructorDecl *Constructor
1116 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1117 QualType FromCanon
1118 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1119 QualType ToCanon
1120 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1121 if (Constructor->isCopyConstructor() &&
1122 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1123 // Turn this into a "standard" conversion sequence, so that it
1124 // gets ranked with standard conversion sequences.
1125 ICS.setStandard();
1126 ICS.Standard.setAsIdentityConversion();
1127 ICS.Standard.setFromType(From->getType());
1128 ICS.Standard.setAllToTypes(ToType);
1129 ICS.Standard.CopyConstructor = Constructor;
1130 if (ToCanon != FromCanon)
1131 ICS.Standard.Second = ICK_Derived_To_Base;
1132 }
1133 }
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001134 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1135 ICS.setAmbiguous();
1136 ICS.Ambiguous.setFromType(From->getType());
1137 ICS.Ambiguous.setToType(ToType);
1138 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1139 Cand != Conversions.end(); ++Cand)
1140 if (Cand->Viable)
1141 ICS.Ambiguous.addConversion(Cand->Function);
1142 } else {
1143 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1144 }
1145
1146 return ICS;
1147}
1148
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001149/// TryImplicitConversion - Attempt to perform an implicit conversion
1150/// from the given expression (Expr) to the given type (ToType). This
1151/// function returns an implicit conversion sequence that can be used
1152/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001153///
1154/// void f(float f);
1155/// void g(int i) { f(i); }
1156///
1157/// this routine would produce an implicit conversion sequence to
1158/// describe the initialization of f from i, which will be a standard
1159/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1160/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1161//
1162/// Note that this routine only determines how the conversion can be
1163/// performed; it does not actually perform the conversion. As such,
1164/// it will not produce any diagnostics if no conversion is available,
1165/// but will instead return an implicit conversion sequence of kind
1166/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001167///
1168/// If @p SuppressUserConversions, then user-defined conversions are
1169/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001170/// If @p AllowExplicit, then explicit user-defined conversions are
1171/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001172///
1173/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1174/// writeback conversion, which allows __autoreleasing id* parameters to
1175/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001176static ImplicitConversionSequence
1177TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1178 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001179 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001180 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001181 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001182 bool AllowObjCWritebackConversion,
1183 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001184 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001185 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001186 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001187 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001188 return ICS;
1189 }
1190
David Blaikiebbafb8a2012-03-11 07:00:24 +00001191 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001192 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001193 return ICS;
1194 }
1195
Douglas Gregor836a7e82010-08-11 02:15:33 +00001196 // C++ [over.ics.user]p4:
1197 // A conversion of an expression of class type to the same class
1198 // type is given Exact Match rank, and a conversion of an
1199 // expression of class type to a base class of that type is
1200 // given Conversion rank, in spite of the fact that a copy/move
1201 // constructor (i.e., a user-defined conversion function) is
1202 // called for those cases.
1203 QualType FromType = From->getType();
1204 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001205 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1206 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001207 ICS.setStandard();
1208 ICS.Standard.setAsIdentityConversion();
1209 ICS.Standard.setFromType(FromType);
1210 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001211
Douglas Gregor5ab11652010-04-17 22:01:05 +00001212 // We don't actually check at this point whether there is a valid
1213 // copy/move constructor, since overloading just assumes that it
1214 // exists. When we actually perform initialization, we'll find the
1215 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001216 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001217
Douglas Gregor5ab11652010-04-17 22:01:05 +00001218 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001219 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001220 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001221
Douglas Gregor836a7e82010-08-11 02:15:33 +00001222 return ICS;
1223 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001224
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001225 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1226 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001227 AllowObjCWritebackConversion,
1228 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001229}
1230
John McCall31168b02011-06-15 23:02:42 +00001231ImplicitConversionSequence
1232Sema::TryImplicitConversion(Expr *From, QualType ToType,
1233 bool SuppressUserConversions,
1234 bool AllowExplicit,
1235 bool InOverloadResolution,
1236 bool CStyle,
1237 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001238 return ::TryImplicitConversion(*this, From, ToType,
1239 SuppressUserConversions, AllowExplicit,
1240 InOverloadResolution, CStyle,
1241 AllowObjCWritebackConversion,
1242 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001243}
1244
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001245/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001246/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001247/// converted expression. Flavor is the kind of conversion we're
1248/// performing, used in the error message. If @p AllowExplicit,
1249/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001250ExprResult
1251Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001252 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001253 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001254 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001255}
1256
John Wiegley01296292011-04-08 18:41:53 +00001257ExprResult
1258Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001259 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001260 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001261 if (checkPlaceholderForOverload(*this, From))
1262 return ExprError();
1263
John McCall31168b02011-06-15 23:02:42 +00001264 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1265 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001266 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001267 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001268 if (getLangOpts().ObjC1)
1269 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1270 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001271 ICS = ::TryImplicitConversion(*this, From, ToType,
1272 /*SuppressUserConversions=*/false,
1273 AllowExplicit,
1274 /*InOverloadResolution=*/false,
1275 /*CStyle=*/false,
1276 AllowObjCWritebackConversion,
1277 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001278 return PerformImplicitConversion(From, ToType, ICS, Action);
1279}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001280
1281/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001282/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001283bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1284 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001285 if (Context.hasSameUnqualifiedType(FromType, ToType))
1286 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001287
John McCall991eb4b2010-12-21 00:44:39 +00001288 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1289 // where F adds one of the following at most once:
1290 // - a pointer
1291 // - a member pointer
1292 // - a block pointer
1293 CanQualType CanTo = Context.getCanonicalType(ToType);
1294 CanQualType CanFrom = Context.getCanonicalType(FromType);
1295 Type::TypeClass TyClass = CanTo->getTypeClass();
1296 if (TyClass != CanFrom->getTypeClass()) return false;
1297 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1298 if (TyClass == Type::Pointer) {
1299 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1300 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1301 } else if (TyClass == Type::BlockPointer) {
1302 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1303 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1304 } else if (TyClass == Type::MemberPointer) {
1305 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1306 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1307 } else {
1308 return false;
1309 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001310
John McCall991eb4b2010-12-21 00:44:39 +00001311 TyClass = CanTo->getTypeClass();
1312 if (TyClass != CanFrom->getTypeClass()) return false;
1313 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1314 return false;
1315 }
1316
1317 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1318 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1319 if (!EInfo.getNoReturn()) return false;
1320
1321 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1322 assert(QualType(FromFn, 0).isCanonical());
1323 if (QualType(FromFn, 0) != CanTo) return false;
1324
1325 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001326 return true;
1327}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001328
Douglas Gregor46188682010-05-18 22:42:18 +00001329/// \brief Determine whether the conversion from FromType to ToType is a valid
1330/// vector conversion.
1331///
1332/// \param ICK Will be set to the vector conversion kind, if this is a vector
1333/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001334static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001335 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001336 // We need at least one of these types to be a vector type to have a vector
1337 // conversion.
1338 if (!ToType->isVectorType() && !FromType->isVectorType())
1339 return false;
1340
1341 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001342 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001343 return false;
1344
1345 // There are no conversions between extended vector types, only identity.
1346 if (ToType->isExtVectorType()) {
1347 // There are no conversions between extended vector types other than the
1348 // identity conversion.
1349 if (FromType->isExtVectorType())
1350 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001351
Douglas Gregor46188682010-05-18 22:42:18 +00001352 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001353 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001354 ICK = ICK_Vector_Splat;
1355 return true;
1356 }
1357 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001358
1359 // We can perform the conversion between vector types in the following cases:
1360 // 1)vector types are equivalent AltiVec and GCC vector types
1361 // 2)lax vector conversions are permitted and the vector types are of the
1362 // same size
1363 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001364 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1365 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001366 ICK = ICK_Vector_Conversion;
1367 return true;
1368 }
Douglas Gregor46188682010-05-18 22:42:18 +00001369 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001370
Douglas Gregor46188682010-05-18 22:42:18 +00001371 return false;
1372}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001373
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001374static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1375 bool InOverloadResolution,
1376 StandardConversionSequence &SCS,
1377 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001378
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001379/// IsStandardConversion - Determines whether there is a standard
1380/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1381/// expression From to the type ToType. Standard conversion sequences
1382/// only consider non-class types; for conversions that involve class
1383/// types, use TryImplicitConversion. If a conversion exists, SCS will
1384/// contain the standard conversion sequence required to perform this
1385/// conversion and this routine will return true. Otherwise, this
1386/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001387static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1388 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001389 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001390 bool CStyle,
1391 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001392 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001393
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001394 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001395 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001396 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001397 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001398 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001399
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001400 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001401 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001402 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001403 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001404 return false;
1405
Mike Stump11289f42009-09-09 15:08:12 +00001406 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001407 }
1408
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001409 // The first conversion can be an lvalue-to-rvalue conversion,
1410 // array-to-pointer conversion, or function-to-pointer conversion
1411 // (C++ 4p1).
1412
John McCall5c32be02010-08-24 20:38:10 +00001413 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001414 DeclAccessPair AccessPair;
1415 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001416 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001417 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001418 // We were able to resolve the address of the overloaded function,
1419 // so we can convert to the type of that function.
1420 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001421 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001422
1423 // we can sometimes resolve &foo<int> regardless of ToType, so check
1424 // if the type matches (identity) or we are converting to bool
1425 if (!S.Context.hasSameUnqualifiedType(
1426 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1427 QualType resultTy;
1428 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001429 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001430 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1431 // otherwise, only a boolean conversion is standard
1432 if (!ToType->isBooleanType())
1433 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001434 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001435
Chandler Carruthffce2452011-03-29 08:08:18 +00001436 // Check if the "from" expression is taking the address of an overloaded
1437 // function and recompute the FromType accordingly. Take advantage of the
1438 // fact that non-static member functions *must* have such an address-of
1439 // expression.
1440 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1441 if (Method && !Method->isStatic()) {
1442 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1443 "Non-unary operator on non-static member address");
1444 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1445 == UO_AddrOf &&
1446 "Non-address-of operator on non-static member address");
1447 const Type *ClassType
1448 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1449 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001450 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1451 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1452 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001453 "Non-address-of operator for overloaded function expression");
1454 FromType = S.Context.getPointerType(FromType);
1455 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001456
Douglas Gregor980fb162010-04-29 18:24:40 +00001457 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001458 assert(S.Context.hasSameType(
1459 FromType,
1460 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001461 } else {
1462 return false;
1463 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001464 }
John McCall154a2fd2011-08-30 00:57:29 +00001465 // Lvalue-to-rvalue conversion (C++11 4.1):
1466 // A glvalue (3.10) of a non-function, non-array type T can
1467 // be converted to a prvalue.
1468 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001469 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001470 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001471 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001472 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001473
Douglas Gregorc79862f2012-04-12 17:51:55 +00001474 // C11 6.3.2.1p2:
1475 // ... if the lvalue has atomic type, the value has the non-atomic version
1476 // of the type of the lvalue ...
1477 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1478 FromType = Atomic->getValueType();
1479
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001480 // If T is a non-class type, the type of the rvalue is the
1481 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001482 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1483 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001484 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001485 } else if (FromType->isArrayType()) {
1486 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001487 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001488
1489 // An lvalue or rvalue of type "array of N T" or "array of unknown
1490 // bound of T" can be converted to an rvalue of type "pointer to
1491 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001492 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001493
John McCall5c32be02010-08-24 20:38:10 +00001494 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001495 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001496 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001497
1498 // For the purpose of ranking in overload resolution
1499 // (13.3.3.1.1), this conversion is considered an
1500 // array-to-pointer conversion followed by a qualification
1501 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001502 SCS.Second = ICK_Identity;
1503 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001504 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001505 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001506 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001507 }
John McCall086a4642010-11-24 05:12:34 +00001508 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001509 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001510 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001511
1512 // An lvalue of function type T can be converted to an rvalue of
1513 // type "pointer to T." The result is a pointer to the
1514 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001515 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001516 } else {
1517 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001518 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001519 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001520 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001521
1522 // The second conversion can be an integral promotion, floating
1523 // point promotion, integral conversion, floating point conversion,
1524 // floating-integral conversion, pointer conversion,
1525 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001526 // For overloading in C, this can also be a "compatible-type"
1527 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001528 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001529 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001530 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001531 // The unqualified versions of the types are the same: there's no
1532 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001533 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001534 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001535 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001536 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001537 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001538 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001539 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001540 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001541 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001542 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001543 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001544 SCS.Second = ICK_Complex_Promotion;
1545 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001546 } else if (ToType->isBooleanType() &&
1547 (FromType->isArithmeticType() ||
1548 FromType->isAnyPointerType() ||
1549 FromType->isBlockPointerType() ||
1550 FromType->isMemberPointerType() ||
1551 FromType->isNullPtrType())) {
1552 // Boolean conversions (C++ 4.12).
1553 SCS.Second = ICK_Boolean_Conversion;
1554 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001555 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001556 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001557 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001558 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001559 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001560 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001561 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001562 SCS.Second = ICK_Complex_Conversion;
1563 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001564 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1565 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001566 // Complex-real conversions (C99 6.3.1.7)
1567 SCS.Second = ICK_Complex_Real;
1568 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001569 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001570 // Floating point conversions (C++ 4.8).
1571 SCS.Second = ICK_Floating_Conversion;
1572 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001573 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001574 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001575 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001576 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001577 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001578 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001579 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001580 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001581 SCS.Second = ICK_Block_Pointer_Conversion;
1582 } else if (AllowObjCWritebackConversion &&
1583 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1584 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001585 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1586 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001587 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001588 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001589 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001590 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001591 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001592 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001593 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001594 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001595 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001596 SCS.Second = SecondICK;
1597 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001598 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001599 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001600 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001601 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001602 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001603 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001604 // Treat a conversion that strips "noreturn" as an identity conversion.
1605 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001606 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1607 InOverloadResolution,
1608 SCS, CStyle)) {
1609 SCS.Second = ICK_TransparentUnionConversion;
1610 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001611 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1612 CStyle)) {
1613 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001614 // appropriately.
1615 return true;
Guy Benyei259f9f42013-02-07 16:05:33 +00001616 } else if (ToType->isEventT() &&
1617 From->isIntegerConstantExpr(S.getASTContext()) &&
1618 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1619 SCS.Second = ICK_Zero_Event_Conversion;
1620 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001621 } else {
1622 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001623 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001624 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001625 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001626
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001627 QualType CanonFrom;
1628 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001629 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001630 bool ObjCLifetimeConversion;
1631 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1632 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001633 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001634 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001635 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001636 CanonFrom = S.Context.getCanonicalType(FromType);
1637 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001638 } else {
1639 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001640 SCS.Third = ICK_Identity;
1641
Mike Stump11289f42009-09-09 15:08:12 +00001642 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001643 // [...] Any difference in top-level cv-qualification is
1644 // subsumed by the initialization itself and does not constitute
1645 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001646 CanonFrom = S.Context.getCanonicalType(FromType);
1647 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001648 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001649 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001650 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001651 FromType = ToType;
1652 CanonFrom = CanonTo;
1653 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001654 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001655 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001656
1657 // If we have not converted the argument type to the parameter type,
1658 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001659 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001660 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001661
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001662 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001663}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001664
1665static bool
1666IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1667 QualType &ToType,
1668 bool InOverloadResolution,
1669 StandardConversionSequence &SCS,
1670 bool CStyle) {
1671
1672 const RecordType *UT = ToType->getAsUnionType();
1673 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1674 return false;
1675 // The field to initialize within the transparent union.
1676 RecordDecl *UD = UT->getDecl();
1677 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001678 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001679 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1680 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001681 ToType = it->getType();
1682 return true;
1683 }
1684 }
1685 return false;
1686}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001687
1688/// IsIntegralPromotion - Determines whether the conversion from the
1689/// expression From (whose potentially-adjusted type is FromType) to
1690/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1691/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001692bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001693 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001694 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001695 if (!To) {
1696 return false;
1697 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001698
1699 // An rvalue of type char, signed char, unsigned char, short int, or
1700 // unsigned short int can be converted to an rvalue of type int if
1701 // int can represent all the values of the source type; otherwise,
1702 // the source rvalue can be converted to an rvalue of type unsigned
1703 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001704 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1705 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001706 if (// We can promote any signed, promotable integer type to an int
1707 (FromType->isSignedIntegerType() ||
1708 // We can promote any unsigned integer type whose size is
1709 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001710 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001711 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001712 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001713 }
1714
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001715 return To->getKind() == BuiltinType::UInt;
1716 }
1717
Richard Smithb9c5a602012-09-13 21:18:54 +00001718 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001719 // A prvalue of an unscoped enumeration type whose underlying type is not
1720 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1721 // following types that can represent all the values of the enumeration
1722 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1723 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001724 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001725 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001726 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727 // with lowest integer conversion rank (4.13) greater than the rank of long
1728 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001729 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001730 // C++11 [conv.prom]p4:
1731 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1732 // can be converted to a prvalue of its underlying type. Moreover, if
1733 // integral promotion can be applied to its underlying type, a prvalue of an
1734 // unscoped enumeration type whose underlying type is fixed can also be
1735 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001736 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1737 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1738 // provided for a scoped enumeration.
1739 if (FromEnumType->getDecl()->isScoped())
1740 return false;
1741
Richard Smithb9c5a602012-09-13 21:18:54 +00001742 // We can perform an integral promotion to the underlying type of the enum,
1743 // even if that's not the promoted type.
1744 if (FromEnumType->getDecl()->isFixed()) {
1745 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1746 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1747 IsIntegralPromotion(From, Underlying, ToType);
1748 }
1749
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001750 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001751 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001752 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001753 return Context.hasSameUnqualifiedType(ToType,
1754 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001755 }
John McCall56774992009-12-09 09:09:27 +00001756
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001757 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001758 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1759 // to an rvalue a prvalue of the first of the following types that can
1760 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001761 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001762 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001763 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001764 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001765 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001766 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001767 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001768 // Determine whether the type we're converting from is signed or
1769 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001770 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001771 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001772
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001773 // The types we'll try to promote to, in the appropriate
1774 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001775 QualType PromoteTypes[6] = {
1776 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001777 Context.LongTy, Context.UnsignedLongTy ,
1778 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001779 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001780 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001781 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1782 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001783 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001784 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1785 // We found the type that we can promote to. If this is the
1786 // type we wanted, we have a promotion. Otherwise, no
1787 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001788 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001789 }
1790 }
1791 }
1792
1793 // An rvalue for an integral bit-field (9.6) can be converted to an
1794 // rvalue of type int if int can represent all the values of the
1795 // bit-field; otherwise, it can be converted to unsigned int if
1796 // unsigned int can represent all the values of the bit-field. If
1797 // the bit-field is larger yet, no integral promotion applies to
1798 // it. If the bit-field has an enumerated type, it is treated as any
1799 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001800 // FIXME: We should delay checking of bit-fields until we actually perform the
1801 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001802 using llvm::APSInt;
1803 if (From)
John McCalld25db7e2013-05-06 21:39:12 +00001804 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001805 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001806 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001807 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1808 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1809 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001810
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001811 // Are we promoting to an int from a bitfield that fits in an int?
1812 if (BitWidth < ToSize ||
1813 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1814 return To->getKind() == BuiltinType::Int;
1815 }
Mike Stump11289f42009-09-09 15:08:12 +00001816
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001817 // Are we promoting to an unsigned int from an unsigned bitfield
1818 // that fits into an unsigned int?
1819 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1820 return To->getKind() == BuiltinType::UInt;
1821 }
Mike Stump11289f42009-09-09 15:08:12 +00001822
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001823 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001824 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001825 }
Mike Stump11289f42009-09-09 15:08:12 +00001826
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001827 // An rvalue of type bool can be converted to an rvalue of type int,
1828 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001829 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001830 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001831 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001832
1833 return false;
1834}
1835
1836/// IsFloatingPointPromotion - Determines whether the conversion from
1837/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1838/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001839bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001840 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1841 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001842 /// An rvalue of type float can be converted to an rvalue of type
1843 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001844 if (FromBuiltin->getKind() == BuiltinType::Float &&
1845 ToBuiltin->getKind() == BuiltinType::Double)
1846 return true;
1847
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001848 // C99 6.3.1.5p1:
1849 // When a float is promoted to double or long double, or a
1850 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001851 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001852 (FromBuiltin->getKind() == BuiltinType::Float ||
1853 FromBuiltin->getKind() == BuiltinType::Double) &&
1854 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1855 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001856
1857 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001858 if (!getLangOpts().NativeHalfType &&
1859 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001860 ToBuiltin->getKind() == BuiltinType::Float)
1861 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001862 }
1863
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001864 return false;
1865}
1866
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001867/// \brief Determine if a conversion is a complex promotion.
1868///
1869/// A complex promotion is defined as a complex -> complex conversion
1870/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001871/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001872bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001873 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001874 if (!FromComplex)
1875 return false;
1876
John McCall9dd450b2009-09-21 23:43:11 +00001877 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001878 if (!ToComplex)
1879 return false;
1880
1881 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001882 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001883 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001884 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001885}
1886
Douglas Gregor237f96c2008-11-26 23:31:11 +00001887/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1888/// the pointer type FromPtr to a pointer to type ToPointee, with the
1889/// same type qualifiers as FromPtr has on its pointee type. ToType,
1890/// if non-empty, will be a pointer to ToType that may or may not have
1891/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001892///
Mike Stump11289f42009-09-09 15:08:12 +00001893static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001894BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001895 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001896 ASTContext &Context,
1897 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001898 assert((FromPtr->getTypeClass() == Type::Pointer ||
1899 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1900 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001901
John McCall31168b02011-06-15 23:02:42 +00001902 /// Conversions to 'id' subsume cv-qualifier conversions.
1903 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001904 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001905
1906 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001907 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001908 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001909 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001910
John McCall31168b02011-06-15 23:02:42 +00001911 if (StripObjCLifetime)
1912 Quals.removeObjCLifetime();
1913
Mike Stump11289f42009-09-09 15:08:12 +00001914 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001915 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001916 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001917 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001918 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001919
1920 // Build a pointer to ToPointee. It has the right qualifiers
1921 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001922 if (isa<ObjCObjectPointerType>(ToType))
1923 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001924 return Context.getPointerType(ToPointee);
1925 }
1926
1927 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001928 QualType QualifiedCanonToPointee
1929 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001930
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001931 if (isa<ObjCObjectPointerType>(ToType))
1932 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1933 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001934}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001935
Mike Stump11289f42009-09-09 15:08:12 +00001936static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001937 bool InOverloadResolution,
1938 ASTContext &Context) {
1939 // Handle value-dependent integral null pointer constants correctly.
1940 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1941 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001942 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001943 return !InOverloadResolution;
1944
Douglas Gregor56751b52009-09-25 04:25:58 +00001945 return Expr->isNullPointerConstant(Context,
1946 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1947 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001948}
Mike Stump11289f42009-09-09 15:08:12 +00001949
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001950/// IsPointerConversion - Determines whether the conversion of the
1951/// expression From, which has the (possibly adjusted) type FromType,
1952/// can be converted to the type ToType via a pointer conversion (C++
1953/// 4.10). If so, returns true and places the converted type (that
1954/// might differ from ToType in its cv-qualifiers at some level) into
1955/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001956///
Douglas Gregora29dc052008-11-27 01:19:21 +00001957/// This routine also supports conversions to and from block pointers
1958/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1959/// pointers to interfaces. FIXME: Once we've determined the
1960/// appropriate overloading rules for Objective-C, we may want to
1961/// split the Objective-C checks into a different routine; however,
1962/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001963/// conversions, so for now they live here. IncompatibleObjC will be
1964/// set if the conversion is an allowed Objective-C conversion that
1965/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001966bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001967 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001968 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001969 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001970 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001971 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1972 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001973 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001974
Mike Stump11289f42009-09-09 15:08:12 +00001975 // Conversion from a null pointer constant to any Objective-C pointer type.
1976 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001977 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001978 ConvertedType = ToType;
1979 return true;
1980 }
1981
Douglas Gregor231d1c62008-11-27 00:15:41 +00001982 // Blocks: Block pointers can be converted to void*.
1983 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001984 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001985 ConvertedType = ToType;
1986 return true;
1987 }
1988 // Blocks: A null pointer constant can be converted to a block
1989 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001990 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001991 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001992 ConvertedType = ToType;
1993 return true;
1994 }
1995
Sebastian Redl576fd422009-05-10 18:38:11 +00001996 // If the left-hand-side is nullptr_t, the right side can be a null
1997 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001998 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001999 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002000 ConvertedType = ToType;
2001 return true;
2002 }
2003
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002004 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002005 if (!ToTypePtr)
2006 return false;
2007
2008 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002009 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002010 ConvertedType = ToType;
2011 return true;
2012 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002013
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002014 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002015 // , including objective-c pointers.
2016 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002017 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002018 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002019 ConvertedType = BuildSimilarlyQualifiedPointerType(
2020 FromType->getAs<ObjCObjectPointerType>(),
2021 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002022 ToType, Context);
2023 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002024 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002025 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002026 if (!FromTypePtr)
2027 return false;
2028
2029 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002030
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002031 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002032 // pointer conversion, so don't do all of the work below.
2033 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2034 return false;
2035
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002036 // An rvalue of type "pointer to cv T," where T is an object type,
2037 // can be converted to an rvalue of type "pointer to cv void" (C++
2038 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002039 if (FromPointeeType->isIncompleteOrObjectType() &&
2040 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002041 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002042 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002043 ToType, Context,
2044 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002045 return true;
2046 }
2047
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002048 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002049 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002050 ToPointeeType->isVoidType()) {
2051 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2052 ToPointeeType,
2053 ToType, Context);
2054 return true;
2055 }
2056
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002057 // When we're overloading in C, we allow a special kind of pointer
2058 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002059 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002060 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002061 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002062 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002063 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002064 return true;
2065 }
2066
Douglas Gregor5c407d92008-10-23 00:40:37 +00002067 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002068 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002069 // An rvalue of type "pointer to cv D," where D is a class type,
2070 // can be converted to an rvalue of type "pointer to cv B," where
2071 // B is a base class (clause 10) of D. If B is an inaccessible
2072 // (clause 11) or ambiguous (10.2) base class of D, a program that
2073 // necessitates this conversion is ill-formed. The result of the
2074 // conversion is a pointer to the base class sub-object of the
2075 // derived class object. The null pointer value is converted to
2076 // the null pointer value of the destination type.
2077 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002078 // Note that we do not check for ambiguity or inaccessibility
2079 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002080 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002081 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002082 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002083 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002084 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002085 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002086 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002087 ToType, Context);
2088 return true;
2089 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002090
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002091 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2092 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2093 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2094 ToPointeeType,
2095 ToType, Context);
2096 return true;
2097 }
2098
Douglas Gregora119f102008-12-19 19:13:09 +00002099 return false;
2100}
Douglas Gregoraec25842011-04-26 23:16:46 +00002101
2102/// \brief Adopt the given qualifiers for the given type.
2103static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2104 Qualifiers TQs = T.getQualifiers();
2105
2106 // Check whether qualifiers already match.
2107 if (TQs == Qs)
2108 return T;
2109
2110 if (Qs.compatiblyIncludes(TQs))
2111 return Context.getQualifiedType(T, Qs);
2112
2113 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2114}
Douglas Gregora119f102008-12-19 19:13:09 +00002115
2116/// isObjCPointerConversion - Determines whether this is an
2117/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2118/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002119bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002120 QualType& ConvertedType,
2121 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002122 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002123 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002124
Douglas Gregoraec25842011-04-26 23:16:46 +00002125 // The set of qualifiers on the type we're converting from.
2126 Qualifiers FromQualifiers = FromType.getQualifiers();
2127
Steve Naroff7cae42b2009-07-10 23:34:53 +00002128 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002129 const ObjCObjectPointerType* ToObjCPtr =
2130 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002131 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002132 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002133
Steve Naroff7cae42b2009-07-10 23:34:53 +00002134 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002135 // If the pointee types are the same (ignoring qualifications),
2136 // then this is not a pointer conversion.
2137 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2138 FromObjCPtr->getPointeeType()))
2139 return false;
2140
Douglas Gregoraec25842011-04-26 23:16:46 +00002141 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002142 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002143 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002144 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002145 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002146 return true;
2147 }
2148 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002149 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002150 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002151 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002152 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002153 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002154 return true;
2155 }
2156 // Objective C++: We're able to convert from a pointer to an
2157 // interface to a pointer to a different interface.
2158 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002159 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2160 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002161 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002162 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2163 FromObjCPtr->getPointeeType()))
2164 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002165 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002166 ToObjCPtr->getPointeeType(),
2167 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002168 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002169 return true;
2170 }
2171
2172 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2173 // Okay: this is some kind of implicit downcast of Objective-C
2174 // interfaces, which is permitted. However, we're going to
2175 // complain about it.
2176 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002177 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002178 ToObjCPtr->getPointeeType(),
2179 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002180 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002181 return true;
2182 }
Mike Stump11289f42009-09-09 15:08:12 +00002183 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002184 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002185 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002186 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002187 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002188 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002189 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002190 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002191 // to a block pointer type.
2192 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002193 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002194 return true;
2195 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002196 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002197 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002198 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002199 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002200 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002201 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002202 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002203 return true;
2204 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002205 else
Douglas Gregora119f102008-12-19 19:13:09 +00002206 return false;
2207
Douglas Gregor033f56d2008-12-23 00:53:59 +00002208 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002209 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002210 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002211 else if (const BlockPointerType *FromBlockPtr =
2212 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002213 FromPointeeType = FromBlockPtr->getPointeeType();
2214 else
Douglas Gregora119f102008-12-19 19:13:09 +00002215 return false;
2216
Douglas Gregora119f102008-12-19 19:13:09 +00002217 // If we have pointers to pointers, recursively check whether this
2218 // is an Objective-C conversion.
2219 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2220 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2221 IncompatibleObjC)) {
2222 // We always complain about this conversion.
2223 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002224 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002225 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002226 return true;
2227 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002228 // Allow conversion of pointee being objective-c pointer to another one;
2229 // as in I* to id.
2230 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2231 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2232 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2233 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002234
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002235 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002236 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002237 return true;
2238 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002239
Douglas Gregor033f56d2008-12-23 00:53:59 +00002240 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002241 // differences in the argument and result types are in Objective-C
2242 // pointer conversions. If so, we permit the conversion (but
2243 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002244 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002245 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002246 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002247 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002248 if (FromFunctionType && ToFunctionType) {
2249 // If the function types are exactly the same, this isn't an
2250 // Objective-C pointer conversion.
2251 if (Context.getCanonicalType(FromPointeeType)
2252 == Context.getCanonicalType(ToPointeeType))
2253 return false;
2254
2255 // Perform the quick checks that will tell us whether these
2256 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002257 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002258 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2259 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2260 return false;
2261
2262 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002263 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2264 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002265 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002266 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2267 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002268 ConvertedType, IncompatibleObjC)) {
2269 // Okay, we have an Objective-C pointer conversion.
2270 HasObjCConversion = true;
2271 } else {
2272 // Function types are too different. Abort.
2273 return false;
2274 }
Mike Stump11289f42009-09-09 15:08:12 +00002275
Douglas Gregora119f102008-12-19 19:13:09 +00002276 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002277 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002278 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002279 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2280 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002281 if (Context.getCanonicalType(FromArgType)
2282 == Context.getCanonicalType(ToArgType)) {
2283 // Okay, the types match exactly. Nothing to do.
2284 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2285 ConvertedType, IncompatibleObjC)) {
2286 // Okay, we have an Objective-C pointer conversion.
2287 HasObjCConversion = true;
2288 } else {
2289 // Argument types are too different. Abort.
2290 return false;
2291 }
2292 }
2293
2294 if (HasObjCConversion) {
2295 // We had an Objective-C conversion. Allow this pointer
2296 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002297 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002298 IncompatibleObjC = true;
2299 return true;
2300 }
2301 }
2302
Sebastian Redl72b597d2009-01-25 19:43:20 +00002303 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002304}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002305
John McCall31168b02011-06-15 23:02:42 +00002306/// \brief Determine whether this is an Objective-C writeback conversion,
2307/// used for parameter passing when performing automatic reference counting.
2308///
2309/// \param FromType The type we're converting form.
2310///
2311/// \param ToType The type we're converting to.
2312///
2313/// \param ConvertedType The type that will be produced after applying
2314/// this conversion.
2315bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2316 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002317 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002318 Context.hasSameUnqualifiedType(FromType, ToType))
2319 return false;
2320
2321 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2322 QualType ToPointee;
2323 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2324 ToPointee = ToPointer->getPointeeType();
2325 else
2326 return false;
2327
2328 Qualifiers ToQuals = ToPointee.getQualifiers();
2329 if (!ToPointee->isObjCLifetimeType() ||
2330 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002331 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002332 return false;
2333
2334 // Argument must be a pointer to __strong to __weak.
2335 QualType FromPointee;
2336 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2337 FromPointee = FromPointer->getPointeeType();
2338 else
2339 return false;
2340
2341 Qualifiers FromQuals = FromPointee.getQualifiers();
2342 if (!FromPointee->isObjCLifetimeType() ||
2343 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2344 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2345 return false;
2346
2347 // Make sure that we have compatible qualifiers.
2348 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2349 if (!ToQuals.compatiblyIncludes(FromQuals))
2350 return false;
2351
2352 // Remove qualifiers from the pointee type we're converting from; they
2353 // aren't used in the compatibility check belong, and we'll be adding back
2354 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2355 FromPointee = FromPointee.getUnqualifiedType();
2356
2357 // The unqualified form of the pointee types must be compatible.
2358 ToPointee = ToPointee.getUnqualifiedType();
2359 bool IncompatibleObjC;
2360 if (Context.typesAreCompatible(FromPointee, ToPointee))
2361 FromPointee = ToPointee;
2362 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2363 IncompatibleObjC))
2364 return false;
2365
2366 /// \brief Construct the type we're converting to, which is a pointer to
2367 /// __autoreleasing pointee.
2368 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2369 ConvertedType = Context.getPointerType(FromPointee);
2370 return true;
2371}
2372
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002373bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2374 QualType& ConvertedType) {
2375 QualType ToPointeeType;
2376 if (const BlockPointerType *ToBlockPtr =
2377 ToType->getAs<BlockPointerType>())
2378 ToPointeeType = ToBlockPtr->getPointeeType();
2379 else
2380 return false;
2381
2382 QualType FromPointeeType;
2383 if (const BlockPointerType *FromBlockPtr =
2384 FromType->getAs<BlockPointerType>())
2385 FromPointeeType = FromBlockPtr->getPointeeType();
2386 else
2387 return false;
2388 // We have pointer to blocks, check whether the only
2389 // differences in the argument and result types are in Objective-C
2390 // pointer conversions. If so, we permit the conversion.
2391
2392 const FunctionProtoType *FromFunctionType
2393 = FromPointeeType->getAs<FunctionProtoType>();
2394 const FunctionProtoType *ToFunctionType
2395 = ToPointeeType->getAs<FunctionProtoType>();
2396
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002397 if (!FromFunctionType || !ToFunctionType)
2398 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002399
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002400 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002401 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002402
2403 // Perform the quick checks that will tell us whether these
2404 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002405 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002406 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2407 return false;
2408
2409 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2410 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2411 if (FromEInfo != ToEInfo)
2412 return false;
2413
2414 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002415 if (Context.hasSameType(FromFunctionType->getReturnType(),
2416 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002417 // Okay, the types match exactly. Nothing to do.
2418 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002419 QualType RHS = FromFunctionType->getReturnType();
2420 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002421 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002422 !RHS.hasQualifiers() && LHS.hasQualifiers())
2423 LHS = LHS.getUnqualifiedType();
2424
2425 if (Context.hasSameType(RHS,LHS)) {
2426 // OK exact match.
2427 } else if (isObjCPointerConversion(RHS, LHS,
2428 ConvertedType, IncompatibleObjC)) {
2429 if (IncompatibleObjC)
2430 return false;
2431 // Okay, we have an Objective-C pointer conversion.
2432 }
2433 else
2434 return false;
2435 }
2436
2437 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002438 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002439 ArgIdx != NumArgs; ++ArgIdx) {
2440 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002441 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2442 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002443 if (Context.hasSameType(FromArgType, ToArgType)) {
2444 // Okay, the types match exactly. Nothing to do.
2445 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2446 ConvertedType, IncompatibleObjC)) {
2447 if (IncompatibleObjC)
2448 return false;
2449 // Okay, we have an Objective-C pointer conversion.
2450 } else
2451 // Argument types are too different. Abort.
2452 return false;
2453 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002454 if (LangOpts.ObjCAutoRefCount &&
2455 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2456 ToFunctionType))
2457 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002458
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002459 ConvertedType = ToType;
2460 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002461}
2462
Richard Trieucaff2472011-11-23 22:32:32 +00002463enum {
2464 ft_default,
2465 ft_different_class,
2466 ft_parameter_arity,
2467 ft_parameter_mismatch,
2468 ft_return_type,
2469 ft_qualifer_mismatch
2470};
2471
2472/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2473/// function types. Catches different number of parameter, mismatch in
2474/// parameter types, and different return types.
2475void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2476 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002477 // If either type is not valid, include no extra info.
2478 if (FromType.isNull() || ToType.isNull()) {
2479 PDiag << ft_default;
2480 return;
2481 }
2482
Richard Trieucaff2472011-11-23 22:32:32 +00002483 // Get the function type from the pointers.
2484 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2485 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2486 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002487 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002488 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2489 << QualType(FromMember->getClass(), 0);
2490 return;
2491 }
2492 FromType = FromMember->getPointeeType();
2493 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002494 }
2495
Richard Trieu96ed5b62011-12-13 23:19:45 +00002496 if (FromType->isPointerType())
2497 FromType = FromType->getPointeeType();
2498 if (ToType->isPointerType())
2499 ToType = ToType->getPointeeType();
2500
2501 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002502 FromType = FromType.getNonReferenceType();
2503 ToType = ToType.getNonReferenceType();
2504
Richard Trieucaff2472011-11-23 22:32:32 +00002505 // Don't print extra info for non-specialized template functions.
2506 if (FromType->isInstantiationDependentType() &&
2507 !FromType->getAs<TemplateSpecializationType>()) {
2508 PDiag << ft_default;
2509 return;
2510 }
2511
Richard Trieu96ed5b62011-12-13 23:19:45 +00002512 // No extra info for same types.
2513 if (Context.hasSameType(FromType, ToType)) {
2514 PDiag << ft_default;
2515 return;
2516 }
2517
Richard Trieucaff2472011-11-23 22:32:32 +00002518 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2519 *ToFunction = ToType->getAs<FunctionProtoType>();
2520
2521 // Both types need to be function types.
2522 if (!FromFunction || !ToFunction) {
2523 PDiag << ft_default;
2524 return;
2525 }
2526
Alp Toker9cacbab2014-01-20 20:26:09 +00002527 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2528 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2529 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002530 return;
2531 }
2532
2533 // Handle different parameter types.
2534 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002535 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002536 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002537 << ToFunction->getParamType(ArgPos)
2538 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002539 return;
2540 }
2541
2542 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002543 if (!Context.hasSameType(FromFunction->getReturnType(),
2544 ToFunction->getReturnType())) {
2545 PDiag << ft_return_type << ToFunction->getReturnType()
2546 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002547 return;
2548 }
2549
2550 unsigned FromQuals = FromFunction->getTypeQuals(),
2551 ToQuals = ToFunction->getTypeQuals();
2552 if (FromQuals != ToQuals) {
2553 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2554 return;
2555 }
2556
2557 // Unable to find a difference, so add no extra info.
2558 PDiag << ft_default;
2559}
2560
Alp Toker9cacbab2014-01-20 20:26:09 +00002561/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002562/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002563/// they have same number of arguments. If the parameters are different,
2564/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002565bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2566 const FunctionProtoType *NewType,
2567 unsigned *ArgPos) {
2568 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2569 N = NewType->param_type_begin(),
2570 E = OldType->param_type_end();
2571 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002572 if (!Context.hasSameType(O->getUnqualifiedType(),
2573 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002574 if (ArgPos)
2575 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002576 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002577 }
2578 }
2579 return true;
2580}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002581
Douglas Gregor39c16d42008-10-24 04:54:22 +00002582/// CheckPointerConversion - Check the pointer conversion from the
2583/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002584/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002585/// conversions for which IsPointerConversion has already returned
2586/// true. It returns true and produces a diagnostic if there was an
2587/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002588bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002589 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002590 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002591 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002592 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002593 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002594
John McCall8cb679e2010-11-15 09:13:47 +00002595 Kind = CK_BitCast;
2596
David Blaikie1c7c8f72012-08-08 17:33:31 +00002597 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002598 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
David Blaikie1c7c8f72012-08-08 17:33:31 +00002599 Expr::NPCK_ZeroExpression) {
2600 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2601 DiagRuntimeBehavior(From->getExprLoc(), From,
2602 PDiag(diag::warn_impcast_bool_to_null_pointer)
2603 << ToType << From->getSourceRange());
2604 else if (!isUnevaluatedContext())
2605 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2606 << ToType << From->getSourceRange();
2607 }
John McCall9320b872011-09-09 05:25:32 +00002608 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2609 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002610 QualType FromPointeeType = FromPtrType->getPointeeType(),
2611 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002612
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002613 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2614 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002615 // We must have a derived-to-base conversion. Check an
2616 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002617 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2618 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002619 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002620 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002621 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002622
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002623 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002624 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002625 }
2626 }
John McCall9320b872011-09-09 05:25:32 +00002627 } else if (const ObjCObjectPointerType *ToPtrType =
2628 ToType->getAs<ObjCObjectPointerType>()) {
2629 if (const ObjCObjectPointerType *FromPtrType =
2630 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002631 // Objective-C++ conversions are always okay.
2632 // FIXME: We should have a different class of conversions for the
2633 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002634 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002635 return false;
John McCall9320b872011-09-09 05:25:32 +00002636 } else if (FromType->isBlockPointerType()) {
2637 Kind = CK_BlockPointerToObjCPointerCast;
2638 } else {
2639 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002640 }
John McCall9320b872011-09-09 05:25:32 +00002641 } else if (ToType->isBlockPointerType()) {
2642 if (!FromType->isBlockPointerType())
2643 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002644 }
John McCall8cb679e2010-11-15 09:13:47 +00002645
2646 // We shouldn't fall into this case unless it's valid for other
2647 // reasons.
2648 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2649 Kind = CK_NullToPointer;
2650
Douglas Gregor39c16d42008-10-24 04:54:22 +00002651 return false;
2652}
2653
Sebastian Redl72b597d2009-01-25 19:43:20 +00002654/// IsMemberPointerConversion - Determines whether the conversion of the
2655/// expression From, which has the (possibly adjusted) type FromType, can be
2656/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2657/// If so, returns true and places the converted type (that might differ from
2658/// ToType in its cv-qualifiers at some level) into ConvertedType.
2659bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002660 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002661 bool InOverloadResolution,
2662 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002663 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002664 if (!ToTypePtr)
2665 return false;
2666
2667 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002668 if (From->isNullPointerConstant(Context,
2669 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2670 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002671 ConvertedType = ToType;
2672 return true;
2673 }
2674
2675 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002676 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002677 if (!FromTypePtr)
2678 return false;
2679
2680 // A pointer to member of B can be converted to a pointer to member of D,
2681 // where D is derived from B (C++ 4.11p2).
2682 QualType FromClass(FromTypePtr->getClass(), 0);
2683 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002684
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002685 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002686 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002687 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002688 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2689 ToClass.getTypePtr());
2690 return true;
2691 }
2692
2693 return false;
2694}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002695
Sebastian Redl72b597d2009-01-25 19:43:20 +00002696/// CheckMemberPointerConversion - Check the member pointer conversion from the
2697/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002698/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002699/// for which IsMemberPointerConversion has already returned true. It returns
2700/// true and produces a diagnostic if there was an error, or returns false
2701/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002702bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002703 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002704 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002705 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002706 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002707 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002708 if (!FromPtrType) {
2709 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002710 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002711 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002712 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002713 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002714 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002715 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002716
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002717 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002718 assert(ToPtrType && "No member pointer cast has a target type "
2719 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002720
Sebastian Redled8f2002009-01-28 18:33:18 +00002721 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2722 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002723
Sebastian Redled8f2002009-01-28 18:33:18 +00002724 // FIXME: What about dependent types?
2725 assert(FromClass->isRecordType() && "Pointer into non-class.");
2726 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002727
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002728 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002729 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002730 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2731 assert(DerivationOkay &&
2732 "Should not have been called if derivation isn't OK.");
2733 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002734
Sebastian Redled8f2002009-01-28 18:33:18 +00002735 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2736 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002737 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2738 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2739 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2740 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002741 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002742
Douglas Gregor89ee6822009-02-28 01:32:25 +00002743 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002744 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2745 << FromClass << ToClass << QualType(VBase, 0)
2746 << From->getSourceRange();
2747 return true;
2748 }
2749
John McCall5b0829a2010-02-10 09:31:12 +00002750 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002751 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2752 Paths.front(),
2753 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002754
Anders Carlssond7923c62009-08-22 23:33:40 +00002755 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002756 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002757 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002758 return false;
2759}
2760
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002761/// Determine whether the lifetime conversion between the two given
2762/// qualifiers sets is nontrivial.
2763static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2764 Qualifiers ToQuals) {
2765 // Converting anything to const __unsafe_unretained is trivial.
2766 if (ToQuals.hasConst() &&
2767 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2768 return false;
2769
2770 return true;
2771}
2772
Douglas Gregor9a657932008-10-21 23:43:52 +00002773/// IsQualificationConversion - Determines whether the conversion from
2774/// an rvalue of type FromType to ToType is a qualification conversion
2775/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002776///
2777/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2778/// when the qualification conversion involves a change in the Objective-C
2779/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002780bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002781Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002782 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002783 FromType = Context.getCanonicalType(FromType);
2784 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002785 ObjCLifetimeConversion = false;
2786
Douglas Gregor9a657932008-10-21 23:43:52 +00002787 // If FromType and ToType are the same type, this is not a
2788 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002789 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002790 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002791
Douglas Gregor9a657932008-10-21 23:43:52 +00002792 // (C++ 4.4p4):
2793 // A conversion can add cv-qualifiers at levels other than the first
2794 // in multi-level pointers, subject to the following rules: [...]
2795 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002796 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002797 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002798 // Within each iteration of the loop, we check the qualifiers to
2799 // determine if this still looks like a qualification
2800 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002801 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002802 // until there are no more pointers or pointers-to-members left to
2803 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002804 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002805
Douglas Gregor90609aa2011-04-25 18:40:17 +00002806 Qualifiers FromQuals = FromType.getQualifiers();
2807 Qualifiers ToQuals = ToType.getQualifiers();
2808
John McCall31168b02011-06-15 23:02:42 +00002809 // Objective-C ARC:
2810 // Check Objective-C lifetime conversions.
2811 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2812 UnwrappedAnyPointer) {
2813 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002814 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2815 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002816 FromQuals.removeObjCLifetime();
2817 ToQuals.removeObjCLifetime();
2818 } else {
2819 // Qualification conversions cannot cast between different
2820 // Objective-C lifetime qualifiers.
2821 return false;
2822 }
2823 }
2824
Douglas Gregorf30053d2011-05-08 06:09:53 +00002825 // Allow addition/removal of GC attributes but not changing GC attributes.
2826 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2827 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2828 FromQuals.removeObjCGCAttr();
2829 ToQuals.removeObjCGCAttr();
2830 }
2831
Douglas Gregor9a657932008-10-21 23:43:52 +00002832 // -- for every j > 0, if const is in cv 1,j then const is in cv
2833 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002834 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002835 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002836
Douglas Gregor9a657932008-10-21 23:43:52 +00002837 // -- if the cv 1,j and cv 2,j are different, then const is in
2838 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002839 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002840 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002841 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002842
Douglas Gregor9a657932008-10-21 23:43:52 +00002843 // Keep track of whether all prior cv-qualifiers in the "to" type
2844 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002845 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002846 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002847 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002848
2849 // We are left with FromType and ToType being the pointee types
2850 // after unwrapping the original FromType and ToType the same number
2851 // of types. If we unwrapped any pointers, and if FromType and
2852 // ToType have the same unqualified type (since we checked
2853 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002854 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002855}
2856
Douglas Gregorc79862f2012-04-12 17:51:55 +00002857/// \brief - Determine whether this is a conversion from a scalar type to an
2858/// atomic type.
2859///
2860/// If successful, updates \c SCS's second and third steps in the conversion
2861/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002862static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2863 bool InOverloadResolution,
2864 StandardConversionSequence &SCS,
2865 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002866 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2867 if (!ToAtomic)
2868 return false;
2869
2870 StandardConversionSequence InnerSCS;
2871 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2872 InOverloadResolution, InnerSCS,
2873 CStyle, /*AllowObjCWritebackConversion=*/false))
2874 return false;
2875
2876 SCS.Second = InnerSCS.Second;
2877 SCS.setToType(1, InnerSCS.getToType(1));
2878 SCS.Third = InnerSCS.Third;
2879 SCS.QualificationIncludesObjCLifetime
2880 = InnerSCS.QualificationIncludesObjCLifetime;
2881 SCS.setToType(2, InnerSCS.getToType(2));
2882 return true;
2883}
2884
Sebastian Redle5417162012-03-27 18:33:03 +00002885static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2886 CXXConstructorDecl *Constructor,
2887 QualType Type) {
2888 const FunctionProtoType *CtorType =
2889 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002890 if (CtorType->getNumParams() > 0) {
2891 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002892 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2893 return true;
2894 }
2895 return false;
2896}
2897
Sebastian Redl82ace982012-02-11 23:51:08 +00002898static OverloadingResult
2899IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2900 CXXRecordDecl *To,
2901 UserDefinedConversionSequence &User,
2902 OverloadCandidateSet &CandidateSet,
2903 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002904 DeclContext::lookup_result R = S.LookupConstructors(To);
2905 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002906 Con != ConEnd; ++Con) {
2907 NamedDecl *D = *Con;
2908 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2909
2910 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00002911 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00002912 FunctionTemplateDecl *ConstructorTmpl
2913 = dyn_cast<FunctionTemplateDecl>(D);
2914 if (ConstructorTmpl)
2915 Constructor
2916 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2917 else
2918 Constructor = cast<CXXConstructorDecl>(D);
2919
2920 bool Usable = !Constructor->isInvalidDecl() &&
2921 S.isInitListConstructor(Constructor) &&
2922 (AllowExplicit || !Constructor->isExplicit());
2923 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002924 // If the first argument is (a reference to) the target type,
2925 // suppress conversions.
2926 bool SuppressUserConversions =
2927 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002928 if (ConstructorTmpl)
2929 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00002930 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002931 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002932 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002933 else
2934 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002935 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002936 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002937 }
2938 }
2939
2940 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2941
2942 OverloadCandidateSet::iterator Best;
2943 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2944 case OR_Success: {
2945 // Record the standard conversion we used and the conversion function.
2946 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002947 QualType ThisType = Constructor->getThisType(S.Context);
2948 // Initializer lists don't have conversions as such.
2949 User.Before.setAsIdentityConversion();
2950 User.HadMultipleCandidates = HadMultipleCandidates;
2951 User.ConversionFunction = Constructor;
2952 User.FoundConversionFunction = Best->FoundDecl;
2953 User.After.setAsIdentityConversion();
2954 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2955 User.After.setAllToTypes(ToType);
2956 return OR_Success;
2957 }
2958
2959 case OR_No_Viable_Function:
2960 return OR_No_Viable_Function;
2961 case OR_Deleted:
2962 return OR_Deleted;
2963 case OR_Ambiguous:
2964 return OR_Ambiguous;
2965 }
2966
2967 llvm_unreachable("Invalid OverloadResult!");
2968}
2969
Douglas Gregor576e98c2009-01-30 23:27:23 +00002970/// Determines whether there is a user-defined conversion sequence
2971/// (C++ [over.ics.user]) that converts expression From to the type
2972/// ToType. If such a conversion exists, User will contain the
2973/// user-defined conversion sequence that performs such a conversion
2974/// and this routine will return true. Otherwise, this routine returns
2975/// false and User is unspecified.
2976///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002977/// \param AllowExplicit true if the conversion should consider C++0x
2978/// "explicit" conversion functions as well as non-explicit conversion
2979/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00002980///
2981/// \param AllowObjCConversionOnExplicit true if the conversion should
2982/// allow an extra Objective-C pointer conversion on uses of explicit
2983/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00002984static OverloadingResult
2985IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002986 UserDefinedConversionSequence &User,
2987 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00002988 bool AllowExplicit,
2989 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00002990 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00002991
Douglas Gregor5ab11652010-04-17 22:01:05 +00002992 // Whether we will only visit constructors.
2993 bool ConstructorsOnly = false;
2994
2995 // If the type we are conversion to is a class type, enumerate its
2996 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002997 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002998 // C++ [over.match.ctor]p1:
2999 // When objects of class type are direct-initialized (8.5), or
3000 // copy-initialized from an expression of the same or a
3001 // derived class type (8.5), overload resolution selects the
3002 // constructor. [...] For copy-initialization, the candidate
3003 // functions are all the converting constructors (12.3.1) of
3004 // that class. The argument list is the expression-list within
3005 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003006 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003007 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003008 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003009 ConstructorsOnly = true;
3010
Benjamin Kramer90633e32012-11-23 17:04:52 +00003011 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003012 // RequireCompleteType may have returned true due to some invalid decl
3013 // during template instantiation, but ToType may be complete enough now
3014 // to try to recover.
3015 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003016 // We're not going to find any constructors.
3017 } else if (CXXRecordDecl *ToRecordDecl
3018 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003019
3020 Expr **Args = &From;
3021 unsigned NumArgs = 1;
3022 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003023 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003024 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003025 OverloadingResult Result = IsInitializerListConstructorConversion(
3026 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3027 if (Result != OR_No_Viable_Function)
3028 return Result;
3029 // Never mind.
3030 CandidateSet.clear();
3031
3032 // If we're list-initializing, we pass the individual elements as
3033 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003034 Args = InitList->getInits();
3035 NumArgs = InitList->getNumInits();
3036 ListInitializing = true;
3037 }
3038
David Blaikieff7d47a2012-12-19 00:45:41 +00003039 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3040 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003041 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003042 NamedDecl *D = *Con;
3043 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3044
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003045 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003046 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003047 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003048 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003049 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003050 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003051 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3052 else
John McCalla0296f72010-03-19 07:35:19 +00003053 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003054
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003055 bool Usable = !Constructor->isInvalidDecl();
3056 if (ListInitializing)
3057 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3058 else
3059 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3060 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003061 bool SuppressUserConversions = !ConstructorsOnly;
3062 if (SuppressUserConversions && ListInitializing) {
3063 SuppressUserConversions = false;
3064 if (NumArgs == 1) {
3065 // If the first argument is (a reference to) the target type,
3066 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003067 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3068 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003069 }
3070 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003071 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003072 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003073 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003074 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003075 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003076 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003077 // Allow one user-defined conversion when user specifies a
3078 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003079 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003080 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003081 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003082 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003083 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003084 }
3085 }
3086
Douglas Gregor5ab11652010-04-17 22:01:05 +00003087 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003088 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003089 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003090 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003091 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003092 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003093 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003094 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3095 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003096 std::pair<CXXRecordDecl::conversion_iterator,
3097 CXXRecordDecl::conversion_iterator>
3098 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3099 for (CXXRecordDecl::conversion_iterator
3100 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003101 DeclAccessPair FoundDecl = I.getPair();
3102 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003103 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3104 if (isa<UsingShadowDecl>(D))
3105 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3106
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003107 CXXConversionDecl *Conv;
3108 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003109 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3110 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003111 else
John McCallda4458e2010-03-31 01:36:47 +00003112 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003113
3114 if (AllowExplicit || !Conv->isExplicit()) {
3115 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003116 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3117 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003118 CandidateSet,
3119 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003120 else
John McCall5c32be02010-08-24 20:38:10 +00003121 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003122 From, ToType, CandidateSet,
3123 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003124 }
3125 }
3126 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003127 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003128
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003129 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3130
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003131 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003132 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003133 case OR_Success:
3134 // Record the standard conversion we used and the conversion function.
3135 if (CXXConstructorDecl *Constructor
3136 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3137 // C++ [over.ics.user]p1:
3138 // If the user-defined conversion is specified by a
3139 // constructor (12.3.1), the initial standard conversion
3140 // sequence converts the source type to the type required by
3141 // the argument of the constructor.
3142 //
3143 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003144 if (isa<InitListExpr>(From)) {
3145 // Initializer lists don't have conversions as such.
3146 User.Before.setAsIdentityConversion();
3147 } else {
3148 if (Best->Conversions[0].isEllipsis())
3149 User.EllipsisConversion = true;
3150 else {
3151 User.Before = Best->Conversions[0].Standard;
3152 User.EllipsisConversion = false;
3153 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003154 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003155 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003156 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003157 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003158 User.After.setAsIdentityConversion();
3159 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3160 User.After.setAllToTypes(ToType);
3161 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003162 }
3163 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003164 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3165 // C++ [over.ics.user]p1:
3166 //
3167 // [...] If the user-defined conversion is specified by a
3168 // conversion function (12.3.2), the initial standard
3169 // conversion sequence converts the source type to the
3170 // implicit object parameter of the conversion function.
3171 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003172 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003173 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003174 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003175 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003176
John McCall5c32be02010-08-24 20:38:10 +00003177 // C++ [over.ics.user]p2:
3178 // The second standard conversion sequence converts the
3179 // result of the user-defined conversion to the target type
3180 // for the sequence. Since an implicit conversion sequence
3181 // is an initialization, the special rules for
3182 // initialization by user-defined conversion apply when
3183 // selecting the best user-defined conversion for a
3184 // user-defined conversion sequence (see 13.3.3 and
3185 // 13.3.3.1).
3186 User.After = Best->FinalConversion;
3187 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003188 }
David Blaikie8a40f702012-01-17 06:56:22 +00003189 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003190
John McCall5c32be02010-08-24 20:38:10 +00003191 case OR_No_Viable_Function:
3192 return OR_No_Viable_Function;
3193 case OR_Deleted:
3194 // No conversion here! We're done.
3195 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003196
John McCall5c32be02010-08-24 20:38:10 +00003197 case OR_Ambiguous:
3198 return OR_Ambiguous;
3199 }
3200
David Blaikie8a40f702012-01-17 06:56:22 +00003201 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003202}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003203
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003204bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003205Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003206 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003207 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3208 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003209 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003210 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003211 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003212 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003213 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3214 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003215 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003216 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003217 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003218 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003219 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3220 << From->getType() << From->getSourceRange() << ToType;
3221 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003222 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003223 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003224 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003225}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003226
Douglas Gregor2837aa22012-02-22 17:32:19 +00003227/// \brief Compare the user-defined conversion functions or constructors
3228/// of two user-defined conversion sequences to determine whether any ordering
3229/// is possible.
3230static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003231compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003232 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003233 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003234 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003235
Douglas Gregor2837aa22012-02-22 17:32:19 +00003236 // Objective-C++:
3237 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003238 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003239 // respectively, always prefer the conversion to a function pointer,
3240 // because the function pointer is more lightweight and is more likely
3241 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003242 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003243 if (!Conv1)
3244 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003245
Douglas Gregor2837aa22012-02-22 17:32:19 +00003246 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3247 if (!Conv2)
3248 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003249
Douglas Gregor2837aa22012-02-22 17:32:19 +00003250 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3251 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3252 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3253 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003254 return Block1 ? ImplicitConversionSequence::Worse
3255 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003256 }
3257
3258 return ImplicitConversionSequence::Indistinguishable;
3259}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003260
3261static bool hasDeprecatedStringLiteralToCharPtrConversion(
3262 const ImplicitConversionSequence &ICS) {
3263 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3264 (ICS.isUserDefined() &&
3265 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3266}
3267
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003268/// CompareImplicitConversionSequences - Compare two implicit
3269/// conversion sequences to determine whether one is better than the
3270/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003271static ImplicitConversionSequence::CompareKind
3272CompareImplicitConversionSequences(Sema &S,
3273 const ImplicitConversionSequence& ICS1,
3274 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003275{
3276 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3277 // conversion sequences (as defined in 13.3.3.1)
3278 // -- a standard conversion sequence (13.3.3.1.1) is a better
3279 // conversion sequence than a user-defined conversion sequence or
3280 // an ellipsis conversion sequence, and
3281 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3282 // conversion sequence than an ellipsis conversion sequence
3283 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003284 //
John McCall0d1da222010-01-12 00:44:57 +00003285 // C++0x [over.best.ics]p10:
3286 // For the purpose of ranking implicit conversion sequences as
3287 // described in 13.3.3.2, the ambiguous conversion sequence is
3288 // treated as a user-defined sequence that is indistinguishable
3289 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003290
3291 // String literal to 'char *' conversion has been deprecated in C++03. It has
3292 // been removed from C++11. We still accept this conversion, if it happens at
3293 // the best viable function. Otherwise, this conversion is considered worse
3294 // than ellipsis conversion. Consider this as an extension; this is not in the
3295 // standard. For example:
3296 //
3297 // int &f(...); // #1
3298 // void f(char*); // #2
3299 // void g() { int &r = f("foo"); }
3300 //
3301 // In C++03, we pick #2 as the best viable function.
3302 // In C++11, we pick #1 as the best viable function, because ellipsis
3303 // conversion is better than string-literal to char* conversion (since there
3304 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3305 // convert arguments, #2 would be the best viable function in C++11.
3306 // If the best viable function has this conversion, a warning will be issued
3307 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3308
3309 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3310 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3311 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3312 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3313 ? ImplicitConversionSequence::Worse
3314 : ImplicitConversionSequence::Better;
3315
Douglas Gregor5ab11652010-04-17 22:01:05 +00003316 if (ICS1.getKindRank() < ICS2.getKindRank())
3317 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003318 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003319 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003320
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003321 // The following checks require both conversion sequences to be of
3322 // the same kind.
3323 if (ICS1.getKind() != ICS2.getKind())
3324 return ImplicitConversionSequence::Indistinguishable;
3325
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003326 ImplicitConversionSequence::CompareKind Result =
3327 ImplicitConversionSequence::Indistinguishable;
3328
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003329 // Two implicit conversion sequences of the same form are
3330 // indistinguishable conversion sequences unless one of the
3331 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003332 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003333 Result = CompareStandardConversionSequences(S,
3334 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003335 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003336 // User-defined conversion sequence U1 is a better conversion
3337 // sequence than another user-defined conversion sequence U2 if
3338 // they contain the same user-defined conversion function or
3339 // constructor and if the second standard conversion sequence of
3340 // U1 is better than the second standard conversion sequence of
3341 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003342 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003343 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003344 Result = CompareStandardConversionSequences(S,
3345 ICS1.UserDefined.After,
3346 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003347 else
3348 Result = compareConversionFunctions(S,
3349 ICS1.UserDefined.ConversionFunction,
3350 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003351 }
3352
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003353 // List-initialization sequence L1 is a better conversion sequence than
3354 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3355 // for some X and L2 does not.
3356 if (Result == ImplicitConversionSequence::Indistinguishable &&
Richard Smitha93f1022013-09-06 22:30:28 +00003357 !ICS1.isBad()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003358 if (ICS1.isStdInitializerListElement() &&
3359 !ICS2.isStdInitializerListElement())
3360 return ImplicitConversionSequence::Better;
3361 if (!ICS1.isStdInitializerListElement() &&
3362 ICS2.isStdInitializerListElement())
3363 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003364 }
3365
3366 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003367}
3368
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003369static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3370 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3371 Qualifiers Quals;
3372 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003373 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003374 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003375
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003376 return Context.hasSameUnqualifiedType(T1, T2);
3377}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003378
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003379// Per 13.3.3.2p3, compare the given standard conversion sequences to
3380// determine if one is a proper subset of the other.
3381static ImplicitConversionSequence::CompareKind
3382compareStandardConversionSubsets(ASTContext &Context,
3383 const StandardConversionSequence& SCS1,
3384 const StandardConversionSequence& SCS2) {
3385 ImplicitConversionSequence::CompareKind Result
3386 = ImplicitConversionSequence::Indistinguishable;
3387
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003388 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003389 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003390 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3391 return ImplicitConversionSequence::Better;
3392 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3393 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003394
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003395 if (SCS1.Second != SCS2.Second) {
3396 if (SCS1.Second == ICK_Identity)
3397 Result = ImplicitConversionSequence::Better;
3398 else if (SCS2.Second == ICK_Identity)
3399 Result = ImplicitConversionSequence::Worse;
3400 else
3401 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003402 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003403 return ImplicitConversionSequence::Indistinguishable;
3404
3405 if (SCS1.Third == SCS2.Third) {
3406 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3407 : ImplicitConversionSequence::Indistinguishable;
3408 }
3409
3410 if (SCS1.Third == ICK_Identity)
3411 return Result == ImplicitConversionSequence::Worse
3412 ? ImplicitConversionSequence::Indistinguishable
3413 : ImplicitConversionSequence::Better;
3414
3415 if (SCS2.Third == ICK_Identity)
3416 return Result == ImplicitConversionSequence::Better
3417 ? ImplicitConversionSequence::Indistinguishable
3418 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003420 return ImplicitConversionSequence::Indistinguishable;
3421}
3422
Douglas Gregore696ebb2011-01-26 14:52:12 +00003423/// \brief Determine whether one of the given reference bindings is better
3424/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003425static bool
3426isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3427 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003428 // C++0x [over.ics.rank]p3b4:
3429 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3430 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003431 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003432 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003433 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003434 // reference*.
3435 //
3436 // FIXME: Rvalue references. We're going rogue with the above edits,
3437 // because the semantics in the current C++0x working paper (N3225 at the
3438 // time of this writing) break the standard definition of std::forward
3439 // and std::reference_wrapper when dealing with references to functions.
3440 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003441 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3442 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3443 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003444
Douglas Gregore696ebb2011-01-26 14:52:12 +00003445 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3446 SCS2.IsLvalueReference) ||
3447 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003448 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003449}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003450
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003451/// CompareStandardConversionSequences - Compare two standard
3452/// conversion sequences to determine whether one is better than the
3453/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003454static ImplicitConversionSequence::CompareKind
3455CompareStandardConversionSequences(Sema &S,
3456 const StandardConversionSequence& SCS1,
3457 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003458{
3459 // Standard conversion sequence S1 is a better conversion sequence
3460 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3461
3462 // -- S1 is a proper subsequence of S2 (comparing the conversion
3463 // sequences in the canonical form defined by 13.3.3.1.1,
3464 // excluding any Lvalue Transformation; the identity conversion
3465 // sequence is considered to be a subsequence of any
3466 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003467 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003468 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003469 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003470
3471 // -- the rank of S1 is better than the rank of S2 (by the rules
3472 // defined below), or, if not that,
3473 ImplicitConversionRank Rank1 = SCS1.getRank();
3474 ImplicitConversionRank Rank2 = SCS2.getRank();
3475 if (Rank1 < Rank2)
3476 return ImplicitConversionSequence::Better;
3477 else if (Rank2 < Rank1)
3478 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003479
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003480 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3481 // are indistinguishable unless one of the following rules
3482 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003483
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003484 // A conversion that is not a conversion of a pointer, or
3485 // pointer to member, to bool is better than another conversion
3486 // that is such a conversion.
3487 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3488 return SCS2.isPointerConversionToBool()
3489 ? ImplicitConversionSequence::Better
3490 : ImplicitConversionSequence::Worse;
3491
Douglas Gregor5c407d92008-10-23 00:40:37 +00003492 // C++ [over.ics.rank]p4b2:
3493 //
3494 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003495 // conversion of B* to A* is better than conversion of B* to
3496 // void*, and conversion of A* to void* is better than conversion
3497 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003498 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003499 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003500 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003501 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003502 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3503 // Exactly one of the conversion sequences is a conversion to
3504 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003505 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3506 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003507 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3508 // Neither conversion sequence converts to a void pointer; compare
3509 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003510 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003511 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003512 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003513 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3514 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003515 // Both conversion sequences are conversions to void
3516 // pointers. Compare the source types to determine if there's an
3517 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003518 QualType FromType1 = SCS1.getFromType();
3519 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003520
3521 // Adjust the types we're converting from via the array-to-pointer
3522 // conversion, if we need to.
3523 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003524 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003525 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003526 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003527
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003528 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3529 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003530
John McCall5c32be02010-08-24 20:38:10 +00003531 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003532 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003533 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003534 return ImplicitConversionSequence::Worse;
3535
3536 // Objective-C++: If one interface is more specific than the
3537 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003538 const ObjCObjectPointerType* FromObjCPtr1
3539 = FromType1->getAs<ObjCObjectPointerType>();
3540 const ObjCObjectPointerType* FromObjCPtr2
3541 = FromType2->getAs<ObjCObjectPointerType>();
3542 if (FromObjCPtr1 && FromObjCPtr2) {
3543 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3544 FromObjCPtr2);
3545 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3546 FromObjCPtr1);
3547 if (AssignLeft != AssignRight) {
3548 return AssignLeft? ImplicitConversionSequence::Better
3549 : ImplicitConversionSequence::Worse;
3550 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003551 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003552 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003553
3554 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3555 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003556 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003557 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003558 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003559
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003560 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003561 // Check for a better reference binding based on the kind of bindings.
3562 if (isBetterReferenceBindingKind(SCS1, SCS2))
3563 return ImplicitConversionSequence::Better;
3564 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3565 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003566
Sebastian Redlb28b4072009-03-22 23:49:27 +00003567 // C++ [over.ics.rank]p3b4:
3568 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3569 // which the references refer are the same type except for
3570 // top-level cv-qualifiers, and the type to which the reference
3571 // initialized by S2 refers is more cv-qualified than the type
3572 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003573 QualType T1 = SCS1.getToType(2);
3574 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003575 T1 = S.Context.getCanonicalType(T1);
3576 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003577 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003578 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3579 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003580 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003581 // Objective-C++ ARC: If the references refer to objects with different
3582 // lifetimes, prefer bindings that don't change lifetime.
3583 if (SCS1.ObjCLifetimeConversionBinding !=
3584 SCS2.ObjCLifetimeConversionBinding) {
3585 return SCS1.ObjCLifetimeConversionBinding
3586 ? ImplicitConversionSequence::Worse
3587 : ImplicitConversionSequence::Better;
3588 }
3589
Chandler Carruth8e543b32010-12-12 08:17:55 +00003590 // If the type is an array type, promote the element qualifiers to the
3591 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003592 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003593 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003594 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003595 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003596 if (T2.isMoreQualifiedThan(T1))
3597 return ImplicitConversionSequence::Better;
3598 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003599 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003600 }
3601 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003602
Francois Pichet08d2fa02011-09-18 21:37:37 +00003603 // In Microsoft mode, prefer an integral conversion to a
3604 // floating-to-integral conversion if the integral conversion
3605 // is between types of the same size.
3606 // For example:
3607 // void f(float);
3608 // void f(int);
3609 // int main {
3610 // long a;
3611 // f(a);
3612 // }
3613 // Here, MSVC will call f(int) instead of generating a compile error
3614 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003615 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3616 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003617 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003618 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003619 return ImplicitConversionSequence::Better;
3620
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003621 return ImplicitConversionSequence::Indistinguishable;
3622}
3623
3624/// CompareQualificationConversions - Compares two standard conversion
3625/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003626/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003627static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003628CompareQualificationConversions(Sema &S,
3629 const StandardConversionSequence& SCS1,
3630 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003631 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003632 // -- S1 and S2 differ only in their qualification conversion and
3633 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3634 // cv-qualification signature of type T1 is a proper subset of
3635 // the cv-qualification signature of type T2, and S1 is not the
3636 // deprecated string literal array-to-pointer conversion (4.2).
3637 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3638 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3639 return ImplicitConversionSequence::Indistinguishable;
3640
3641 // FIXME: the example in the standard doesn't use a qualification
3642 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003643 QualType T1 = SCS1.getToType(2);
3644 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003645 T1 = S.Context.getCanonicalType(T1);
3646 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003647 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003648 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3649 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003650
3651 // If the types are the same, we won't learn anything by unwrapped
3652 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003653 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003654 return ImplicitConversionSequence::Indistinguishable;
3655
Chandler Carruth607f38e2009-12-29 07:16:59 +00003656 // If the type is an array type, promote the element qualifiers to the type
3657 // for comparison.
3658 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003659 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003660 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003661 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003662
Mike Stump11289f42009-09-09 15:08:12 +00003663 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003664 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003665
3666 // Objective-C++ ARC:
3667 // Prefer qualification conversions not involving a change in lifetime
3668 // to qualification conversions that do not change lifetime.
3669 if (SCS1.QualificationIncludesObjCLifetime !=
3670 SCS2.QualificationIncludesObjCLifetime) {
3671 Result = SCS1.QualificationIncludesObjCLifetime
3672 ? ImplicitConversionSequence::Worse
3673 : ImplicitConversionSequence::Better;
3674 }
3675
John McCall5c32be02010-08-24 20:38:10 +00003676 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003677 // Within each iteration of the loop, we check the qualifiers to
3678 // determine if this still looks like a qualification
3679 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003680 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003681 // until there are no more pointers or pointers-to-members left
3682 // to unwrap. This essentially mimics what
3683 // IsQualificationConversion does, but here we're checking for a
3684 // strict subset of qualifiers.
3685 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3686 // The qualifiers are the same, so this doesn't tell us anything
3687 // about how the sequences rank.
3688 ;
3689 else if (T2.isMoreQualifiedThan(T1)) {
3690 // T1 has fewer qualifiers, so it could be the better sequence.
3691 if (Result == ImplicitConversionSequence::Worse)
3692 // Neither has qualifiers that are a subset of the other's
3693 // qualifiers.
3694 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003695
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003696 Result = ImplicitConversionSequence::Better;
3697 } else if (T1.isMoreQualifiedThan(T2)) {
3698 // T2 has fewer qualifiers, so it could be the better sequence.
3699 if (Result == ImplicitConversionSequence::Better)
3700 // Neither has qualifiers that are a subset of the other's
3701 // qualifiers.
3702 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003703
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003704 Result = ImplicitConversionSequence::Worse;
3705 } else {
3706 // Qualifiers are disjoint.
3707 return ImplicitConversionSequence::Indistinguishable;
3708 }
3709
3710 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003711 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003712 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003713 }
3714
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003715 // Check that the winning standard conversion sequence isn't using
3716 // the deprecated string literal array to pointer conversion.
3717 switch (Result) {
3718 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003719 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003720 Result = ImplicitConversionSequence::Indistinguishable;
3721 break;
3722
3723 case ImplicitConversionSequence::Indistinguishable:
3724 break;
3725
3726 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003727 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003728 Result = ImplicitConversionSequence::Indistinguishable;
3729 break;
3730 }
3731
3732 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003733}
3734
Douglas Gregor5c407d92008-10-23 00:40:37 +00003735/// CompareDerivedToBaseConversions - Compares two standard conversion
3736/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003737/// various kinds of derived-to-base conversions (C++
3738/// [over.ics.rank]p4b3). As part of these checks, we also look at
3739/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003740static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003741CompareDerivedToBaseConversions(Sema &S,
3742 const StandardConversionSequence& SCS1,
3743 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003744 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003745 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003746 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003747 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003748
3749 // Adjust the types we're converting from via the array-to-pointer
3750 // conversion, if we need to.
3751 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003752 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003753 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003754 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003755
3756 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003757 FromType1 = S.Context.getCanonicalType(FromType1);
3758 ToType1 = S.Context.getCanonicalType(ToType1);
3759 FromType2 = S.Context.getCanonicalType(FromType2);
3760 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003761
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003762 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003763 //
3764 // If class B is derived directly or indirectly from class A and
3765 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003766 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003767 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003768 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003769 SCS2.Second == ICK_Pointer_Conversion &&
3770 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3771 FromType1->isPointerType() && FromType2->isPointerType() &&
3772 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003773 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003774 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003775 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003776 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003777 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003778 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003779 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003780 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003781
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003782 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003783 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003784 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003785 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003786 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003787 return ImplicitConversionSequence::Worse;
3788 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003789
3790 // -- conversion of B* to A* is better than conversion of C* to A*,
3791 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003792 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003793 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003794 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003795 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003796 }
3797 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3798 SCS2.Second == ICK_Pointer_Conversion) {
3799 const ObjCObjectPointerType *FromPtr1
3800 = FromType1->getAs<ObjCObjectPointerType>();
3801 const ObjCObjectPointerType *FromPtr2
3802 = FromType2->getAs<ObjCObjectPointerType>();
3803 const ObjCObjectPointerType *ToPtr1
3804 = ToType1->getAs<ObjCObjectPointerType>();
3805 const ObjCObjectPointerType *ToPtr2
3806 = ToType2->getAs<ObjCObjectPointerType>();
3807
3808 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3809 // Apply the same conversion ranking rules for Objective-C pointer types
3810 // that we do for C++ pointers to class types. However, we employ the
3811 // Objective-C pseudo-subtyping relationship used for assignment of
3812 // Objective-C pointer types.
3813 bool FromAssignLeft
3814 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3815 bool FromAssignRight
3816 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3817 bool ToAssignLeft
3818 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3819 bool ToAssignRight
3820 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3821
3822 // A conversion to an a non-id object pointer type or qualified 'id'
3823 // type is better than a conversion to 'id'.
3824 if (ToPtr1->isObjCIdType() &&
3825 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3826 return ImplicitConversionSequence::Worse;
3827 if (ToPtr2->isObjCIdType() &&
3828 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3829 return ImplicitConversionSequence::Better;
3830
3831 // A conversion to a non-id object pointer type is better than a
3832 // conversion to a qualified 'id' type
3833 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3834 return ImplicitConversionSequence::Worse;
3835 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3836 return ImplicitConversionSequence::Better;
3837
3838 // A conversion to an a non-Class object pointer type or qualified 'Class'
3839 // type is better than a conversion to 'Class'.
3840 if (ToPtr1->isObjCClassType() &&
3841 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3842 return ImplicitConversionSequence::Worse;
3843 if (ToPtr2->isObjCClassType() &&
3844 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3845 return ImplicitConversionSequence::Better;
3846
3847 // A conversion to a non-Class object pointer type is better than a
3848 // conversion to a qualified 'Class' type.
3849 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3850 return ImplicitConversionSequence::Worse;
3851 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3852 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003853
Douglas Gregor058d3de2011-01-31 18:51:41 +00003854 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3855 if (S.Context.hasSameType(FromType1, FromType2) &&
3856 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3857 (ToAssignLeft != ToAssignRight))
3858 return ToAssignLeft? ImplicitConversionSequence::Worse
3859 : ImplicitConversionSequence::Better;
3860
3861 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3862 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3863 (FromAssignLeft != FromAssignRight))
3864 return FromAssignLeft? ImplicitConversionSequence::Better
3865 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003866 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003867 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003868
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003869 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003870 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3871 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3872 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003873 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003874 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003875 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003876 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003877 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003878 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003879 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003880 ToType2->getAs<MemberPointerType>();
3881 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3882 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3883 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3884 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3885 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3886 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3887 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3888 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003889 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003890 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003891 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003892 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003893 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003894 return ImplicitConversionSequence::Better;
3895 }
3896 // conversion of B::* to C::* is better than conversion of A::* to C::*
3897 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003898 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003899 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003900 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003901 return ImplicitConversionSequence::Worse;
3902 }
3903 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003904
Douglas Gregor5ab11652010-04-17 22:01:05 +00003905 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003906 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003907 // -- binding of an expression of type C to a reference of type
3908 // B& is better than binding an expression of type C to a
3909 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003910 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3911 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3912 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003913 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003914 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003915 return ImplicitConversionSequence::Worse;
3916 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003917
Douglas Gregor2fe98832008-11-03 19:09:14 +00003918 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003919 // -- binding of an expression of type B to a reference of type
3920 // A& is better than binding an expression of type C to a
3921 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003922 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3923 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3924 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003925 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003926 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003927 return ImplicitConversionSequence::Worse;
3928 }
3929 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003930
Douglas Gregor5c407d92008-10-23 00:40:37 +00003931 return ImplicitConversionSequence::Indistinguishable;
3932}
3933
Douglas Gregor45bb4832013-03-26 23:36:30 +00003934/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3935/// C++ class.
3936static bool isTypeValid(QualType T) {
3937 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3938 return !Record->isInvalidDecl();
3939
3940 return true;
3941}
3942
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003943/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3944/// determine whether they are reference-related,
3945/// reference-compatible, reference-compatible with added
3946/// qualification, or incompatible, for use in C++ initialization by
3947/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3948/// type, and the first type (T1) is the pointee type of the reference
3949/// type being initialized.
3950Sema::ReferenceCompareResult
3951Sema::CompareReferenceRelationship(SourceLocation Loc,
3952 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003953 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003954 bool &ObjCConversion,
3955 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003956 assert(!OrigT1->isReferenceType() &&
3957 "T1 must be the pointee type of the reference type");
3958 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3959
3960 QualType T1 = Context.getCanonicalType(OrigT1);
3961 QualType T2 = Context.getCanonicalType(OrigT2);
3962 Qualifiers T1Quals, T2Quals;
3963 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3964 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3965
3966 // C++ [dcl.init.ref]p4:
3967 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3968 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3969 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003970 DerivedToBase = false;
3971 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003972 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003973 if (UnqualT1 == UnqualT2) {
3974 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003975 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00003976 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3977 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003978 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003979 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3980 UnqualT2->isObjCObjectOrInterfaceType() &&
3981 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3982 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003983 else
3984 return Ref_Incompatible;
3985
3986 // At this point, we know that T1 and T2 are reference-related (at
3987 // least).
3988
3989 // If the type is an array type, promote the element qualifiers to the type
3990 // for comparison.
3991 if (isa<ArrayType>(T1) && T1Quals)
3992 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3993 if (isa<ArrayType>(T2) && T2Quals)
3994 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3995
3996 // C++ [dcl.init.ref]p4:
3997 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3998 // reference-related to T2 and cv1 is the same cv-qualification
3999 // as, or greater cv-qualification than, cv2. For purposes of
4000 // overload resolution, cases for which cv1 is greater
4001 // cv-qualification than cv2 are identified as
4002 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004003 //
4004 // Note that we also require equivalence of Objective-C GC and address-space
4005 // qualifiers when performing these computations, so that e.g., an int in
4006 // address space 1 is not reference-compatible with an int in address
4007 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004008 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4009 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004010 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4011 ObjCLifetimeConversion = true;
4012
John McCall31168b02011-06-15 23:02:42 +00004013 T1Quals.removeObjCLifetime();
4014 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004015 }
4016
Douglas Gregord517d552011-04-28 17:56:11 +00004017 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004018 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004019 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004020 return Ref_Compatible_With_Added_Qualification;
4021 else
4022 return Ref_Related;
4023}
4024
Douglas Gregor836a7e82010-08-11 02:15:33 +00004025/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004026/// with DeclType. Return true if something definite is found.
4027static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004028FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4029 QualType DeclType, SourceLocation DeclLoc,
4030 Expr *Init, QualType T2, bool AllowRvalues,
4031 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004032 assert(T2->isRecordType() && "Can only find conversions of record types.");
4033 CXXRecordDecl *T2RecordDecl
4034 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4035
Richard Smith100b24a2014-04-17 01:52:14 +00004036 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004037 std::pair<CXXRecordDecl::conversion_iterator,
4038 CXXRecordDecl::conversion_iterator>
4039 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4040 for (CXXRecordDecl::conversion_iterator
4041 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004042 NamedDecl *D = *I;
4043 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4044 if (isa<UsingShadowDecl>(D))
4045 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4046
4047 FunctionTemplateDecl *ConvTemplate
4048 = dyn_cast<FunctionTemplateDecl>(D);
4049 CXXConversionDecl *Conv;
4050 if (ConvTemplate)
4051 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4052 else
4053 Conv = cast<CXXConversionDecl>(D);
4054
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004055 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004056 // explicit conversions, skip it.
4057 if (!AllowExplicit && Conv->isExplicit())
4058 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004059
Douglas Gregor836a7e82010-08-11 02:15:33 +00004060 if (AllowRvalues) {
4061 bool DerivedToBase = false;
4062 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004063 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004064
4065 // If we are initializing an rvalue reference, don't permit conversion
4066 // functions that return lvalues.
4067 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4068 const ReferenceType *RefType
4069 = Conv->getConversionType()->getAs<LValueReferenceType>();
4070 if (RefType && !RefType->getPointeeType()->isFunctionType())
4071 continue;
4072 }
4073
Douglas Gregor836a7e82010-08-11 02:15:33 +00004074 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004075 S.CompareReferenceRelationship(
4076 DeclLoc,
4077 Conv->getConversionType().getNonReferenceType()
4078 .getUnqualifiedType(),
4079 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004080 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004081 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004082 continue;
4083 } else {
4084 // If the conversion function doesn't return a reference type,
4085 // it can't be considered for this conversion. An rvalue reference
4086 // is only acceptable if its referencee is a function type.
4087
4088 const ReferenceType *RefType =
4089 Conv->getConversionType()->getAs<ReferenceType>();
4090 if (!RefType ||
4091 (!RefType->isLValueReferenceType() &&
4092 !RefType->getPointeeType()->isFunctionType()))
4093 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004094 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004095
Douglas Gregor836a7e82010-08-11 02:15:33 +00004096 if (ConvTemplate)
4097 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004098 Init, DeclType, CandidateSet,
4099 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004100 else
4101 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004102 DeclType, CandidateSet,
4103 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004104 }
4105
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004106 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4107
Sebastian Redld92badf2010-06-30 18:13:39 +00004108 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004109 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004110 case OR_Success:
4111 // C++ [over.ics.ref]p1:
4112 //
4113 // [...] If the parameter binds directly to the result of
4114 // applying a conversion function to the argument
4115 // expression, the implicit conversion sequence is a
4116 // user-defined conversion sequence (13.3.3.1.2), with the
4117 // second standard conversion sequence either an identity
4118 // conversion or, if the conversion function returns an
4119 // entity of a type that is a derived class of the parameter
4120 // type, a derived-to-base Conversion.
4121 if (!Best->FinalConversion.DirectBinding)
4122 return false;
4123
4124 ICS.setUserDefined();
4125 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4126 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004127 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004128 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004129 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004130 ICS.UserDefined.EllipsisConversion = false;
4131 assert(ICS.UserDefined.After.ReferenceBinding &&
4132 ICS.UserDefined.After.DirectBinding &&
4133 "Expected a direct reference binding!");
4134 return true;
4135
4136 case OR_Ambiguous:
4137 ICS.setAmbiguous();
4138 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4139 Cand != CandidateSet.end(); ++Cand)
4140 if (Cand->Viable)
4141 ICS.Ambiguous.addConversion(Cand->Function);
4142 return true;
4143
4144 case OR_No_Viable_Function:
4145 case OR_Deleted:
4146 // There was no suitable conversion, or we found a deleted
4147 // conversion; continue with other checks.
4148 return false;
4149 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004150
David Blaikie8a40f702012-01-17 06:56:22 +00004151 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004152}
4153
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004154/// \brief Compute an implicit conversion sequence for reference
4155/// initialization.
4156static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004157TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004158 SourceLocation DeclLoc,
4159 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004160 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004161 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4162
4163 // Most paths end in a failed conversion.
4164 ImplicitConversionSequence ICS;
4165 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4166
4167 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4168 QualType T2 = Init->getType();
4169
4170 // If the initializer is the address of an overloaded function, try
4171 // to resolve the overloaded function. If all goes well, T2 is the
4172 // type of the resulting function.
4173 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4174 DeclAccessPair Found;
4175 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4176 false, Found))
4177 T2 = Fn->getType();
4178 }
4179
4180 // Compute some basic properties of the types and the initializer.
4181 bool isRValRef = DeclType->isRValueReferenceType();
4182 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004183 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004184 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004185 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004186 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004187 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004188 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004189
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004190
Sebastian Redld92badf2010-06-30 18:13:39 +00004191 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004192 // A reference to type "cv1 T1" is initialized by an expression
4193 // of type "cv2 T2" as follows:
4194
Sebastian Redld92badf2010-06-30 18:13:39 +00004195 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004196 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004197 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4198 // reference-compatible with "cv2 T2," or
4199 //
4200 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4201 if (InitCategory.isLValue() &&
4202 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004203 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004204 // When a parameter of reference type binds directly (8.5.3)
4205 // to an argument expression, the implicit conversion sequence
4206 // is the identity conversion, unless the argument expression
4207 // has a type that is a derived class of the parameter type,
4208 // in which case the implicit conversion sequence is a
4209 // derived-to-base Conversion (13.3.3.1).
4210 ICS.setStandard();
4211 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004212 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4213 : ObjCConversion? ICK_Compatible_Conversion
4214 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004215 ICS.Standard.Third = ICK_Identity;
4216 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4217 ICS.Standard.setToType(0, T2);
4218 ICS.Standard.setToType(1, T1);
4219 ICS.Standard.setToType(2, T1);
4220 ICS.Standard.ReferenceBinding = true;
4221 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004222 ICS.Standard.IsLvalueReference = !isRValRef;
4223 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4224 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004225 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004226 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004227 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004228 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004229
Sebastian Redld92badf2010-06-30 18:13:39 +00004230 // Nothing more to do: the inaccessibility/ambiguity check for
4231 // derived-to-base conversions is suppressed when we're
4232 // computing the implicit conversion sequence (C++
4233 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004234 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004235 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004236
Sebastian Redld92badf2010-06-30 18:13:39 +00004237 // -- has a class type (i.e., T2 is a class type), where T1 is
4238 // not reference-related to T2, and can be implicitly
4239 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4240 // is reference-compatible with "cv3 T3" 92) (this
4241 // conversion is selected by enumerating the applicable
4242 // conversion functions (13.3.1.6) and choosing the best
4243 // one through overload resolution (13.3)),
4244 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004245 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004246 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004247 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4248 Init, T2, /*AllowRvalues=*/false,
4249 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004250 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004251 }
4252 }
4253
Sebastian Redld92badf2010-06-30 18:13:39 +00004254 // -- Otherwise, the reference shall be an lvalue reference to a
4255 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004256 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004257 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004258 // We actually handle one oddity of C++ [over.ics.ref] at this
4259 // point, which is that, due to p2 (which short-circuits reference
4260 // binding by only attempting a simple conversion for non-direct
4261 // bindings) and p3's strange wording, we allow a const volatile
4262 // reference to bind to an rvalue. Hence the check for the presence
4263 // of "const" rather than checking for "const" being the only
4264 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004265 // This is also the point where rvalue references and lvalue inits no longer
4266 // go together.
Richard Smithce4f6082012-05-24 04:29:20 +00004267 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004268 return ICS;
4269
Douglas Gregorf143cd52011-01-24 16:14:37 +00004270 // -- If the initializer expression
4271 //
4272 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004273 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004274 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4275 (InitCategory.isXValue() ||
4276 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4277 (InitCategory.isLValue() && T2->isFunctionType()))) {
4278 ICS.setStandard();
4279 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004280 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004281 : ObjCConversion? ICK_Compatible_Conversion
4282 : ICK_Identity;
4283 ICS.Standard.Third = ICK_Identity;
4284 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4285 ICS.Standard.setToType(0, T2);
4286 ICS.Standard.setToType(1, T1);
4287 ICS.Standard.setToType(2, T1);
4288 ICS.Standard.ReferenceBinding = true;
4289 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4290 // binding unless we're binding to a class prvalue.
4291 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4292 // allow the use of rvalue references in C++98/03 for the benefit of
4293 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004294 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004295 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004296 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004297 ICS.Standard.IsLvalueReference = !isRValRef;
4298 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004300 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004301 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004302 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004303 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004304 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004305 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306
Douglas Gregorf143cd52011-01-24 16:14:37 +00004307 // -- has a class type (i.e., T2 is a class type), where T1 is not
4308 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004309 // an xvalue, class prvalue, or function lvalue of type
4310 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004311 // "cv3 T3",
4312 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004314 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004315 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004316 // class subobject).
4317 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004318 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004319 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4320 Init, T2, /*AllowRvalues=*/true,
4321 AllowExplicit)) {
4322 // In the second case, if the reference is an rvalue reference
4323 // and the second standard conversion sequence of the
4324 // user-defined conversion sequence includes an lvalue-to-rvalue
4325 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004326 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004327 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4328 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4329
Douglas Gregor95273c32011-01-21 16:36:05 +00004330 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004331 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004332
Richard Smith19172c42014-07-14 02:28:44 +00004333 // A temporary of function type cannot be created; don't even try.
4334 if (T1->isFunctionType())
4335 return ICS;
4336
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004337 // -- Otherwise, a temporary of type "cv1 T1" is created and
4338 // initialized from the initializer expression using the
4339 // rules for a non-reference copy initialization (8.5). The
4340 // reference is then bound to the temporary. If T1 is
4341 // reference-related to T2, cv1 must be the same
4342 // cv-qualification as, or greater cv-qualification than,
4343 // cv2; otherwise, the program is ill-formed.
4344 if (RefRelationship == Sema::Ref_Related) {
4345 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4346 // we would be reference-compatible or reference-compatible with
4347 // added qualification. But that wasn't the case, so the reference
4348 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004349 //
4350 // Note that we only want to check address spaces and cvr-qualifiers here.
4351 // ObjC GC and lifetime qualifiers aren't important.
4352 Qualifiers T1Quals = T1.getQualifiers();
4353 Qualifiers T2Quals = T2.getQualifiers();
4354 T1Quals.removeObjCGCAttr();
4355 T1Quals.removeObjCLifetime();
4356 T2Quals.removeObjCGCAttr();
4357 T2Quals.removeObjCLifetime();
4358 if (!T1Quals.compatiblyIncludes(T2Quals))
4359 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004360 }
4361
4362 // If at least one of the types is a class type, the types are not
4363 // related, and we aren't allowed any user conversions, the
4364 // reference binding fails. This case is important for breaking
4365 // recursion, since TryImplicitConversion below will attempt to
4366 // create a temporary through the use of a copy constructor.
4367 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4368 (T1->isRecordType() || T2->isRecordType()))
4369 return ICS;
4370
Douglas Gregorcba72b12011-01-21 05:18:22 +00004371 // If T1 is reference-related to T2 and the reference is an rvalue
4372 // reference, the initializer expression shall not be an lvalue.
4373 if (RefRelationship >= Sema::Ref_Related &&
4374 isRValRef && Init->Classify(S.Context).isLValue())
4375 return ICS;
4376
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004377 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004378 // When a parameter of reference type is not bound directly to
4379 // an argument expression, the conversion sequence is the one
4380 // required to convert the argument expression to the
4381 // underlying type of the reference according to
4382 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4383 // to copy-initializing a temporary of the underlying type with
4384 // the argument expression. Any difference in top-level
4385 // cv-qualification is subsumed by the initialization itself
4386 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004387 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4388 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004389 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004390 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004391 /*AllowObjCWritebackConversion=*/false,
4392 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004393
4394 // Of course, that's still a reference binding.
4395 if (ICS.isStandard()) {
4396 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004397 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004398 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004399 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004400 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004401 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004402 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004403 const ReferenceType *LValRefType =
4404 ICS.UserDefined.ConversionFunction->getReturnType()
4405 ->getAs<LValueReferenceType>();
4406
4407 // C++ [over.ics.ref]p3:
4408 // Except for an implicit object parameter, for which see 13.3.1, a
4409 // standard conversion sequence cannot be formed if it requires [...]
4410 // binding an rvalue reference to an lvalue other than a function
4411 // lvalue.
4412 // Note that the function case is not possible here.
4413 if (DeclType->isRValueReferenceType() && LValRefType) {
4414 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4415 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4416 // reference to an rvalue!
4417 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4418 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004419 }
Richard Smith19172c42014-07-14 02:28:44 +00004420
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004421 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004422 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004423 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004424 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4425 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004426 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4427 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004428 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004429
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004430 return ICS;
4431}
4432
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004433static ImplicitConversionSequence
4434TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4435 bool SuppressUserConversions,
4436 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004437 bool AllowObjCWritebackConversion,
4438 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004439
4440/// TryListConversion - Try to copy-initialize a value of type ToType from the
4441/// initializer list From.
4442static ImplicitConversionSequence
4443TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4444 bool SuppressUserConversions,
4445 bool InOverloadResolution,
4446 bool AllowObjCWritebackConversion) {
4447 // C++11 [over.ics.list]p1:
4448 // When an argument is an initializer list, it is not an expression and
4449 // special rules apply for converting it to a parameter type.
4450
4451 ImplicitConversionSequence Result;
4452 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4453
Sebastian Redl09edce02012-01-23 22:09:39 +00004454 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004455 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004456 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004457 return Result;
4458
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004459 // C++11 [over.ics.list]p2:
4460 // If the parameter type is std::initializer_list<X> or "array of X" and
4461 // all the elements can be implicitly converted to X, the implicit
4462 // conversion sequence is the worst conversion necessary to convert an
4463 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004464 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004465 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004466 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004467 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004468 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004469 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004470 if (!X.isNull()) {
4471 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4472 Expr *Init = From->getInit(i);
4473 ImplicitConversionSequence ICS =
4474 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4475 InOverloadResolution,
4476 AllowObjCWritebackConversion);
4477 // If a single element isn't convertible, fail.
4478 if (ICS.isBad()) {
4479 Result = ICS;
4480 break;
4481 }
4482 // Otherwise, look for the worst conversion.
4483 if (Result.isBad() ||
4484 CompareImplicitConversionSequences(S, ICS, Result) ==
4485 ImplicitConversionSequence::Worse)
4486 Result = ICS;
4487 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004488
4489 // For an empty list, we won't have computed any conversion sequence.
4490 // Introduce the identity conversion sequence.
4491 if (From->getNumInits() == 0) {
4492 Result.setStandard();
4493 Result.Standard.setAsIdentityConversion();
4494 Result.Standard.setFromType(ToType);
4495 Result.Standard.setAllToTypes(ToType);
4496 }
4497
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004498 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004499 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004500 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004501
4502 // C++11 [over.ics.list]p3:
4503 // Otherwise, if the parameter is a non-aggregate class X and overload
4504 // resolution chooses a single best constructor [...] the implicit
4505 // conversion sequence is a user-defined conversion sequence. If multiple
4506 // constructors are viable but none is better than the others, the
4507 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004508 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4509 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004510 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4511 /*AllowExplicit=*/false,
4512 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004513 AllowObjCWritebackConversion,
4514 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004515 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004516
4517 // C++11 [over.ics.list]p4:
4518 // Otherwise, if the parameter has an aggregate type which can be
4519 // initialized from the initializer list [...] the implicit conversion
4520 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004521 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004522 // Type is an aggregate, argument is an init list. At this point it comes
4523 // down to checking whether the initialization works.
4524 // FIXME: Find out whether this parameter is consumed or not.
4525 InitializedEntity Entity =
4526 InitializedEntity::InitializeParameter(S.Context, ToType,
4527 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004528 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004529 Result.setUserDefined();
4530 Result.UserDefined.Before.setAsIdentityConversion();
4531 // Initializer lists don't have a type.
4532 Result.UserDefined.Before.setFromType(QualType());
4533 Result.UserDefined.Before.setAllToTypes(QualType());
4534
4535 Result.UserDefined.After.setAsIdentityConversion();
4536 Result.UserDefined.After.setFromType(ToType);
4537 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004538 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004539 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004540 return Result;
4541 }
4542
4543 // C++11 [over.ics.list]p5:
4544 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004545 if (ToType->isReferenceType()) {
4546 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4547 // mention initializer lists in any way. So we go by what list-
4548 // initialization would do and try to extrapolate from that.
4549
4550 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4551
4552 // If the initializer list has a single element that is reference-related
4553 // to the parameter type, we initialize the reference from that.
4554 if (From->getNumInits() == 1) {
4555 Expr *Init = From->getInit(0);
4556
4557 QualType T2 = Init->getType();
4558
4559 // If the initializer is the address of an overloaded function, try
4560 // to resolve the overloaded function. If all goes well, T2 is the
4561 // type of the resulting function.
4562 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4563 DeclAccessPair Found;
4564 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4565 Init, ToType, false, Found))
4566 T2 = Fn->getType();
4567 }
4568
4569 // Compute some basic properties of the types and the initializer.
4570 bool dummy1 = false;
4571 bool dummy2 = false;
4572 bool dummy3 = false;
4573 Sema::ReferenceCompareResult RefRelationship
4574 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4575 dummy2, dummy3);
4576
Richard Smith4d2bbd72013-09-06 01:22:42 +00004577 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004578 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4579 SuppressUserConversions,
4580 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004581 }
Sebastian Redldf888642011-12-03 14:54:30 +00004582 }
4583
4584 // Otherwise, we bind the reference to a temporary created from the
4585 // initializer list.
4586 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4587 InOverloadResolution,
4588 AllowObjCWritebackConversion);
4589 if (Result.isFailure())
4590 return Result;
4591 assert(!Result.isEllipsis() &&
4592 "Sub-initialization cannot result in ellipsis conversion.");
4593
4594 // Can we even bind to a temporary?
4595 if (ToType->isRValueReferenceType() ||
4596 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4597 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4598 Result.UserDefined.After;
4599 SCS.ReferenceBinding = true;
4600 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4601 SCS.BindsToRvalue = true;
4602 SCS.BindsToFunctionLvalue = false;
4603 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4604 SCS.ObjCLifetimeConversionBinding = false;
4605 } else
4606 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4607 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004608 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004609 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004610
4611 // C++11 [over.ics.list]p6:
4612 // Otherwise, if the parameter type is not a class:
4613 if (!ToType->isRecordType()) {
4614 // - if the initializer list has one element, the implicit conversion
4615 // sequence is the one required to convert the element to the
4616 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004617 unsigned NumInits = From->getNumInits();
4618 if (NumInits == 1)
4619 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4620 SuppressUserConversions,
4621 InOverloadResolution,
4622 AllowObjCWritebackConversion);
4623 // - if the initializer list has no elements, the implicit conversion
4624 // sequence is the identity conversion.
4625 else if (NumInits == 0) {
4626 Result.setStandard();
4627 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004628 Result.Standard.setFromType(ToType);
4629 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004630 }
4631 return Result;
4632 }
4633
4634 // C++11 [over.ics.list]p7:
4635 // In all cases other than those enumerated above, no conversion is possible
4636 return Result;
4637}
4638
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004639/// TryCopyInitialization - Try to copy-initialize a value of type
4640/// ToType from the expression From. Return the implicit conversion
4641/// sequence required to pass this argument, which may be a bad
4642/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004643/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004644/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004645static ImplicitConversionSequence
4646TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004647 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004648 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004649 bool AllowObjCWritebackConversion,
4650 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004651 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4652 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4653 InOverloadResolution,AllowObjCWritebackConversion);
4654
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004655 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004656 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004657 /*FIXME:*/From->getLocStart(),
4658 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004659 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004660
John McCall5c32be02010-08-24 20:38:10 +00004661 return TryImplicitConversion(S, From, ToType,
4662 SuppressUserConversions,
4663 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004664 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004665 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004666 AllowObjCWritebackConversion,
4667 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004668}
4669
Anna Zaks1b068122011-07-28 19:46:48 +00004670static bool TryCopyInitialization(const CanQualType FromQTy,
4671 const CanQualType ToQTy,
4672 Sema &S,
4673 SourceLocation Loc,
4674 ExprValueKind FromVK) {
4675 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4676 ImplicitConversionSequence ICS =
4677 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4678
4679 return !ICS.isBad();
4680}
4681
Douglas Gregor436424c2008-11-18 23:14:02 +00004682/// TryObjectArgumentInitialization - Try to initialize the object
4683/// parameter of the given member function (@c Method) from the
4684/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004685static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004686TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004687 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004688 CXXMethodDecl *Method,
4689 CXXRecordDecl *ActingContext) {
4690 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004691 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4692 // const volatile object.
4693 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4694 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004695 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004696
4697 // Set up the conversion sequence as a "bad" conversion, to allow us
4698 // to exit early.
4699 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004700
4701 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004702 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004703 FromType = PT->getPointeeType();
4704
Douglas Gregor02824322011-01-26 19:30:28 +00004705 // When we had a pointer, it's implicitly dereferenced, so we
4706 // better have an lvalue.
4707 assert(FromClassification.isLValue());
4708 }
4709
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004710 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004711
Douglas Gregor02824322011-01-26 19:30:28 +00004712 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004713 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004714 // parameter is
4715 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004716 // - "lvalue reference to cv X" for functions declared without a
4717 // ref-qualifier or with the & ref-qualifier
4718 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004719 // ref-qualifier
4720 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004721 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004722 // cv-qualification on the member function declaration.
4723 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004724 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004725 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004726 // (C++ [over.match.funcs]p5). We perform a simplified version of
4727 // reference binding here, that allows class rvalues to bind to
4728 // non-constant references.
4729
Douglas Gregor02824322011-01-26 19:30:28 +00004730 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004731 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004732 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004733 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004734 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004735 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004736 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004737 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004738 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004739
4740 // Check that we have either the same type or a derived type. It
4741 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004742 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004743 ImplicitConversionKind SecondKind;
4744 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4745 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004746 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004747 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004748 else {
John McCall65eb8792010-02-25 01:37:24 +00004749 ICS.setBad(BadConversionSequence::unrelated_class,
4750 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004751 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004752 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004753
Douglas Gregor02824322011-01-26 19:30:28 +00004754 // Check the ref-qualifier.
4755 switch (Method->getRefQualifier()) {
4756 case RQ_None:
4757 // Do nothing; we don't care about lvalueness or rvalueness.
4758 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004759
Douglas Gregor02824322011-01-26 19:30:28 +00004760 case RQ_LValue:
4761 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4762 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004763 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004764 ImplicitParamType);
4765 return ICS;
4766 }
4767 break;
4768
4769 case RQ_RValue:
4770 if (!FromClassification.isRValue()) {
4771 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004772 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004773 ImplicitParamType);
4774 return ICS;
4775 }
4776 break;
4777 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004778
Douglas Gregor436424c2008-11-18 23:14:02 +00004779 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004780 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004781 ICS.Standard.setAsIdentityConversion();
4782 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004783 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004784 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004785 ICS.Standard.ReferenceBinding = true;
4786 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004787 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004788 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004789 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4790 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4791 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004792 return ICS;
4793}
4794
4795/// PerformObjectArgumentInitialization - Perform initialization of
4796/// the implicit object parameter for the given Method with the given
4797/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004798ExprResult
4799Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004800 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004801 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004802 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004803 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004804 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004805 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004806
Douglas Gregor02824322011-01-26 19:30:28 +00004807 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004808 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004809 FromRecordType = PT->getPointeeType();
4810 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004811 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004812 } else {
4813 FromRecordType = From->getType();
4814 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004815 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004816 }
4817
John McCall6e9f8f62009-12-03 04:06:58 +00004818 // Note that we always use the true parent context when performing
4819 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004820 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004821 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4822 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004823 if (ICS.isBad()) {
4824 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4825 Qualifiers FromQs = FromRecordType.getQualifiers();
4826 Qualifiers ToQs = DestType.getQualifiers();
4827 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4828 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004829 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004830 diag::err_member_function_call_bad_cvr)
4831 << Method->getDeclName() << FromRecordType << (CVR - 1)
4832 << From->getSourceRange();
4833 Diag(Method->getLocation(), diag::note_previous_decl)
4834 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004835 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004836 }
4837 }
4838
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004839 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004840 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004841 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004842 }
Mike Stump11289f42009-09-09 15:08:12 +00004843
John Wiegley01296292011-04-08 18:41:53 +00004844 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4845 ExprResult FromRes =
4846 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4847 if (FromRes.isInvalid())
4848 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004849 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00004850 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004851
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004852 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004853 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004854 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004855 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00004856}
4857
Douglas Gregor5fb53972009-01-14 15:45:31 +00004858/// TryContextuallyConvertToBool - Attempt to contextually convert the
4859/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004860static ImplicitConversionSequence
4861TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004862 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004863 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004864 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004865 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004866 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004867 /*AllowObjCWritebackConversion=*/false,
4868 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004869}
4870
4871/// PerformContextuallyConvertToBool - Perform a contextual conversion
4872/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004873ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004874 if (checkPlaceholderForOverload(*this, From))
4875 return ExprError();
4876
John McCall5c32be02010-08-24 20:38:10 +00004877 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004878 if (!ICS.isBad())
4879 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004880
Fariborz Jahanian76197412009-11-18 18:26:29 +00004881 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004882 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004883 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004884 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004885 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004886}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004887
Richard Smithf8379a02012-01-18 23:55:52 +00004888/// Check that the specified conversion is permitted in a converted constant
4889/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4890/// is acceptable.
4891static bool CheckConvertedConstantConversions(Sema &S,
4892 StandardConversionSequence &SCS) {
4893 // Since we know that the target type is an integral or unscoped enumeration
4894 // type, most conversion kinds are impossible. All possible First and Third
4895 // conversions are fine.
4896 switch (SCS.Second) {
4897 case ICK_Identity:
4898 case ICK_Integral_Promotion:
4899 case ICK_Integral_Conversion:
Guy Benyei259f9f42013-02-07 16:05:33 +00004900 case ICK_Zero_Event_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004901 return true;
4902
4903 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004904 // Conversion from an integral or unscoped enumeration type to bool is
4905 // classified as ICK_Boolean_Conversion, but it's also an integral
4906 // conversion, so it's permitted in a converted constant expression.
4907 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4908 SCS.getToType(2)->isBooleanType();
4909
Richard Smithf8379a02012-01-18 23:55:52 +00004910 case ICK_Floating_Integral:
4911 case ICK_Complex_Real:
4912 return false;
4913
4914 case ICK_Lvalue_To_Rvalue:
4915 case ICK_Array_To_Pointer:
4916 case ICK_Function_To_Pointer:
4917 case ICK_NoReturn_Adjustment:
4918 case ICK_Qualification:
4919 case ICK_Compatible_Conversion:
4920 case ICK_Vector_Conversion:
4921 case ICK_Vector_Splat:
4922 case ICK_Derived_To_Base:
4923 case ICK_Pointer_Conversion:
4924 case ICK_Pointer_Member:
4925 case ICK_Block_Pointer_Conversion:
4926 case ICK_Writeback_Conversion:
4927 case ICK_Floating_Promotion:
4928 case ICK_Complex_Promotion:
4929 case ICK_Complex_Conversion:
4930 case ICK_Floating_Conversion:
4931 case ICK_TransparentUnionConversion:
4932 llvm_unreachable("unexpected second conversion kind");
4933
4934 case ICK_Num_Conversion_Kinds:
4935 break;
4936 }
4937
4938 llvm_unreachable("unknown conversion kind");
4939}
4940
4941/// CheckConvertedConstantExpression - Check that the expression From is a
4942/// converted constant expression of type T, perform the conversion and produce
4943/// the converted expression, per C++11 [expr.const]p3.
4944ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4945 llvm::APSInt &Value,
4946 CCEKind CCE) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004947 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00004948 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4949
4950 if (checkPlaceholderForOverload(*this, From))
4951 return ExprError();
4952
4953 // C++11 [expr.const]p3 with proposed wording fixes:
4954 // A converted constant expression of type T is a core constant expression,
4955 // implicitly converted to a prvalue of type T, where the converted
4956 // expression is a literal constant expression and the implicit conversion
4957 // sequence contains only user-defined conversions, lvalue-to-rvalue
4958 // conversions, integral promotions, and integral conversions other than
4959 // narrowing conversions.
4960 ImplicitConversionSequence ICS =
4961 TryImplicitConversion(From, T,
4962 /*SuppressUserConversions=*/false,
4963 /*AllowExplicit=*/false,
4964 /*InOverloadResolution=*/false,
4965 /*CStyle=*/false,
4966 /*AllowObjcWritebackConversion=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00004967 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00004968 switch (ICS.getKind()) {
4969 case ImplicitConversionSequence::StandardConversion:
4970 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004971 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004972 diag::err_typecheck_converted_constant_expression_disallowed)
4973 << From->getType() << From->getSourceRange() << T;
4974 SCS = &ICS.Standard;
4975 break;
4976 case ImplicitConversionSequence::UserDefinedConversion:
4977 // We are converting from class type to an integral or enumeration type, so
4978 // the Before sequence must be trivial.
4979 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004980 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004981 diag::err_typecheck_converted_constant_expression_disallowed)
4982 << From->getType() << From->getSourceRange() << T;
4983 SCS = &ICS.UserDefined.After;
4984 break;
4985 case ImplicitConversionSequence::AmbiguousConversion:
4986 case ImplicitConversionSequence::BadConversion:
4987 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004988 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004989 diag::err_typecheck_converted_constant_expression)
4990 << From->getType() << From->getSourceRange() << T;
4991 return ExprError();
4992
4993 case ImplicitConversionSequence::EllipsisConversion:
4994 llvm_unreachable("ellipsis conversion in converted constant expression");
4995 }
4996
4997 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4998 if (Result.isInvalid())
4999 return Result;
5000
5001 // Check for a narrowing implicit conversion.
5002 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005003 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00005004 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
5005 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005006 case NK_Variable_Narrowing:
5007 // Implicit conversion to a narrower type, and the value is not a constant
5008 // expression. We'll diagnose this in a moment.
5009 case NK_Not_Narrowing:
5010 break;
5011
5012 case NK_Constant_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005013 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005014 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00005015 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005016 break;
5017
5018 case NK_Type_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005019 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005020 << CCE << /*Constant*/0 << From->getType() << T;
5021 break;
5022 }
5023
5024 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005025 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005026 Expr::EvalResult Eval;
5027 Eval.Diag = &Notes;
5028
Douglas Gregorebe2db72013-04-08 23:24:07 +00005029 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005030 // The expression can't be folded, so we can't keep it at this position in
5031 // the AST.
5032 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005033 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00005034 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00005035
5036 if (Notes.empty()) {
5037 // It's a constant expression.
5038 return Result;
5039 }
Richard Smithf8379a02012-01-18 23:55:52 +00005040 }
5041
5042 // It's not a constant expression. Produce an appropriate diagnostic.
5043 if (Notes.size() == 1 &&
5044 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5045 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5046 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005047 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005048 << CCE << From->getSourceRange();
5049 for (unsigned I = 0; I < Notes.size(); ++I)
5050 Diag(Notes[I].first, Notes[I].second);
5051 }
Richard Smith911e1422012-01-30 22:27:01 +00005052 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00005053}
5054
John McCallfec112d2011-09-09 06:11:02 +00005055/// dropPointerConversions - If the given standard conversion sequence
5056/// involves any pointer conversions, remove them. This may change
5057/// the result type of the conversion sequence.
5058static void dropPointerConversion(StandardConversionSequence &SCS) {
5059 if (SCS.Second == ICK_Pointer_Conversion) {
5060 SCS.Second = ICK_Identity;
5061 SCS.Third = ICK_Identity;
5062 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5063 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005064}
John McCall5c32be02010-08-24 20:38:10 +00005065
John McCallfec112d2011-09-09 06:11:02 +00005066/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5067/// convert the expression From to an Objective-C pointer type.
5068static ImplicitConversionSequence
5069TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5070 // Do an implicit conversion to 'id'.
5071 QualType Ty = S.Context.getObjCIdType();
5072 ImplicitConversionSequence ICS
5073 = TryImplicitConversion(S, From, Ty,
5074 // FIXME: Are these flags correct?
5075 /*SuppressUserConversions=*/false,
5076 /*AllowExplicit=*/true,
5077 /*InOverloadResolution=*/false,
5078 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005079 /*AllowObjCWritebackConversion=*/false,
5080 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005081
5082 // Strip off any final conversions to 'id'.
5083 switch (ICS.getKind()) {
5084 case ImplicitConversionSequence::BadConversion:
5085 case ImplicitConversionSequence::AmbiguousConversion:
5086 case ImplicitConversionSequence::EllipsisConversion:
5087 break;
5088
5089 case ImplicitConversionSequence::UserDefinedConversion:
5090 dropPointerConversion(ICS.UserDefined.After);
5091 break;
5092
5093 case ImplicitConversionSequence::StandardConversion:
5094 dropPointerConversion(ICS.Standard);
5095 break;
5096 }
5097
5098 return ICS;
5099}
5100
5101/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5102/// conversion of the expression From to an Objective-C pointer type.
5103ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005104 if (checkPlaceholderForOverload(*this, From))
5105 return ExprError();
5106
John McCall8b07ec22010-05-15 11:32:37 +00005107 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005108 ImplicitConversionSequence ICS =
5109 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005110 if (!ICS.isBad())
5111 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005112 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005113}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005114
Richard Smith8dd34252012-02-04 07:07:42 +00005115/// Determine whether the provided type is an integral type, or an enumeration
5116/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005117bool Sema::ICEConvertDiagnoser::match(QualType T) {
5118 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5119 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005120}
5121
Larisse Voufo236bec22013-06-10 06:50:24 +00005122static ExprResult
5123diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5124 Sema::ContextualImplicitConverter &Converter,
5125 QualType T, UnresolvedSetImpl &ViableConversions) {
5126
5127 if (Converter.Suppress)
5128 return ExprError();
5129
5130 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5131 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5132 CXXConversionDecl *Conv =
5133 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5134 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5135 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5136 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005137 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005138}
5139
5140static bool
5141diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5142 Sema::ContextualImplicitConverter &Converter,
5143 QualType T, bool HadMultipleCandidates,
5144 UnresolvedSetImpl &ExplicitConversions) {
5145 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5146 DeclAccessPair Found = ExplicitConversions[0];
5147 CXXConversionDecl *Conversion =
5148 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5149
5150 // The user probably meant to invoke the given explicit
5151 // conversion; use it.
5152 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5153 std::string TypeStr;
5154 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5155
5156 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5157 << FixItHint::CreateInsertion(From->getLocStart(),
5158 "static_cast<" + TypeStr + ">(")
5159 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005160 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005161 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5162
5163 // If we aren't in a SFINAE context, build a call to the
5164 // explicit conversion function.
5165 if (SemaRef.isSFINAEContext())
5166 return true;
5167
Craig Topperc3ec1492014-05-26 06:22:03 +00005168 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005169 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5170 HadMultipleCandidates);
5171 if (Result.isInvalid())
5172 return true;
5173 // Record usage of conversion in an implicit cast.
5174 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005175 CK_UserDefinedConversion, Result.get(),
5176 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005177 }
5178 return false;
5179}
5180
5181static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5182 Sema::ContextualImplicitConverter &Converter,
5183 QualType T, bool HadMultipleCandidates,
5184 DeclAccessPair &Found) {
5185 CXXConversionDecl *Conversion =
5186 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005187 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005188
5189 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5190 if (!Converter.SuppressConversion) {
5191 if (SemaRef.isSFINAEContext())
5192 return true;
5193
5194 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5195 << From->getSourceRange();
5196 }
5197
5198 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5199 HadMultipleCandidates);
5200 if (Result.isInvalid())
5201 return true;
5202 // Record usage of conversion in an implicit cast.
5203 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005204 CK_UserDefinedConversion, Result.get(),
5205 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005206 return false;
5207}
5208
5209static ExprResult finishContextualImplicitConversion(
5210 Sema &SemaRef, SourceLocation Loc, Expr *From,
5211 Sema::ContextualImplicitConverter &Converter) {
5212 if (!Converter.match(From->getType()) && !Converter.Suppress)
5213 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5214 << From->getSourceRange();
5215
5216 return SemaRef.DefaultLvalueConversion(From);
5217}
5218
5219static void
5220collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5221 UnresolvedSetImpl &ViableConversions,
5222 OverloadCandidateSet &CandidateSet) {
5223 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5224 DeclAccessPair FoundDecl = ViableConversions[I];
5225 NamedDecl *D = FoundDecl.getDecl();
5226 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5227 if (isa<UsingShadowDecl>(D))
5228 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5229
5230 CXXConversionDecl *Conv;
5231 FunctionTemplateDecl *ConvTemplate;
5232 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5233 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5234 else
5235 Conv = cast<CXXConversionDecl>(D);
5236
5237 if (ConvTemplate)
5238 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005239 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5240 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005241 else
5242 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005243 ToType, CandidateSet,
5244 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005245 }
5246}
5247
Richard Smithccc11812013-05-21 19:05:48 +00005248/// \brief Attempt to convert the given expression to a type which is accepted
5249/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005250///
Richard Smithccc11812013-05-21 19:05:48 +00005251/// This routine will attempt to convert an expression of class type to a
5252/// type accepted by the specified converter. In C++11 and before, the class
5253/// must have a single non-explicit conversion function converting to a matching
5254/// type. In C++1y, there can be multiple such conversion functions, but only
5255/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005256///
Douglas Gregor4799d032010-06-30 00:20:43 +00005257/// \param Loc The source location of the construct that requires the
5258/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005259///
James Dennett18348b62012-06-22 08:52:37 +00005260/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005261///
Richard Smithccc11812013-05-21 19:05:48 +00005262/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005263///
Douglas Gregor4799d032010-06-30 00:20:43 +00005264/// \returns The expression, converted to an integral or enumeration type if
5265/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005266ExprResult Sema::PerformContextualImplicitConversion(
5267 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005268 // We can't perform any more checking for type-dependent expressions.
5269 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005270 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005271
Eli Friedman1da70392012-01-26 00:26:18 +00005272 // Process placeholders immediately.
5273 if (From->hasPlaceholderType()) {
5274 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005275 if (result.isInvalid())
5276 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005277 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005278 }
5279
Richard Smithccc11812013-05-21 19:05:48 +00005280 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005281 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005282 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005283 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005284
5285 // FIXME: Check for missing '()' if T is a function type?
5286
Richard Smithccc11812013-05-21 19:05:48 +00005287 // We can only perform contextual implicit conversions on objects of class
5288 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005289 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005290 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005291 if (!Converter.Suppress)
5292 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005293 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005294 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005295
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005296 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005297 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005298 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005299 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005300
5301 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5302 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5303
Craig Toppere14c0f82014-03-12 04:55:44 +00005304 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005305 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005306 }
Richard Smithccc11812013-05-21 19:05:48 +00005307 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005308
5309 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005310 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005311
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005312 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005313 UnresolvedSet<4>
5314 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005315 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005316 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo236bec22013-06-10 06:50:24 +00005317 CXXRecordDecl::conversion_iterator> Conversions =
5318 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005319
Larisse Voufo236bec22013-06-10 06:50:24 +00005320 bool HadMultipleCandidates =
5321 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005322
Larisse Voufo236bec22013-06-10 06:50:24 +00005323 // To check that there is only one target type, in C++1y:
5324 QualType ToType;
5325 bool HasUniqueTargetType = true;
5326
5327 // Collect explicit or viable (potentially in C++1y) conversions.
5328 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5329 E = Conversions.second;
5330 I != E; ++I) {
5331 NamedDecl *D = (*I)->getUnderlyingDecl();
5332 CXXConversionDecl *Conversion;
5333 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5334 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005335 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005336 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5337 else
5338 continue; // C++11 does not consider conversion operator templates(?).
5339 } else
5340 Conversion = cast<CXXConversionDecl>(D);
5341
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005342 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005343 "Conversion operator templates are considered potentially "
5344 "viable in C++1y");
5345
5346 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5347 if (Converter.match(CurToType) || ConvTemplate) {
5348
5349 if (Conversion->isExplicit()) {
5350 // FIXME: For C++1y, do we need this restriction?
5351 // cf. diagnoseNoViableConversion()
5352 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005353 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005354 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005355 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005356 if (ToType.isNull())
5357 ToType = CurToType.getUnqualifiedType();
5358 else if (HasUniqueTargetType &&
5359 (CurToType.getUnqualifiedType() != ToType))
5360 HasUniqueTargetType = false;
5361 }
5362 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005363 }
Richard Smith8dd34252012-02-04 07:07:42 +00005364 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005365 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005366
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005367 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005368 // C++1y [conv]p6:
5369 // ... An expression e of class type E appearing in such a context
5370 // is said to be contextually implicitly converted to a specified
5371 // type T and is well-formed if and only if e can be implicitly
5372 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005373 // for conversion functions whose return type is cv T or reference to
5374 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005375 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005376
Larisse Voufo236bec22013-06-10 06:50:24 +00005377 // If no unique T is found:
5378 if (ToType.isNull()) {
5379 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5380 HadMultipleCandidates,
5381 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005382 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005383 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005384 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005385
Larisse Voufo236bec22013-06-10 06:50:24 +00005386 // If more than one unique Ts are found:
5387 if (!HasUniqueTargetType)
5388 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5389 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005390
Larisse Voufo236bec22013-06-10 06:50:24 +00005391 // If one unique T is found:
5392 // First, build a candidate set from the previously recorded
5393 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005394 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005395 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5396 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005397
Larisse Voufo236bec22013-06-10 06:50:24 +00005398 // Then, perform overload resolution over the candidate set.
5399 OverloadCandidateSet::iterator Best;
5400 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5401 case OR_Success: {
5402 // Apply this conversion.
5403 DeclAccessPair Found =
5404 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5405 if (recordConversion(*this, Loc, From, Converter, T,
5406 HadMultipleCandidates, Found))
5407 return ExprError();
5408 break;
5409 }
5410 case OR_Ambiguous:
5411 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5412 ViableConversions);
5413 case OR_No_Viable_Function:
5414 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5415 HadMultipleCandidates,
5416 ExplicitConversions))
5417 return ExprError();
5418 // fall through 'OR_Deleted' case.
5419 case OR_Deleted:
5420 // We'll complain below about a non-integral condition type.
5421 break;
5422 }
5423 } else {
5424 switch (ViableConversions.size()) {
5425 case 0: {
5426 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5427 HadMultipleCandidates,
5428 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005429 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005430
Larisse Voufo236bec22013-06-10 06:50:24 +00005431 // We'll complain below about a non-integral condition type.
5432 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005433 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005434 case 1: {
5435 // Apply this conversion.
5436 DeclAccessPair Found = ViableConversions[0];
5437 if (recordConversion(*this, Loc, From, Converter, T,
5438 HadMultipleCandidates, Found))
5439 return ExprError();
5440 break;
5441 }
5442 default:
5443 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5444 ViableConversions);
5445 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005446 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005447
Larisse Voufo236bec22013-06-10 06:50:24 +00005448 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005449}
5450
Richard Smith100b24a2014-04-17 01:52:14 +00005451/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5452/// an acceptable non-member overloaded operator for a call whose
5453/// arguments have types T1 (and, if non-empty, T2). This routine
5454/// implements the check in C++ [over.match.oper]p3b2 concerning
5455/// enumeration types.
5456static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5457 FunctionDecl *Fn,
5458 ArrayRef<Expr *> Args) {
5459 QualType T1 = Args[0]->getType();
5460 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5461
5462 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5463 return true;
5464
5465 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5466 return true;
5467
5468 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5469 if (Proto->getNumParams() < 1)
5470 return false;
5471
5472 if (T1->isEnumeralType()) {
5473 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5474 if (Context.hasSameUnqualifiedType(T1, ArgType))
5475 return true;
5476 }
5477
5478 if (Proto->getNumParams() < 2)
5479 return false;
5480
5481 if (!T2.isNull() && T2->isEnumeralType()) {
5482 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5483 if (Context.hasSameUnqualifiedType(T2, ArgType))
5484 return true;
5485 }
5486
5487 return false;
5488}
5489
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005490/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005491/// candidate functions, using the given function call arguments. If
5492/// @p SuppressUserConversions, then don't allow user-defined
5493/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005494///
James Dennett2a4d13c2012-06-15 07:13:21 +00005495/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005496/// based on an incomplete set of function arguments. This feature is used by
5497/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005498void
5499Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005500 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005501 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005502 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005503 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005504 bool PartialOverloading,
5505 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005506 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005507 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005508 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005509 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005510 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005511
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005512 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005513 if (!isa<CXXConstructorDecl>(Method)) {
5514 // If we get here, it's because we're calling a member function
5515 // that is named without a member access expression (e.g.,
5516 // "this->f") that was either written explicitly or created
5517 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005518 // function, e.g., X::f(). We use an empty type for the implied
5519 // object argument (C++ [over.call.func]p3), and the acting context
5520 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005521 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005522 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005523 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005524 return;
5525 }
5526 // We treat a constructor like a non-member function, since its object
5527 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005528 }
5529
Douglas Gregorff7028a2009-11-13 23:59:09 +00005530 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005531 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005532
Richard Smith100b24a2014-04-17 01:52:14 +00005533 // C++ [over.match.oper]p3:
5534 // if no operand has a class type, only those non-member functions in the
5535 // lookup set that have a first parameter of type T1 or "reference to
5536 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5537 // is a right operand) a second parameter of type T2 or "reference to
5538 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5539 // candidate functions.
5540 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5541 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5542 return;
5543
Richard Smith8b86f2d2013-11-04 01:48:18 +00005544 // C++11 [class.copy]p11: [DR1402]
5545 // A defaulted move constructor that is defined as deleted is ignored by
5546 // overload resolution.
5547 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5548 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5549 Constructor->isMoveConstructor())
5550 return;
5551
Douglas Gregor27381f32009-11-23 12:27:39 +00005552 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005553 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005554
Richard Smith8b86f2d2013-11-04 01:48:18 +00005555 if (Constructor) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00005556 // C++ [class.copy]p3:
5557 // A member function template is never instantiated to perform the copy
5558 // of a class object to an object of its class type.
5559 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005560 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005561 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005562 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5563 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005564 return;
5565 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005566
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005567 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005568 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005569 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005570 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005571 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005572 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005573 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005574 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005575
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005576 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005577
5578 // (C++ 13.3.2p2): A candidate function having fewer than m
5579 // parameters is viable only if it has an ellipsis in its parameter
5580 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005581 if ((Args.size() + (PartialOverloading && Args.size())) > NumParams &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005582 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005583 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005584 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005585 return;
5586 }
5587
5588 // (C++ 13.3.2p2): A candidate function having more than m parameters
5589 // is viable only if the (m+1)st parameter has a default argument
5590 // (8.3.6). For the purposes of overload resolution, the
5591 // parameter list is truncated on the right, so that there are
5592 // exactly m parameters.
5593 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005594 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005595 // Not enough arguments.
5596 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005597 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005598 return;
5599 }
5600
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005601 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005602 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005603 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005604 // Skip the check for callers that are implicit members, because in this
5605 // case we may not yet know what the member's target is; the target is
5606 // inferred for the member automatically, based on the bases and fields of
5607 // the class.
5608 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005609 Candidate.Viable = false;
5610 Candidate.FailureKind = ovl_fail_bad_target;
5611 return;
5612 }
5613
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005614 // Determine the implicit conversion sequences for each of the
5615 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005616 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005617 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005618 // (C++ 13.3.2p3): for F to be a viable function, there shall
5619 // exist for each argument an implicit conversion sequence
5620 // (13.3.3.1) that converts that argument to the corresponding
5621 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005622 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005623 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005624 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005625 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005626 /*InOverloadResolution=*/true,
5627 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005628 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005629 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005630 if (Candidate.Conversions[ArgIdx].isBad()) {
5631 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005632 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005633 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005634 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005635 } else {
5636 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5637 // argument for which there is no corresponding parameter is
5638 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005639 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005640 }
5641 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005642
5643 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5644 Candidate.Viable = false;
5645 Candidate.FailureKind = ovl_fail_enable_if;
5646 Candidate.DeductionFailure.Data = FailedAttr;
5647 return;
5648 }
5649}
5650
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005651ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005652 bool IsInstance) {
5653 SmallVector<ObjCMethodDecl*, 4> Methods;
5654 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5655 return nullptr;
5656
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005657 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5658 bool Match = true;
5659 ObjCMethodDecl *Method = Methods[b];
5660 unsigned NumNamedArgs = Sel.getNumArgs();
5661 // Method might have more arguments than selector indicates. This is due
5662 // to addition of c-style arguments in method.
5663 if (Method->param_size() > NumNamedArgs)
5664 NumNamedArgs = Method->param_size();
5665 if (Args.size() < NumNamedArgs)
5666 continue;
5667
5668 for (unsigned i = 0; i < NumNamedArgs; i++) {
5669 // We can't do any type-checking on a type-dependent argument.
5670 if (Args[i]->isTypeDependent()) {
5671 Match = false;
5672 break;
5673 }
5674
5675 ParmVarDecl *param = Method->parameters()[i];
5676 Expr *argExpr = Args[i];
5677 assert(argExpr && "SelectBestMethod(): missing expression");
5678
5679 // Strip the unbridged-cast placeholder expression off unless it's
5680 // a consumed argument.
5681 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5682 !param->hasAttr<CFConsumedAttr>())
5683 argExpr = stripARCUnbridgedCast(argExpr);
5684
5685 // If the parameter is __unknown_anytype, move on to the next method.
5686 if (param->getType() == Context.UnknownAnyTy) {
5687 Match = false;
5688 break;
5689 }
5690
5691 ImplicitConversionSequence ConversionState
5692 = TryCopyInitialization(*this, argExpr, param->getType(),
5693 /*SuppressUserConversions*/false,
5694 /*InOverloadResolution=*/true,
5695 /*AllowObjCWritebackConversion=*/
5696 getLangOpts().ObjCAutoRefCount,
5697 /*AllowExplicit*/false);
5698 if (ConversionState.isBad()) {
5699 Match = false;
5700 break;
5701 }
5702 }
5703 // Promote additional arguments to variadic methods.
5704 if (Match && Method->isVariadic()) {
5705 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5706 if (Args[i]->isTypeDependent()) {
5707 Match = false;
5708 break;
5709 }
5710 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5711 nullptr);
5712 if (Arg.isInvalid()) {
5713 Match = false;
5714 break;
5715 }
5716 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005717 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005718 // Check for extra arguments to non-variadic methods.
5719 if (Args.size() != NumNamedArgs)
5720 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005721 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5722 // Special case when selectors have no argument. In this case, select
5723 // one with the most general result type of 'id'.
5724 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5725 QualType ReturnT = Methods[b]->getReturnType();
5726 if (ReturnT->isObjCIdType())
5727 return Methods[b];
5728 }
5729 }
5730 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005731
5732 if (Match)
5733 return Method;
5734 }
5735 return nullptr;
5736}
5737
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005738static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5739
5740EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5741 bool MissingImplicitThis) {
5742 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5743 // we need to find the first failing one.
5744 if (!Function->hasAttrs())
Craig Topperc3ec1492014-05-26 06:22:03 +00005745 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005746 AttrVec Attrs = Function->getAttrs();
5747 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5748 IsNotEnableIfAttr);
5749 if (Attrs.begin() == E)
Craig Topperc3ec1492014-05-26 06:22:03 +00005750 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005751 std::reverse(Attrs.begin(), E);
5752
5753 SFINAETrap Trap(*this);
5754
5755 // Convert the arguments.
5756 SmallVector<Expr *, 16> ConvertedArgs;
5757 bool InitializationFailed = false;
5758 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5759 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005760 !cast<CXXMethodDecl>(Function)->isStatic() &&
5761 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005762 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5763 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005764 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005765 Method, Method);
5766 if (R.isInvalid()) {
5767 InitializationFailed = true;
5768 break;
5769 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005770 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005771 } else {
5772 ExprResult R =
5773 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5774 Context,
5775 Function->getParamDecl(i)),
5776 SourceLocation(),
5777 Args[i]);
5778 if (R.isInvalid()) {
5779 InitializationFailed = true;
5780 break;
5781 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005782 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005783 }
5784 }
5785
5786 if (InitializationFailed || Trap.hasErrorOccurred())
5787 return cast<EnableIfAttr>(Attrs[0]);
5788
5789 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5790 APValue Result;
5791 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5792 if (!EIA->getCond()->EvaluateWithSubstitution(
Craig Topperf78d8492014-08-29 06:05:01 +00005793 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)) ||
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005794 !Result.isInt() || !Result.getInt().getBoolValue()) {
5795 return EIA;
5796 }
5797 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005798 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005799}
5800
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005801/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005802/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005803void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005804 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005805 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005806 bool SuppressUserConversions,
5807 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005808 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005809 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5810 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005811 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005812 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005813 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005814 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005815 Args.slice(1), CandidateSet,
5816 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005817 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005818 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005819 SuppressUserConversions);
5820 } else {
John McCalla0296f72010-03-19 07:35:19 +00005821 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005822 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5823 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005824 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005825 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005826 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005827 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005828 Args[0]->Classify(Context), Args.slice(1),
5829 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005830 else
John McCalla0296f72010-03-19 07:35:19 +00005831 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005832 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005833 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005834 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005835 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005836}
5837
John McCallf0f1cf02009-11-17 07:50:12 +00005838/// AddMethodCandidate - Adds a named decl (which is some kind of
5839/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005840void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005841 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005842 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005843 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00005844 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005845 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005846 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005847 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005848
5849 if (isa<UsingShadowDecl>(Decl))
5850 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005851
John McCallf0f1cf02009-11-17 07:50:12 +00005852 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5853 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5854 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005855 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00005856 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005857 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005858 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005859 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005860 } else {
John McCalla0296f72010-03-19 07:35:19 +00005861 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005862 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005863 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005864 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005865 }
5866}
5867
Douglas Gregor436424c2008-11-18 23:14:02 +00005868/// AddMethodCandidate - Adds the given C++ member function to the set
5869/// of candidate functions, using the given function call arguments
5870/// and the object argument (@c Object). For example, in a call
5871/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5872/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5873/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005874/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005875void
John McCalla0296f72010-03-19 07:35:19 +00005876Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005877 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005878 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005879 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005880 OverloadCandidateSet &CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005881 bool SuppressUserConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005882 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005883 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005884 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005885 assert(!isa<CXXConstructorDecl>(Method) &&
5886 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005887
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005888 if (!CandidateSet.isNewCandidate(Method))
5889 return;
5890
Richard Smith8b86f2d2013-11-04 01:48:18 +00005891 // C++11 [class.copy]p23: [DR1402]
5892 // A defaulted move assignment operator that is defined as deleted is
5893 // ignored by overload resolution.
5894 if (Method->isDefaulted() && Method->isDeleted() &&
5895 Method->isMoveAssignmentOperator())
5896 return;
5897
Douglas Gregor27381f32009-11-23 12:27:39 +00005898 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005899 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005900
Douglas Gregor436424c2008-11-18 23:14:02 +00005901 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005902 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005903 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005904 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005905 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005906 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005907 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005908
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005909 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00005910
5911 // (C++ 13.3.2p2): A candidate function having fewer than m
5912 // parameters is viable only if it has an ellipsis in its parameter
5913 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005914 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005915 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005916 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005917 return;
5918 }
5919
5920 // (C++ 13.3.2p2): A candidate function having more than m parameters
5921 // is viable only if the (m+1)st parameter has a default argument
5922 // (8.3.6). For the purposes of overload resolution, the
5923 // parameter list is truncated on the right, so that there are
5924 // exactly m parameters.
5925 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005926 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005927 // Not enough arguments.
5928 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005929 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005930 return;
5931 }
5932
5933 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005934
John McCall6e9f8f62009-12-03 04:06:58 +00005935 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005936 // The implicit object argument is ignored.
5937 Candidate.IgnoreObjectArgument = true;
5938 else {
5939 // Determine the implicit conversion sequence for the object
5940 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005941 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005942 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5943 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005944 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005945 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005946 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005947 return;
5948 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005949 }
5950
Eli Bendersky291a57e2014-09-25 23:59:08 +00005951 // (CUDA B.1): Check for invalid calls between targets.
5952 if (getLangOpts().CUDA)
5953 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5954 if (CheckCUDATarget(Caller, Method)) {
5955 Candidate.Viable = false;
5956 Candidate.FailureKind = ovl_fail_bad_target;
5957 return;
5958 }
5959
Douglas Gregor436424c2008-11-18 23:14:02 +00005960 // Determine the implicit conversion sequences for each of the
5961 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005962 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005963 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005964 // (C++ 13.3.2p3): for F to be a viable function, there shall
5965 // exist for each argument an implicit conversion sequence
5966 // (13.3.3.1) that converts that argument to the corresponding
5967 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005968 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005969 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005970 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005971 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005972 /*InOverloadResolution=*/true,
5973 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005974 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005975 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005976 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005977 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005978 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005979 }
5980 } else {
5981 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5982 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005983 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005984 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005985 }
5986 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005987
5988 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
5989 Candidate.Viable = false;
5990 Candidate.FailureKind = ovl_fail_enable_if;
5991 Candidate.DeductionFailure.Data = FailedAttr;
5992 return;
5993 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005994}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005995
Douglas Gregor97628d62009-08-21 00:16:32 +00005996/// \brief Add a C++ member function template as a candidate to the candidate
5997/// set, using template argument deduction to produce an appropriate member
5998/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005999void
Douglas Gregor97628d62009-08-21 00:16:32 +00006000Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006001 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006002 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006003 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006004 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006005 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006006 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006007 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006008 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006009 if (!CandidateSet.isNewCandidate(MethodTmpl))
6010 return;
6011
Douglas Gregor97628d62009-08-21 00:16:32 +00006012 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006013 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006014 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006015 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006016 // candidate functions in the usual way.113) A given name can refer to one
6017 // or more function templates and also to a set of overloaded non-template
6018 // functions. In such a case, the candidate functions generated from each
6019 // function template are combined with the set of non-template candidate
6020 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006021 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006022 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006023 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006024 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6025 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006026 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006027 Candidate.FoundDecl = FoundDecl;
6028 Candidate.Function = MethodTmpl->getTemplatedDecl();
6029 Candidate.Viable = false;
6030 Candidate.FailureKind = ovl_fail_bad_deduction;
6031 Candidate.IsSurrogate = false;
6032 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006033 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006034 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006035 Info);
6036 return;
6037 }
Mike Stump11289f42009-09-09 15:08:12 +00006038
Douglas Gregor97628d62009-08-21 00:16:32 +00006039 // Add the function template specialization produced by template argument
6040 // deduction as a candidate.
6041 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006042 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006043 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006044 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006045 ActingContext, ObjectType, ObjectClassification, Args,
6046 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00006047}
6048
Douglas Gregor05155d82009-08-21 23:19:43 +00006049/// \brief Add a C++ function template specialization as a candidate
6050/// in the candidate set, using template argument deduction to produce
6051/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006052void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006053Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006054 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006055 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006056 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006057 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006058 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006059 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6060 return;
6061
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006062 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006063 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006064 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006065 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006066 // candidate functions in the usual way.113) A given name can refer to one
6067 // or more function templates and also to a set of overloaded non-template
6068 // functions. In such a case, the candidate functions generated from each
6069 // function template are combined with the set of non-template candidate
6070 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006071 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006072 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006073 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006074 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6075 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006076 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006077 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006078 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6079 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006080 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006081 Candidate.IsSurrogate = false;
6082 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006083 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006084 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006085 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006086 return;
6087 }
Mike Stump11289f42009-09-09 15:08:12 +00006088
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006089 // Add the function template specialization produced by template argument
6090 // deduction as a candidate.
6091 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006092 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006093 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006094}
Mike Stump11289f42009-09-09 15:08:12 +00006095
Douglas Gregor4b60a152013-11-07 22:34:54 +00006096/// Determine whether this is an allowable conversion from the result
6097/// of an explicit conversion operator to the expected type, per C++
6098/// [over.match.conv]p1 and [over.match.ref]p1.
6099///
6100/// \param ConvType The return type of the conversion function.
6101///
6102/// \param ToType The type we are converting to.
6103///
6104/// \param AllowObjCPointerConversion Allow a conversion from one
6105/// Objective-C pointer to another.
6106///
6107/// \returns true if the conversion is allowable, false otherwise.
6108static bool isAllowableExplicitConversion(Sema &S,
6109 QualType ConvType, QualType ToType,
6110 bool AllowObjCPointerConversion) {
6111 QualType ToNonRefType = ToType.getNonReferenceType();
6112
6113 // Easy case: the types are the same.
6114 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6115 return true;
6116
6117 // Allow qualification conversions.
6118 bool ObjCLifetimeConversion;
6119 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6120 ObjCLifetimeConversion))
6121 return true;
6122
6123 // If we're not allowed to consider Objective-C pointer conversions,
6124 // we're done.
6125 if (!AllowObjCPointerConversion)
6126 return false;
6127
6128 // Is this an Objective-C pointer conversion?
6129 bool IncompatibleObjC = false;
6130 QualType ConvertedType;
6131 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6132 IncompatibleObjC);
6133}
6134
Douglas Gregora1f013e2008-11-07 22:36:19 +00006135/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006136/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006137/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006138/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006139/// (which may or may not be the same type as the type that the
6140/// conversion function produces).
6141void
6142Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006143 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006144 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006145 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006146 OverloadCandidateSet& CandidateSet,
6147 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006148 assert(!Conversion->getDescribedFunctionTemplate() &&
6149 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006150 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006151 if (!CandidateSet.isNewCandidate(Conversion))
6152 return;
6153
Richard Smith2a7d4812013-05-04 07:00:32 +00006154 // If the conversion function has an undeduced return type, trigger its
6155 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006156 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006157 if (DeduceReturnType(Conversion, From->getExprLoc()))
6158 return;
6159 ConvType = Conversion->getConversionType().getNonReferenceType();
6160 }
6161
Richard Smith089c3162013-09-21 21:55:46 +00006162 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6163 // operator is only a candidate if its return type is the target type or
6164 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006165 if (Conversion->isExplicit() &&
6166 !isAllowableExplicitConversion(*this, ConvType, ToType,
6167 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006168 return;
6169
Douglas Gregor27381f32009-11-23 12:27:39 +00006170 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006171 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006172
Douglas Gregora1f013e2008-11-07 22:36:19 +00006173 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006174 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006175 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006176 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006177 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006178 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006179 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006180 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006181 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006182 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006183 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006184
Douglas Gregor6affc782010-08-19 15:37:02 +00006185 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006186 // For conversion functions, the function is considered to be a member of
6187 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006188 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006189 //
6190 // Determine the implicit conversion sequence for the implicit
6191 // object parameter.
6192 QualType ImplicitParamType = From->getType();
6193 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6194 ImplicitParamType = FromPtrType->getPointeeType();
6195 CXXRecordDecl *ConversionContext
6196 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006197
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006198 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006199 = TryObjectArgumentInitialization(*this, From->getType(),
6200 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006201 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006202
John McCall0d1da222010-01-12 00:44:57 +00006203 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006204 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006205 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006206 return;
6207 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006208
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006209 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006210 // derived to base as such conversions are given Conversion Rank. They only
6211 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6212 QualType FromCanon
6213 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6214 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6215 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6216 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006217 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006218 return;
6219 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006220
Douglas Gregora1f013e2008-11-07 22:36:19 +00006221 // To determine what the conversion from the result of calling the
6222 // conversion function to the type we're eventually trying to
6223 // convert to (ToType), we need to synthesize a call to the
6224 // conversion function and attempt copy initialization from it. This
6225 // makes sure that we get the right semantics with respect to
6226 // lvalues/rvalues and the type. Fortunately, we can allocate this
6227 // call on the stack and we don't need its arguments to be
6228 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006229 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006230 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006231 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6232 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006233 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006234 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006235
Richard Smith48d24642011-07-13 22:53:21 +00006236 QualType ConversionType = Conversion->getConversionType();
6237 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006238 Candidate.Viable = false;
6239 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6240 return;
6241 }
6242
Richard Smith48d24642011-07-13 22:53:21 +00006243 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006244
Mike Stump11289f42009-09-09 15:08:12 +00006245 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006246 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6247 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006248 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006249 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006250 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006251 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006252 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006253 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006254 /*InOverloadResolution=*/false,
6255 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006256
John McCall0d1da222010-01-12 00:44:57 +00006257 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006258 case ImplicitConversionSequence::StandardConversion:
6259 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006260
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006261 // C++ [over.ics.user]p3:
6262 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006263 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006264 // shall have exact match rank.
6265 if (Conversion->getPrimaryTemplate() &&
6266 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6267 Candidate.Viable = false;
6268 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006269 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006270 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006271
Douglas Gregorcba72b12011-01-21 05:18:22 +00006272 // C++0x [dcl.init.ref]p5:
6273 // In the second case, if the reference is an rvalue reference and
6274 // the second standard conversion sequence of the user-defined
6275 // conversion sequence includes an lvalue-to-rvalue conversion, the
6276 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006277 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006278 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6279 Candidate.Viable = false;
6280 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006281 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006282 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006283 break;
6284
6285 case ImplicitConversionSequence::BadConversion:
6286 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006287 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006288 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006289
6290 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006291 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006292 "Can only end up with a standard conversion sequence or failure");
6293 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006294
Craig Topper5fc8fc22014-08-27 06:28:36 +00006295 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006296 Candidate.Viable = false;
6297 Candidate.FailureKind = ovl_fail_enable_if;
6298 Candidate.DeductionFailure.Data = FailedAttr;
6299 return;
6300 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006301}
6302
Douglas Gregor05155d82009-08-21 23:19:43 +00006303/// \brief Adds a conversion function template specialization
6304/// candidate to the overload set, using template argument deduction
6305/// to deduce the template arguments of the conversion function
6306/// template from the type that we are converting to (C++
6307/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006308void
Douglas Gregor05155d82009-08-21 23:19:43 +00006309Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006310 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006311 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006312 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006313 OverloadCandidateSet &CandidateSet,
6314 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006315 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6316 "Only conversion function templates permitted here");
6317
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006318 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6319 return;
6320
Craig Toppere6706e42012-09-19 02:26:47 +00006321 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006322 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006323 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006324 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006325 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006326 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006327 Candidate.FoundDecl = FoundDecl;
6328 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6329 Candidate.Viable = false;
6330 Candidate.FailureKind = ovl_fail_bad_deduction;
6331 Candidate.IsSurrogate = false;
6332 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006333 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006334 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006335 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006336 return;
6337 }
Mike Stump11289f42009-09-09 15:08:12 +00006338
Douglas Gregor05155d82009-08-21 23:19:43 +00006339 // Add the conversion function template specialization produced by
6340 // template argument deduction as a candidate.
6341 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006342 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006343 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006344}
6345
Douglas Gregorab7897a2008-11-19 22:57:39 +00006346/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6347/// converts the given @c Object to a function pointer via the
6348/// conversion function @c Conversion, and then attempts to call it
6349/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6350/// the type of function that we'll eventually be calling.
6351void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006352 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006353 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006354 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006355 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006356 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006357 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006358 if (!CandidateSet.isNewCandidate(Conversion))
6359 return;
6360
Douglas Gregor27381f32009-11-23 12:27:39 +00006361 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006362 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006363
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006364 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006365 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006366 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006367 Candidate.Surrogate = Conversion;
6368 Candidate.Viable = true;
6369 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006370 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006371 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006372
6373 // Determine the implicit conversion sequence for the implicit
6374 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006375 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006376 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006377 Object->Classify(Context),
6378 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006379 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006380 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006381 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006382 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006383 return;
6384 }
6385
6386 // The first conversion is actually a user-defined conversion whose
6387 // first conversion is ObjectInit's standard conversion (which is
6388 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006389 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006390 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006391 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006392 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006393 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006394 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006395 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006396 = Candidate.Conversions[0].UserDefined.Before;
6397 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6398
Mike Stump11289f42009-09-09 15:08:12 +00006399 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006400 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006401
6402 // (C++ 13.3.2p2): A candidate function having fewer than m
6403 // parameters is viable only if it has an ellipsis in its parameter
6404 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006405 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006406 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006407 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006408 return;
6409 }
6410
6411 // Function types don't have any default arguments, so just check if
6412 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006413 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006414 // Not enough arguments.
6415 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006416 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006417 return;
6418 }
6419
6420 // Determine the implicit conversion sequences for each of the
6421 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006422 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006423 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006424 // (C++ 13.3.2p3): for F to be a viable function, there shall
6425 // exist for each argument an implicit conversion sequence
6426 // (13.3.3.1) that converts that argument to the corresponding
6427 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006428 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006429 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006430 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006431 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006432 /*InOverloadResolution=*/false,
6433 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006434 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006435 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006436 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006437 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006438 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006439 }
6440 } else {
6441 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6442 // argument for which there is no corresponding parameter is
6443 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006444 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006445 }
6446 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006447
Craig Topper5fc8fc22014-08-27 06:28:36 +00006448 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006449 Candidate.Viable = false;
6450 Candidate.FailureKind = ovl_fail_enable_if;
6451 Candidate.DeductionFailure.Data = FailedAttr;
6452 return;
6453 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006454}
6455
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006456/// \brief Add overload candidates for overloaded operators that are
6457/// member functions.
6458///
6459/// Add the overloaded operator candidates that are member functions
6460/// for the operator Op that was used in an operator expression such
6461/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6462/// CandidateSet will store the added overload candidates. (C++
6463/// [over.match.oper]).
6464void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6465 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006466 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006467 OverloadCandidateSet& CandidateSet,
6468 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006469 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6470
6471 // C++ [over.match.oper]p3:
6472 // For a unary operator @ with an operand of a type whose
6473 // cv-unqualified version is T1, and for a binary operator @ with
6474 // a left operand of a type whose cv-unqualified version is T1 and
6475 // a right operand of a type whose cv-unqualified version is T2,
6476 // three sets of candidate functions, designated member
6477 // candidates, non-member candidates and built-in candidates, are
6478 // constructed as follows:
6479 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006480
Richard Smith0feaf0c2013-04-20 12:41:22 +00006481 // -- If T1 is a complete class type or a class currently being
6482 // defined, the set of member candidates is the result of the
6483 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6484 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006485 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006486 // Complete the type if it can be completed.
6487 RequireCompleteType(OpLoc, T1, 0);
6488 // If the type is neither complete nor being defined, bail out now.
6489 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006490 return;
Mike Stump11289f42009-09-09 15:08:12 +00006491
John McCall27b18f82009-11-17 02:14:36 +00006492 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6493 LookupQualifiedName(Operators, T1Rec->getDecl());
6494 Operators.suppressDiagnostics();
6495
Mike Stump11289f42009-09-09 15:08:12 +00006496 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006497 OperEnd = Operators.end();
6498 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006499 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006500 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006501 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006502 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006503 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006504 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006505 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006506}
6507
Douglas Gregora11693b2008-11-12 17:17:38 +00006508/// AddBuiltinCandidate - Add a candidate for a built-in
6509/// operator. ResultTy and ParamTys are the result and parameter types
6510/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006511/// arguments being passed to the candidate. IsAssignmentOperator
6512/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006513/// operator. NumContextualBoolArguments is the number of arguments
6514/// (at the beginning of the argument list) that will be contextually
6515/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006516void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006517 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006518 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006519 bool IsAssignmentOperator,
6520 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006521 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006522 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006523
Douglas Gregora11693b2008-11-12 17:17:38 +00006524 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006525 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006526 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6527 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006528 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006529 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006530 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006531 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006532 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6533
6534 // Determine the implicit conversion sequences for each of the
6535 // arguments.
6536 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006537 Candidate.ExplicitCallArguments = Args.size();
6538 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006539 // C++ [over.match.oper]p4:
6540 // For the built-in assignment operators, conversions of the
6541 // left operand are restricted as follows:
6542 // -- no temporaries are introduced to hold the left operand, and
6543 // -- no user-defined conversions are applied to the left
6544 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006545 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006546 //
6547 // We block these conversions by turning off user-defined
6548 // conversions, since that is the only way that initialization of
6549 // a reference to a non-class type can occur from something that
6550 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006551 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006552 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006553 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006554 Candidate.Conversions[ArgIdx]
6555 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006556 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006557 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006558 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006559 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006560 /*InOverloadResolution=*/false,
6561 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006562 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006563 }
John McCall0d1da222010-01-12 00:44:57 +00006564 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006565 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006566 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006567 break;
6568 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006569 }
6570}
6571
Craig Toppercd7b0332013-07-01 06:29:40 +00006572namespace {
6573
Douglas Gregora11693b2008-11-12 17:17:38 +00006574/// BuiltinCandidateTypeSet - A set of types that will be used for the
6575/// candidate operator functions for built-in operators (C++
6576/// [over.built]). The types are separated into pointer types and
6577/// enumeration types.
6578class BuiltinCandidateTypeSet {
6579 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006580 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006581
6582 /// PointerTypes - The set of pointer types that will be used in the
6583 /// built-in candidates.
6584 TypeSet PointerTypes;
6585
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006586 /// MemberPointerTypes - The set of member pointer types that will be
6587 /// used in the built-in candidates.
6588 TypeSet MemberPointerTypes;
6589
Douglas Gregora11693b2008-11-12 17:17:38 +00006590 /// EnumerationTypes - The set of enumeration types that will be
6591 /// used in the built-in candidates.
6592 TypeSet EnumerationTypes;
6593
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006594 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006595 /// candidates.
6596 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006597
6598 /// \brief A flag indicating non-record types are viable candidates
6599 bool HasNonRecordTypes;
6600
6601 /// \brief A flag indicating whether either arithmetic or enumeration types
6602 /// were present in the candidate set.
6603 bool HasArithmeticOrEnumeralTypes;
6604
Douglas Gregor80af3132011-05-21 23:15:46 +00006605 /// \brief A flag indicating whether the nullptr type was present in the
6606 /// candidate set.
6607 bool HasNullPtrType;
6608
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006609 /// Sema - The semantic analysis instance where we are building the
6610 /// candidate type set.
6611 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006612
Douglas Gregora11693b2008-11-12 17:17:38 +00006613 /// Context - The AST context in which we will build the type sets.
6614 ASTContext &Context;
6615
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006616 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6617 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006618 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006619
6620public:
6621 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006622 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006623
Mike Stump11289f42009-09-09 15:08:12 +00006624 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006625 : HasNonRecordTypes(false),
6626 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006627 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006628 SemaRef(SemaRef),
6629 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006630
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006631 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006632 SourceLocation Loc,
6633 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006634 bool AllowExplicitConversions,
6635 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006636
6637 /// pointer_begin - First pointer type found;
6638 iterator pointer_begin() { return PointerTypes.begin(); }
6639
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006640 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006641 iterator pointer_end() { return PointerTypes.end(); }
6642
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006643 /// member_pointer_begin - First member pointer type found;
6644 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6645
6646 /// member_pointer_end - Past the last member pointer type found;
6647 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6648
Douglas Gregora11693b2008-11-12 17:17:38 +00006649 /// enumeration_begin - First enumeration type found;
6650 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6651
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006652 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006653 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006654
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006655 iterator vector_begin() { return VectorTypes.begin(); }
6656 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006657
6658 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6659 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006660 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006661};
6662
Craig Toppercd7b0332013-07-01 06:29:40 +00006663} // end anonymous namespace
6664
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006665/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006666/// the set of pointer types along with any more-qualified variants of
6667/// that type. For example, if @p Ty is "int const *", this routine
6668/// will add "int const *", "int const volatile *", "int const
6669/// restrict *", and "int const volatile restrict *" to the set of
6670/// pointer types. Returns true if the add of @p Ty itself succeeded,
6671/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006672///
6673/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006674bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006675BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6676 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006677
Douglas Gregora11693b2008-11-12 17:17:38 +00006678 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006679 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006680 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006681
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006682 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006683 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006684 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006685 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006686 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6687 PointeeTy = PTy->getPointeeType();
6688 buildObjCPtr = true;
6689 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006690 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006691 }
6692
Sebastian Redl4990a632009-11-18 20:39:26 +00006693 // Don't add qualified variants of arrays. For one, they're not allowed
6694 // (the qualifier would sink to the element type), and for another, the
6695 // only overload situation where it matters is subscript or pointer +- int,
6696 // and those shouldn't have qualifier variants anyway.
6697 if (PointeeTy->isArrayType())
6698 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006699
John McCall8ccfcb52009-09-24 19:53:00 +00006700 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006701 bool hasVolatile = VisibleQuals.hasVolatile();
6702 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006703
John McCall8ccfcb52009-09-24 19:53:00 +00006704 // Iterate through all strict supersets of BaseCVR.
6705 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6706 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006707 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006708 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006709
6710 // Skip over restrict if no restrict found anywhere in the types, or if
6711 // the type cannot be restrict-qualified.
6712 if ((CVR & Qualifiers::Restrict) &&
6713 (!hasRestrict ||
6714 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6715 continue;
6716
6717 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006718 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006719
6720 // Build qualified pointer type.
6721 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006722 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006723 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006724 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006725 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6726
6727 // Insert qualified pointer type.
6728 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006729 }
6730
6731 return true;
6732}
6733
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006734/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6735/// to the set of pointer types along with any more-qualified variants of
6736/// that type. For example, if @p Ty is "int const *", this routine
6737/// will add "int const *", "int const volatile *", "int const
6738/// restrict *", and "int const volatile restrict *" to the set of
6739/// pointer types. Returns true if the add of @p Ty itself succeeded,
6740/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006741///
6742/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006743bool
6744BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6745 QualType Ty) {
6746 // Insert this type.
6747 if (!MemberPointerTypes.insert(Ty))
6748 return false;
6749
John McCall8ccfcb52009-09-24 19:53:00 +00006750 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6751 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006752
John McCall8ccfcb52009-09-24 19:53:00 +00006753 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006754 // Don't add qualified variants of arrays. For one, they're not allowed
6755 // (the qualifier would sink to the element type), and for another, the
6756 // only overload situation where it matters is subscript or pointer +- int,
6757 // and those shouldn't have qualifier variants anyway.
6758 if (PointeeTy->isArrayType())
6759 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006760 const Type *ClassTy = PointerTy->getClass();
6761
6762 // Iterate through all strict supersets of the pointee type's CVR
6763 // qualifiers.
6764 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6765 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6766 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006767
John McCall8ccfcb52009-09-24 19:53:00 +00006768 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006769 MemberPointerTypes.insert(
6770 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006771 }
6772
6773 return true;
6774}
6775
Douglas Gregora11693b2008-11-12 17:17:38 +00006776/// AddTypesConvertedFrom - Add each of the types to which the type @p
6777/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006778/// primarily interested in pointer types and enumeration types. We also
6779/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006780/// AllowUserConversions is true if we should look at the conversion
6781/// functions of a class type, and AllowExplicitConversions if we
6782/// should also include the explicit conversion functions of a class
6783/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006784void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006785BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006786 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006787 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006788 bool AllowExplicitConversions,
6789 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006790 // Only deal with canonical types.
6791 Ty = Context.getCanonicalType(Ty);
6792
6793 // Look through reference types; they aren't part of the type of an
6794 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006795 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006796 Ty = RefTy->getPointeeType();
6797
John McCall33ddac02011-01-19 10:06:00 +00006798 // If we're dealing with an array type, decay to the pointer.
6799 if (Ty->isArrayType())
6800 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6801
6802 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006803 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006804
Chandler Carruth00a38332010-12-13 01:44:01 +00006805 // Flag if we ever add a non-record type.
6806 const RecordType *TyRec = Ty->getAs<RecordType>();
6807 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6808
Chandler Carruth00a38332010-12-13 01:44:01 +00006809 // Flag if we encounter an arithmetic type.
6810 HasArithmeticOrEnumeralTypes =
6811 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6812
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006813 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6814 PointerTypes.insert(Ty);
6815 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006816 // Insert our type, and its more-qualified variants, into the set
6817 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006818 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006819 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006820 } else if (Ty->isMemberPointerType()) {
6821 // Member pointers are far easier, since the pointee can't be converted.
6822 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6823 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006824 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006825 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006826 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006827 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006828 // We treat vector types as arithmetic types in many contexts as an
6829 // extension.
6830 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006831 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006832 } else if (Ty->isNullPtrType()) {
6833 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006834 } else if (AllowUserConversions && TyRec) {
6835 // No conversion functions in incomplete types.
6836 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6837 return;
Mike Stump11289f42009-09-09 15:08:12 +00006838
Chandler Carruth00a38332010-12-13 01:44:01 +00006839 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006840 std::pair<CXXRecordDecl::conversion_iterator,
6841 CXXRecordDecl::conversion_iterator>
6842 Conversions = ClassDecl->getVisibleConversionFunctions();
6843 for (CXXRecordDecl::conversion_iterator
6844 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006845 NamedDecl *D = I.getDecl();
6846 if (isa<UsingShadowDecl>(D))
6847 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006848
Chandler Carruth00a38332010-12-13 01:44:01 +00006849 // Skip conversion function templates; they don't tell us anything
6850 // about which builtin types we can convert to.
6851 if (isa<FunctionTemplateDecl>(D))
6852 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006853
Chandler Carruth00a38332010-12-13 01:44:01 +00006854 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6855 if (AllowExplicitConversions || !Conv->isExplicit()) {
6856 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6857 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006858 }
6859 }
6860 }
6861}
6862
Douglas Gregor84605ae2009-08-24 13:43:27 +00006863/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6864/// the volatile- and non-volatile-qualified assignment operators for the
6865/// given type to the candidate set.
6866static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6867 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00006868 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006869 OverloadCandidateSet &CandidateSet) {
6870 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006871
Douglas Gregor84605ae2009-08-24 13:43:27 +00006872 // T& operator=(T&, T)
6873 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6874 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006875 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006876 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006877
Douglas Gregor84605ae2009-08-24 13:43:27 +00006878 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6879 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006880 ParamTypes[0]
6881 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006882 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006883 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006884 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006885 }
6886}
Mike Stump11289f42009-09-09 15:08:12 +00006887
Sebastian Redl1054fae2009-10-25 17:03:50 +00006888/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6889/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006890static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6891 Qualifiers VRQuals;
6892 const RecordType *TyRec;
6893 if (const MemberPointerType *RHSMPType =
6894 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006895 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006896 else
6897 TyRec = ArgExpr->getType()->getAs<RecordType>();
6898 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006899 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006900 VRQuals.addVolatile();
6901 VRQuals.addRestrict();
6902 return VRQuals;
6903 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006904
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006905 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006906 if (!ClassDecl->hasDefinition())
6907 return VRQuals;
6908
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006909 std::pair<CXXRecordDecl::conversion_iterator,
6910 CXXRecordDecl::conversion_iterator>
6911 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006912
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006913 for (CXXRecordDecl::conversion_iterator
6914 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006915 NamedDecl *D = I.getDecl();
6916 if (isa<UsingShadowDecl>(D))
6917 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6918 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006919 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6920 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6921 CanTy = ResTypeRef->getPointeeType();
6922 // Need to go down the pointer/mempointer chain and add qualifiers
6923 // as see them.
6924 bool done = false;
6925 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006926 if (CanTy.isRestrictQualified())
6927 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006928 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6929 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006930 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006931 CanTy->getAs<MemberPointerType>())
6932 CanTy = ResTypeMPtr->getPointeeType();
6933 else
6934 done = true;
6935 if (CanTy.isVolatileQualified())
6936 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006937 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6938 return VRQuals;
6939 }
6940 }
6941 }
6942 return VRQuals;
6943}
John McCall52872982010-11-13 05:51:15 +00006944
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006945namespace {
John McCall52872982010-11-13 05:51:15 +00006946
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006947/// \brief Helper class to manage the addition of builtin operator overload
6948/// candidates. It provides shared state and utility methods used throughout
6949/// the process, as well as a helper method to add each group of builtin
6950/// operator overloads from the standard to a candidate set.
6951class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006952 // Common instance state available to all overload candidate addition methods.
6953 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00006954 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006955 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006956 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006957 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006958 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006959
Chandler Carruthc6586e52010-12-12 10:35:00 +00006960 // Define some constants used to index and iterate over the arithemetic types
6961 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006962 // The "promoted arithmetic types" are the arithmetic
6963 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006964 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00006965 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00006966 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00006967 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00006968 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00006969 LastPromotedArithmeticType = 11;
6970 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00006971
Chandler Carruthc6586e52010-12-12 10:35:00 +00006972 /// \brief Get the canonical type for a given arithmetic type index.
6973 CanQualType getArithmeticType(unsigned index) {
6974 assert(index < NumArithmeticTypes);
6975 static CanQualType ASTContext::* const
6976 ArithmeticTypes[NumArithmeticTypes] = {
6977 // Start of promoted types.
6978 &ASTContext::FloatTy,
6979 &ASTContext::DoubleTy,
6980 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006981
Chandler Carruthc6586e52010-12-12 10:35:00 +00006982 // Start of integral types.
6983 &ASTContext::IntTy,
6984 &ASTContext::LongTy,
6985 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006986 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006987 &ASTContext::UnsignedIntTy,
6988 &ASTContext::UnsignedLongTy,
6989 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006990 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006991 // End of promoted types.
6992
6993 &ASTContext::BoolTy,
6994 &ASTContext::CharTy,
6995 &ASTContext::WCharTy,
6996 &ASTContext::Char16Ty,
6997 &ASTContext::Char32Ty,
6998 &ASTContext::SignedCharTy,
6999 &ASTContext::ShortTy,
7000 &ASTContext::UnsignedCharTy,
7001 &ASTContext::UnsignedShortTy,
7002 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007003 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007004 };
7005 return S.Context.*ArithmeticTypes[index];
7006 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007007
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007008 /// \brief Gets the canonical type resulting from the usual arithemetic
7009 /// converions for the given arithmetic types.
7010 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7011 // Accelerator table for performing the usual arithmetic conversions.
7012 // The rules are basically:
7013 // - if either is floating-point, use the wider floating-point
7014 // - if same signedness, use the higher rank
7015 // - if same size, use unsigned of the higher rank
7016 // - use the larger type
7017 // These rules, together with the axiom that higher ranks are
7018 // never smaller, are sufficient to precompute all of these results
7019 // *except* when dealing with signed types of higher rank.
7020 // (we could precompute SLL x UI for all known platforms, but it's
7021 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007022 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007023 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007024 Dep=-1,
7025 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007026 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007027 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007028 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007029/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7030/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7031/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7032/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7033/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7034/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7035/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7036/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7037/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7038/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7039/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007040 };
7041
7042 assert(L < LastPromotedArithmeticType);
7043 assert(R < LastPromotedArithmeticType);
7044 int Idx = ConversionsTable[L][R];
7045
7046 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007047 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007048
7049 // Slow path: we need to compare widths.
7050 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007051 CanQualType LT = getArithmeticType(L),
7052 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007053 unsigned LW = S.Context.getIntWidth(LT),
7054 RW = S.Context.getIntWidth(RT);
7055
7056 // If they're different widths, use the signed type.
7057 if (LW > RW) return LT;
7058 else if (LW < RW) return RT;
7059
7060 // Otherwise, use the unsigned type of the signed type's rank.
7061 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7062 assert(L == SLL || R == SLL);
7063 return S.Context.UnsignedLongLongTy;
7064 }
7065
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007066 /// \brief Helper method to factor out the common pattern of adding overloads
7067 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007068 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007069 bool HasVolatile,
7070 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007071 QualType ParamTypes[2] = {
7072 S.Context.getLValueReferenceType(CandidateTy),
7073 S.Context.IntTy
7074 };
7075
7076 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007077 if (Args.size() == 1)
7078 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007079 else
Richard Smithe54c3072013-05-05 15:51:06 +00007080 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007081
7082 // Use a heuristic to reduce number of builtin candidates in the set:
7083 // add volatile version only if there are conversions to a volatile type.
7084 if (HasVolatile) {
7085 ParamTypes[0] =
7086 S.Context.getLValueReferenceType(
7087 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007088 if (Args.size() == 1)
7089 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007090 else
Richard Smithe54c3072013-05-05 15:51:06 +00007091 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007092 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007093
7094 // Add restrict version only if there are conversions to a restrict type
7095 // and our candidate type is a non-restrict-qualified pointer.
7096 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7097 !CandidateTy.isRestrictQualified()) {
7098 ParamTypes[0]
7099 = S.Context.getLValueReferenceType(
7100 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007101 if (Args.size() == 1)
7102 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007103 else
Richard Smithe54c3072013-05-05 15:51:06 +00007104 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007105
7106 if (HasVolatile) {
7107 ParamTypes[0]
7108 = S.Context.getLValueReferenceType(
7109 S.Context.getCVRQualifiedType(CandidateTy,
7110 (Qualifiers::Volatile |
7111 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007112 if (Args.size() == 1)
7113 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007114 else
Richard Smithe54c3072013-05-05 15:51:06 +00007115 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007116 }
7117 }
7118
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007119 }
7120
7121public:
7122 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007123 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007124 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007125 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007126 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007127 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007128 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007129 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007130 HasArithmeticOrEnumeralCandidateType(
7131 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007132 CandidateTypes(CandidateTypes),
7133 CandidateSet(CandidateSet) {
7134 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007135 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007136 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007137 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007138 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007139 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007140 assert(getArithmeticType(FirstPromotedArithmeticType)
7141 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007142 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007143 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007144 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007145 "Invalid last promoted arithmetic type");
7146 }
7147
7148 // C++ [over.built]p3:
7149 //
7150 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7151 // is either volatile or empty, there exist candidate operator
7152 // functions of the form
7153 //
7154 // VQ T& operator++(VQ T&);
7155 // T operator++(VQ T&, int);
7156 //
7157 // C++ [over.built]p4:
7158 //
7159 // For every pair (T, VQ), where T is an arithmetic type other
7160 // than bool, and VQ is either volatile or empty, there exist
7161 // candidate operator functions of the form
7162 //
7163 // VQ T& operator--(VQ T&);
7164 // T operator--(VQ T&, int);
7165 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007166 if (!HasArithmeticOrEnumeralCandidateType)
7167 return;
7168
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007169 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7170 Arith < NumArithmeticTypes; ++Arith) {
7171 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007172 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007173 VisibleTypeConversionsQuals.hasVolatile(),
7174 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007175 }
7176 }
7177
7178 // C++ [over.built]p5:
7179 //
7180 // For every pair (T, VQ), where T is a cv-qualified or
7181 // cv-unqualified object type, and VQ is either volatile or
7182 // empty, there exist candidate operator functions of the form
7183 //
7184 // T*VQ& operator++(T*VQ&);
7185 // T*VQ& operator--(T*VQ&);
7186 // T* operator++(T*VQ&, int);
7187 // T* operator--(T*VQ&, int);
7188 void addPlusPlusMinusMinusPointerOverloads() {
7189 for (BuiltinCandidateTypeSet::iterator
7190 Ptr = CandidateTypes[0].pointer_begin(),
7191 PtrEnd = CandidateTypes[0].pointer_end();
7192 Ptr != PtrEnd; ++Ptr) {
7193 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007194 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007195 continue;
7196
7197 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007198 (!(*Ptr).isVolatileQualified() &&
7199 VisibleTypeConversionsQuals.hasVolatile()),
7200 (!(*Ptr).isRestrictQualified() &&
7201 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007202 }
7203 }
7204
7205 // C++ [over.built]p6:
7206 // For every cv-qualified or cv-unqualified object type T, there
7207 // exist candidate operator functions of the form
7208 //
7209 // T& operator*(T*);
7210 //
7211 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007212 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007213 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007214 // T& operator*(T*);
7215 void addUnaryStarPointerOverloads() {
7216 for (BuiltinCandidateTypeSet::iterator
7217 Ptr = CandidateTypes[0].pointer_begin(),
7218 PtrEnd = CandidateTypes[0].pointer_end();
7219 Ptr != PtrEnd; ++Ptr) {
7220 QualType ParamTy = *Ptr;
7221 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007222 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7223 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007224
Douglas Gregor02824322011-01-26 19:30:28 +00007225 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7226 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7227 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007228
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007229 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007230 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007231 }
7232 }
7233
7234 // C++ [over.built]p9:
7235 // For every promoted arithmetic type T, there exist candidate
7236 // operator functions of the form
7237 //
7238 // T operator+(T);
7239 // T operator-(T);
7240 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007241 if (!HasArithmeticOrEnumeralCandidateType)
7242 return;
7243
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007244 for (unsigned Arith = FirstPromotedArithmeticType;
7245 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007246 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007247 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007248 }
7249
7250 // Extension: We also add these operators for vector types.
7251 for (BuiltinCandidateTypeSet::iterator
7252 Vec = CandidateTypes[0].vector_begin(),
7253 VecEnd = CandidateTypes[0].vector_end();
7254 Vec != VecEnd; ++Vec) {
7255 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007256 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007257 }
7258 }
7259
7260 // C++ [over.built]p8:
7261 // For every type T, there exist candidate operator functions of
7262 // the form
7263 //
7264 // T* operator+(T*);
7265 void addUnaryPlusPointerOverloads() {
7266 for (BuiltinCandidateTypeSet::iterator
7267 Ptr = CandidateTypes[0].pointer_begin(),
7268 PtrEnd = CandidateTypes[0].pointer_end();
7269 Ptr != PtrEnd; ++Ptr) {
7270 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007271 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007272 }
7273 }
7274
7275 // C++ [over.built]p10:
7276 // For every promoted integral type T, there exist candidate
7277 // operator functions of the form
7278 //
7279 // T operator~(T);
7280 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007281 if (!HasArithmeticOrEnumeralCandidateType)
7282 return;
7283
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007284 for (unsigned Int = FirstPromotedIntegralType;
7285 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007286 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007287 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007288 }
7289
7290 // Extension: We also add this operator for vector types.
7291 for (BuiltinCandidateTypeSet::iterator
7292 Vec = CandidateTypes[0].vector_begin(),
7293 VecEnd = CandidateTypes[0].vector_end();
7294 Vec != VecEnd; ++Vec) {
7295 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007296 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007297 }
7298 }
7299
7300 // C++ [over.match.oper]p16:
7301 // For every pointer to member type T, there exist candidate operator
7302 // functions of the form
7303 //
7304 // bool operator==(T,T);
7305 // bool operator!=(T,T);
7306 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7307 /// Set of (canonical) types that we've already handled.
7308 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7309
Richard Smithe54c3072013-05-05 15:51:06 +00007310 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007311 for (BuiltinCandidateTypeSet::iterator
7312 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7313 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7314 MemPtr != MemPtrEnd;
7315 ++MemPtr) {
7316 // Don't add the same builtin candidate twice.
7317 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7318 continue;
7319
7320 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007321 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007322 }
7323 }
7324 }
7325
7326 // C++ [over.built]p15:
7327 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007328 // For every T, where T is an enumeration type, a pointer type, or
7329 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007330 //
7331 // bool operator<(T, T);
7332 // bool operator>(T, T);
7333 // bool operator<=(T, T);
7334 // bool operator>=(T, T);
7335 // bool operator==(T, T);
7336 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007337 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007338 // C++ [over.match.oper]p3:
7339 // [...]the built-in candidates include all of the candidate operator
7340 // functions defined in 13.6 that, compared to the given operator, [...]
7341 // do not have the same parameter-type-list as any non-template non-member
7342 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007343 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007344 // Note that in practice, this only affects enumeration types because there
7345 // aren't any built-in candidates of record type, and a user-defined operator
7346 // must have an operand of record or enumeration type. Also, the only other
7347 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007348 // cannot be overloaded for enumeration types, so this is the only place
7349 // where we must suppress candidates like this.
7350 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7351 UserDefinedBinaryOperators;
7352
Richard Smithe54c3072013-05-05 15:51:06 +00007353 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007354 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7355 CandidateTypes[ArgIdx].enumeration_end()) {
7356 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7357 CEnd = CandidateSet.end();
7358 C != CEnd; ++C) {
7359 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7360 continue;
7361
Eli Friedman14f082b2012-09-18 21:52:24 +00007362 if (C->Function->isFunctionTemplateSpecialization())
7363 continue;
7364
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007365 QualType FirstParamType =
7366 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7367 QualType SecondParamType =
7368 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7369
7370 // Skip if either parameter isn't of enumeral type.
7371 if (!FirstParamType->isEnumeralType() ||
7372 !SecondParamType->isEnumeralType())
7373 continue;
7374
7375 // Add this operator to the set of known user-defined operators.
7376 UserDefinedBinaryOperators.insert(
7377 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7378 S.Context.getCanonicalType(SecondParamType)));
7379 }
7380 }
7381 }
7382
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007383 /// Set of (canonical) types that we've already handled.
7384 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7385
Richard Smithe54c3072013-05-05 15:51:06 +00007386 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007387 for (BuiltinCandidateTypeSet::iterator
7388 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7389 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7390 Ptr != PtrEnd; ++Ptr) {
7391 // Don't add the same builtin candidate twice.
7392 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7393 continue;
7394
7395 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007396 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007397 }
7398 for (BuiltinCandidateTypeSet::iterator
7399 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7400 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7401 Enum != EnumEnd; ++Enum) {
7402 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7403
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007404 // Don't add the same builtin candidate twice, or if a user defined
7405 // candidate exists.
7406 if (!AddedTypes.insert(CanonType) ||
7407 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7408 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007409 continue;
7410
7411 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007412 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007413 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007414
7415 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7416 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7417 if (AddedTypes.insert(NullPtrTy) &&
Richard Smithe54c3072013-05-05 15:51:06 +00007418 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007419 NullPtrTy))) {
7420 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007421 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007422 CandidateSet);
7423 }
7424 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007425 }
7426 }
7427
7428 // C++ [over.built]p13:
7429 //
7430 // For every cv-qualified or cv-unqualified object type T
7431 // there exist candidate operator functions of the form
7432 //
7433 // T* operator+(T*, ptrdiff_t);
7434 // T& operator[](T*, ptrdiff_t); [BELOW]
7435 // T* operator-(T*, ptrdiff_t);
7436 // T* operator+(ptrdiff_t, T*);
7437 // T& operator[](ptrdiff_t, T*); [BELOW]
7438 //
7439 // C++ [over.built]p14:
7440 //
7441 // For every T, where T is a pointer to object type, there
7442 // exist candidate operator functions of the form
7443 //
7444 // ptrdiff_t operator-(T, T);
7445 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7446 /// Set of (canonical) types that we've already handled.
7447 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7448
7449 for (int Arg = 0; Arg < 2; ++Arg) {
7450 QualType AsymetricParamTypes[2] = {
7451 S.Context.getPointerDiffType(),
7452 S.Context.getPointerDiffType(),
7453 };
7454 for (BuiltinCandidateTypeSet::iterator
7455 Ptr = CandidateTypes[Arg].pointer_begin(),
7456 PtrEnd = CandidateTypes[Arg].pointer_end();
7457 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007458 QualType PointeeTy = (*Ptr)->getPointeeType();
7459 if (!PointeeTy->isObjectType())
7460 continue;
7461
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007462 AsymetricParamTypes[Arg] = *Ptr;
7463 if (Arg == 0 || Op == OO_Plus) {
7464 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7465 // T* operator+(ptrdiff_t, T*);
Richard Smithe54c3072013-05-05 15:51:06 +00007466 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007467 }
7468 if (Op == OO_Minus) {
7469 // ptrdiff_t operator-(T, T);
7470 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7471 continue;
7472
7473 QualType ParamTypes[2] = { *Ptr, *Ptr };
7474 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007475 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007476 }
7477 }
7478 }
7479 }
7480
7481 // C++ [over.built]p12:
7482 //
7483 // For every pair of promoted arithmetic types L and R, there
7484 // exist candidate operator functions of the form
7485 //
7486 // LR operator*(L, R);
7487 // LR operator/(L, R);
7488 // LR operator+(L, R);
7489 // LR operator-(L, R);
7490 // bool operator<(L, R);
7491 // bool operator>(L, R);
7492 // bool operator<=(L, R);
7493 // bool operator>=(L, R);
7494 // bool operator==(L, R);
7495 // bool operator!=(L, R);
7496 //
7497 // where LR is the result of the usual arithmetic conversions
7498 // between types L and R.
7499 //
7500 // C++ [over.built]p24:
7501 //
7502 // For every pair of promoted arithmetic types L and R, there exist
7503 // candidate operator functions of the form
7504 //
7505 // LR operator?(bool, L, R);
7506 //
7507 // where LR is the result of the usual arithmetic conversions
7508 // between types L and R.
7509 // Our candidates ignore the first parameter.
7510 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007511 if (!HasArithmeticOrEnumeralCandidateType)
7512 return;
7513
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007514 for (unsigned Left = FirstPromotedArithmeticType;
7515 Left < LastPromotedArithmeticType; ++Left) {
7516 for (unsigned Right = FirstPromotedArithmeticType;
7517 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007518 QualType LandR[2] = { getArithmeticType(Left),
7519 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007520 QualType Result =
7521 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007522 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007523 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007524 }
7525 }
7526
7527 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7528 // conditional operator for vector types.
7529 for (BuiltinCandidateTypeSet::iterator
7530 Vec1 = CandidateTypes[0].vector_begin(),
7531 Vec1End = CandidateTypes[0].vector_end();
7532 Vec1 != Vec1End; ++Vec1) {
7533 for (BuiltinCandidateTypeSet::iterator
7534 Vec2 = CandidateTypes[1].vector_begin(),
7535 Vec2End = CandidateTypes[1].vector_end();
7536 Vec2 != Vec2End; ++Vec2) {
7537 QualType LandR[2] = { *Vec1, *Vec2 };
7538 QualType Result = S.Context.BoolTy;
7539 if (!isComparison) {
7540 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7541 Result = *Vec1;
7542 else
7543 Result = *Vec2;
7544 }
7545
Richard Smithe54c3072013-05-05 15:51:06 +00007546 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007547 }
7548 }
7549 }
7550
7551 // C++ [over.built]p17:
7552 //
7553 // For every pair of promoted integral types L and R, there
7554 // exist candidate operator functions of the form
7555 //
7556 // LR operator%(L, R);
7557 // LR operator&(L, R);
7558 // LR operator^(L, R);
7559 // LR operator|(L, R);
7560 // L operator<<(L, R);
7561 // L operator>>(L, R);
7562 //
7563 // where LR is the result of the usual arithmetic conversions
7564 // between types L and R.
7565 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007566 if (!HasArithmeticOrEnumeralCandidateType)
7567 return;
7568
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007569 for (unsigned Left = FirstPromotedIntegralType;
7570 Left < LastPromotedIntegralType; ++Left) {
7571 for (unsigned Right = FirstPromotedIntegralType;
7572 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007573 QualType LandR[2] = { getArithmeticType(Left),
7574 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007575 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7576 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007577 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007578 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007579 }
7580 }
7581 }
7582
7583 // C++ [over.built]p20:
7584 //
7585 // For every pair (T, VQ), where T is an enumeration or
7586 // pointer to member type and VQ is either volatile or
7587 // empty, there exist candidate operator functions of the form
7588 //
7589 // VQ T& operator=(VQ T&, T);
7590 void addAssignmentMemberPointerOrEnumeralOverloads() {
7591 /// Set of (canonical) types that we've already handled.
7592 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7593
7594 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7595 for (BuiltinCandidateTypeSet::iterator
7596 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7597 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7598 Enum != EnumEnd; ++Enum) {
7599 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7600 continue;
7601
Richard Smithe54c3072013-05-05 15:51:06 +00007602 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007603 }
7604
7605 for (BuiltinCandidateTypeSet::iterator
7606 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7607 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7608 MemPtr != MemPtrEnd; ++MemPtr) {
7609 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7610 continue;
7611
Richard Smithe54c3072013-05-05 15:51:06 +00007612 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007613 }
7614 }
7615 }
7616
7617 // C++ [over.built]p19:
7618 //
7619 // For every pair (T, VQ), where T is any type and VQ is either
7620 // volatile or empty, there exist candidate operator functions
7621 // of the form
7622 //
7623 // T*VQ& operator=(T*VQ&, T*);
7624 //
7625 // C++ [over.built]p21:
7626 //
7627 // For every pair (T, VQ), where T is a cv-qualified or
7628 // cv-unqualified object type and VQ is either volatile or
7629 // empty, there exist candidate operator functions of the form
7630 //
7631 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7632 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7633 void addAssignmentPointerOverloads(bool isEqualOp) {
7634 /// Set of (canonical) types that we've already handled.
7635 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7636
7637 for (BuiltinCandidateTypeSet::iterator
7638 Ptr = CandidateTypes[0].pointer_begin(),
7639 PtrEnd = CandidateTypes[0].pointer_end();
7640 Ptr != PtrEnd; ++Ptr) {
7641 // If this is operator=, keep track of the builtin candidates we added.
7642 if (isEqualOp)
7643 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007644 else if (!(*Ptr)->getPointeeType()->isObjectType())
7645 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007646
7647 // non-volatile version
7648 QualType ParamTypes[2] = {
7649 S.Context.getLValueReferenceType(*Ptr),
7650 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7651 };
Richard Smithe54c3072013-05-05 15:51:06 +00007652 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007653 /*IsAssigmentOperator=*/ isEqualOp);
7654
Douglas Gregor5bee2582012-06-04 00:15:09 +00007655 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7656 VisibleTypeConversionsQuals.hasVolatile();
7657 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007658 // volatile version
7659 ParamTypes[0] =
7660 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007661 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007662 /*IsAssigmentOperator=*/isEqualOp);
7663 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007664
7665 if (!(*Ptr).isRestrictQualified() &&
7666 VisibleTypeConversionsQuals.hasRestrict()) {
7667 // restrict version
7668 ParamTypes[0]
7669 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007670 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007671 /*IsAssigmentOperator=*/isEqualOp);
7672
7673 if (NeedVolatile) {
7674 // volatile restrict version
7675 ParamTypes[0]
7676 = S.Context.getLValueReferenceType(
7677 S.Context.getCVRQualifiedType(*Ptr,
7678 (Qualifiers::Volatile |
7679 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007680 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007681 /*IsAssigmentOperator=*/isEqualOp);
7682 }
7683 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007684 }
7685
7686 if (isEqualOp) {
7687 for (BuiltinCandidateTypeSet::iterator
7688 Ptr = CandidateTypes[1].pointer_begin(),
7689 PtrEnd = CandidateTypes[1].pointer_end();
7690 Ptr != PtrEnd; ++Ptr) {
7691 // Make sure we don't add the same candidate twice.
7692 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7693 continue;
7694
Chandler Carruth8e543b32010-12-12 08:17:55 +00007695 QualType ParamTypes[2] = {
7696 S.Context.getLValueReferenceType(*Ptr),
7697 *Ptr,
7698 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007699
7700 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007701 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007702 /*IsAssigmentOperator=*/true);
7703
Douglas Gregor5bee2582012-06-04 00:15:09 +00007704 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7705 VisibleTypeConversionsQuals.hasVolatile();
7706 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007707 // volatile version
7708 ParamTypes[0] =
7709 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007710 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7711 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007712 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007713
7714 if (!(*Ptr).isRestrictQualified() &&
7715 VisibleTypeConversionsQuals.hasRestrict()) {
7716 // restrict version
7717 ParamTypes[0]
7718 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007719 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7720 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007721
7722 if (NeedVolatile) {
7723 // volatile restrict version
7724 ParamTypes[0]
7725 = S.Context.getLValueReferenceType(
7726 S.Context.getCVRQualifiedType(*Ptr,
7727 (Qualifiers::Volatile |
7728 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007729 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7730 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007731 }
7732 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007733 }
7734 }
7735 }
7736
7737 // C++ [over.built]p18:
7738 //
7739 // For every triple (L, VQ, R), where L is an arithmetic type,
7740 // VQ is either volatile or empty, and R is a promoted
7741 // arithmetic type, there exist candidate operator functions of
7742 // the form
7743 //
7744 // VQ L& operator=(VQ L&, R);
7745 // VQ L& operator*=(VQ L&, R);
7746 // VQ L& operator/=(VQ L&, R);
7747 // VQ L& operator+=(VQ L&, R);
7748 // VQ L& operator-=(VQ L&, R);
7749 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007750 if (!HasArithmeticOrEnumeralCandidateType)
7751 return;
7752
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007753 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7754 for (unsigned Right = FirstPromotedArithmeticType;
7755 Right < LastPromotedArithmeticType; ++Right) {
7756 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007757 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007758
7759 // Add this built-in operator as a candidate (VQ is empty).
7760 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007761 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007762 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007763 /*IsAssigmentOperator=*/isEqualOp);
7764
7765 // Add this built-in operator as a candidate (VQ is 'volatile').
7766 if (VisibleTypeConversionsQuals.hasVolatile()) {
7767 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007768 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007769 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007770 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007771 /*IsAssigmentOperator=*/isEqualOp);
7772 }
7773 }
7774 }
7775
7776 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7777 for (BuiltinCandidateTypeSet::iterator
7778 Vec1 = CandidateTypes[0].vector_begin(),
7779 Vec1End = CandidateTypes[0].vector_end();
7780 Vec1 != Vec1End; ++Vec1) {
7781 for (BuiltinCandidateTypeSet::iterator
7782 Vec2 = CandidateTypes[1].vector_begin(),
7783 Vec2End = CandidateTypes[1].vector_end();
7784 Vec2 != Vec2End; ++Vec2) {
7785 QualType ParamTypes[2];
7786 ParamTypes[1] = *Vec2;
7787 // Add this built-in operator as a candidate (VQ is empty).
7788 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007789 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007790 /*IsAssigmentOperator=*/isEqualOp);
7791
7792 // Add this built-in operator as a candidate (VQ is 'volatile').
7793 if (VisibleTypeConversionsQuals.hasVolatile()) {
7794 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7795 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007796 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007797 /*IsAssigmentOperator=*/isEqualOp);
7798 }
7799 }
7800 }
7801 }
7802
7803 // C++ [over.built]p22:
7804 //
7805 // For every triple (L, VQ, R), where L is an integral type, VQ
7806 // is either volatile or empty, and R is a promoted integral
7807 // type, there exist candidate operator functions of the form
7808 //
7809 // VQ L& operator%=(VQ L&, R);
7810 // VQ L& operator<<=(VQ L&, R);
7811 // VQ L& operator>>=(VQ L&, R);
7812 // VQ L& operator&=(VQ L&, R);
7813 // VQ L& operator^=(VQ L&, R);
7814 // VQ L& operator|=(VQ L&, R);
7815 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007816 if (!HasArithmeticOrEnumeralCandidateType)
7817 return;
7818
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007819 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7820 for (unsigned Right = FirstPromotedIntegralType;
7821 Right < LastPromotedIntegralType; ++Right) {
7822 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007823 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007824
7825 // Add this built-in operator as a candidate (VQ is empty).
7826 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007827 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007828 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007829 if (VisibleTypeConversionsQuals.hasVolatile()) {
7830 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007831 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007832 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7833 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007834 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007835 }
7836 }
7837 }
7838 }
7839
7840 // C++ [over.operator]p23:
7841 //
7842 // There also exist candidate operator functions of the form
7843 //
7844 // bool operator!(bool);
7845 // bool operator&&(bool, bool);
7846 // bool operator||(bool, bool);
7847 void addExclaimOverload() {
7848 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007849 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007850 /*IsAssignmentOperator=*/false,
7851 /*NumContextualBoolArguments=*/1);
7852 }
7853 void addAmpAmpOrPipePipeOverload() {
7854 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007855 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007856 /*IsAssignmentOperator=*/false,
7857 /*NumContextualBoolArguments=*/2);
7858 }
7859
7860 // C++ [over.built]p13:
7861 //
7862 // For every cv-qualified or cv-unqualified object type T there
7863 // exist candidate operator functions of the form
7864 //
7865 // T* operator+(T*, ptrdiff_t); [ABOVE]
7866 // T& operator[](T*, ptrdiff_t);
7867 // T* operator-(T*, ptrdiff_t); [ABOVE]
7868 // T* operator+(ptrdiff_t, T*); [ABOVE]
7869 // T& operator[](ptrdiff_t, T*);
7870 void addSubscriptOverloads() {
7871 for (BuiltinCandidateTypeSet::iterator
7872 Ptr = CandidateTypes[0].pointer_begin(),
7873 PtrEnd = CandidateTypes[0].pointer_end();
7874 Ptr != PtrEnd; ++Ptr) {
7875 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7876 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007877 if (!PointeeType->isObjectType())
7878 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007879
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007880 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7881
7882 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00007883 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007884 }
7885
7886 for (BuiltinCandidateTypeSet::iterator
7887 Ptr = CandidateTypes[1].pointer_begin(),
7888 PtrEnd = CandidateTypes[1].pointer_end();
7889 Ptr != PtrEnd; ++Ptr) {
7890 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7891 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007892 if (!PointeeType->isObjectType())
7893 continue;
7894
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007895 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7896
7897 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00007898 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007899 }
7900 }
7901
7902 // C++ [over.built]p11:
7903 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7904 // C1 is the same type as C2 or is a derived class of C2, T is an object
7905 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7906 // there exist candidate operator functions of the form
7907 //
7908 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7909 //
7910 // where CV12 is the union of CV1 and CV2.
7911 void addArrowStarOverloads() {
7912 for (BuiltinCandidateTypeSet::iterator
7913 Ptr = CandidateTypes[0].pointer_begin(),
7914 PtrEnd = CandidateTypes[0].pointer_end();
7915 Ptr != PtrEnd; ++Ptr) {
7916 QualType C1Ty = (*Ptr);
7917 QualType C1;
7918 QualifierCollector Q1;
7919 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7920 if (!isa<RecordType>(C1))
7921 continue;
7922 // heuristic to reduce number of builtin candidates in the set.
7923 // Add volatile/restrict version only if there are conversions to a
7924 // volatile/restrict type.
7925 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7926 continue;
7927 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7928 continue;
7929 for (BuiltinCandidateTypeSet::iterator
7930 MemPtr = CandidateTypes[1].member_pointer_begin(),
7931 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7932 MemPtr != MemPtrEnd; ++MemPtr) {
7933 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7934 QualType C2 = QualType(mptr->getClass(), 0);
7935 C2 = C2.getUnqualifiedType();
7936 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7937 break;
7938 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7939 // build CV12 T&
7940 QualType T = mptr->getPointeeType();
7941 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7942 T.isVolatileQualified())
7943 continue;
7944 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7945 T.isRestrictQualified())
7946 continue;
7947 T = Q1.apply(S.Context, T);
7948 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00007949 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007950 }
7951 }
7952 }
7953
7954 // Note that we don't consider the first argument, since it has been
7955 // contextually converted to bool long ago. The candidates below are
7956 // therefore added as binary.
7957 //
7958 // C++ [over.built]p25:
7959 // For every type T, where T is a pointer, pointer-to-member, or scoped
7960 // enumeration type, there exist candidate operator functions of the form
7961 //
7962 // T operator?(bool, T, T);
7963 //
7964 void addConditionalOperatorOverloads() {
7965 /// Set of (canonical) types that we've already handled.
7966 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7967
7968 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7969 for (BuiltinCandidateTypeSet::iterator
7970 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7971 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7972 Ptr != PtrEnd; ++Ptr) {
7973 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7974 continue;
7975
7976 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007977 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007978 }
7979
7980 for (BuiltinCandidateTypeSet::iterator
7981 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7982 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7983 MemPtr != MemPtrEnd; ++MemPtr) {
7984 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7985 continue;
7986
7987 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007988 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007989 }
7990
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007991 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007992 for (BuiltinCandidateTypeSet::iterator
7993 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7994 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7995 Enum != EnumEnd; ++Enum) {
7996 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7997 continue;
7998
7999 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
8000 continue;
8001
8002 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008003 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008004 }
8005 }
8006 }
8007 }
8008};
8009
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008010} // end anonymous namespace
8011
8012/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8013/// operator overloads to the candidate set (C++ [over.built]), based
8014/// on the operator @p Op and the arguments given. For example, if the
8015/// operator is a binary '+', this routine might add "int
8016/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008017void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8018 SourceLocation OpLoc,
8019 ArrayRef<Expr *> Args,
8020 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008021 // Find all of the types that the arguments can convert to, but only
8022 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008023 // that make use of these types. Also record whether we encounter non-record
8024 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008025 Qualifiers VisibleTypeConversionsQuals;
8026 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008027 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008028 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008029
8030 bool HasNonRecordCandidateType = false;
8031 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008032 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008033 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008034 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
8035 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8036 OpLoc,
8037 true,
8038 (Op == OO_Exclaim ||
8039 Op == OO_AmpAmp ||
8040 Op == OO_PipePipe),
8041 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008042 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8043 CandidateTypes[ArgIdx].hasNonRecordTypes();
8044 HasArithmeticOrEnumeralCandidateType =
8045 HasArithmeticOrEnumeralCandidateType ||
8046 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008047 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008048
Chandler Carruth00a38332010-12-13 01:44:01 +00008049 // Exit early when no non-record types have been added to the candidate set
8050 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008051 //
8052 // We can't exit early for !, ||, or &&, since there we have always have
8053 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008054 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008055 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008056 return;
8057
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008058 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008059 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008060 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008061 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008062 CandidateTypes, CandidateSet);
8063
8064 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008065 switch (Op) {
8066 case OO_None:
8067 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008068 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008069
Chandler Carruth5184de02010-12-12 08:51:33 +00008070 case OO_New:
8071 case OO_Delete:
8072 case OO_Array_New:
8073 case OO_Array_Delete:
8074 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008075 llvm_unreachable(
8076 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008077
8078 case OO_Comma:
8079 case OO_Arrow:
8080 // C++ [over.match.oper]p3:
8081 // -- For the operator ',', the unary operator '&', or the
8082 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008083 break;
8084
8085 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008086 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008087 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008088 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008089
8090 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008091 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008092 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008093 } else {
8094 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8095 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8096 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008097 break;
8098
Chandler Carruth5184de02010-12-12 08:51:33 +00008099 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008100 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008101 OpBuilder.addUnaryStarPointerOverloads();
8102 else
8103 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8104 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008105
Chandler Carruth5184de02010-12-12 08:51:33 +00008106 case OO_Slash:
8107 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008108 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008109
8110 case OO_PlusPlus:
8111 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008112 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8113 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008114 break;
8115
Douglas Gregor84605ae2009-08-24 13:43:27 +00008116 case OO_EqualEqual:
8117 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008118 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008119 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008120
Douglas Gregora11693b2008-11-12 17:17:38 +00008121 case OO_Less:
8122 case OO_Greater:
8123 case OO_LessEqual:
8124 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008125 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008126 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8127 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008128
Douglas Gregora11693b2008-11-12 17:17:38 +00008129 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008130 case OO_Caret:
8131 case OO_Pipe:
8132 case OO_LessLess:
8133 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008134 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008135 break;
8136
Chandler Carruth5184de02010-12-12 08:51:33 +00008137 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008138 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008139 // C++ [over.match.oper]p3:
8140 // -- For the operator ',', the unary operator '&', or the
8141 // operator '->', the built-in candidates set is empty.
8142 break;
8143
8144 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8145 break;
8146
8147 case OO_Tilde:
8148 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8149 break;
8150
Douglas Gregora11693b2008-11-12 17:17:38 +00008151 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008152 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008153 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008154
8155 case OO_PlusEqual:
8156 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008157 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008158 // Fall through.
8159
8160 case OO_StarEqual:
8161 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008162 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008163 break;
8164
8165 case OO_PercentEqual:
8166 case OO_LessLessEqual:
8167 case OO_GreaterGreaterEqual:
8168 case OO_AmpEqual:
8169 case OO_CaretEqual:
8170 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008171 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008172 break;
8173
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008174 case OO_Exclaim:
8175 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008176 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008177
Douglas Gregora11693b2008-11-12 17:17:38 +00008178 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008179 case OO_PipePipe:
8180 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008181 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008182
8183 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008184 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008185 break;
8186
8187 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008188 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008189 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008190
8191 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008192 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008193 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8194 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008195 }
8196}
8197
Douglas Gregore254f902009-02-04 00:32:51 +00008198/// \brief Add function candidates found via argument-dependent lookup
8199/// to the set of overloading candidates.
8200///
8201/// This routine performs argument-dependent name lookup based on the
8202/// given function name (which may also be an operator name) and adds
8203/// all of the overload candidates found by ADL to the overload
8204/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008205void
Douglas Gregore254f902009-02-04 00:32:51 +00008206Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008207 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008208 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008209 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008210 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008211 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008212 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008213
John McCall91f61fc2010-01-26 06:04:06 +00008214 // FIXME: This approach for uniquing ADL results (and removing
8215 // redundant candidates from the set) relies on pointer-equality,
8216 // which means we need to key off the canonical decl. However,
8217 // always going back to the canonical decl might not get us the
8218 // right set of default arguments. What default arguments are
8219 // we supposed to consider on ADL candidates, anyway?
8220
Douglas Gregorcabea402009-09-22 15:41:20 +00008221 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008222 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008223
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008224 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008225 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8226 CandEnd = CandidateSet.end();
8227 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008228 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008229 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008230 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008231 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008232 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008233
8234 // For each of the ADL candidates we found, add it to the overload
8235 // set.
John McCall8fe68082010-01-26 07:16:45 +00008236 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008237 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008238 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008239 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008240 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008241
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008242 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8243 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008244 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008245 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008246 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008247 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00008248 }
Douglas Gregore254f902009-02-04 00:32:51 +00008249}
8250
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008251/// isBetterOverloadCandidate - Determines whether the first overload
8252/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008253bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8254 const OverloadCandidate &Cand2,
8255 SourceLocation Loc,
8256 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008257 // Define viable functions to be better candidates than non-viable
8258 // functions.
8259 if (!Cand2.Viable)
8260 return Cand1.Viable;
8261 else if (!Cand1.Viable)
8262 return false;
8263
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008264 // C++ [over.match.best]p1:
8265 //
8266 // -- if F is a static member function, ICS1(F) is defined such
8267 // that ICS1(F) is neither better nor worse than ICS1(G) for
8268 // any function G, and, symmetrically, ICS1(G) is neither
8269 // better nor worse than ICS1(F).
8270 unsigned StartArg = 0;
8271 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8272 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008273
Douglas Gregord3cb3562009-07-07 23:38:56 +00008274 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008275 // A viable function F1 is defined to be a better function than another
8276 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008277 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008278 unsigned NumArgs = Cand1.NumConversions;
8279 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008280 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008281 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008282 switch (CompareImplicitConversionSequences(S,
8283 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008284 Cand2.Conversions[ArgIdx])) {
8285 case ImplicitConversionSequence::Better:
8286 // Cand1 has a better conversion sequence.
8287 HasBetterConversion = true;
8288 break;
8289
8290 case ImplicitConversionSequence::Worse:
8291 // Cand1 can't be better than Cand2.
8292 return false;
8293
8294 case ImplicitConversionSequence::Indistinguishable:
8295 // Do nothing.
8296 break;
8297 }
8298 }
8299
Mike Stump11289f42009-09-09 15:08:12 +00008300 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008301 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008302 if (HasBetterConversion)
8303 return true;
8304
Douglas Gregora1f013e2008-11-07 22:36:19 +00008305 // -- the context is an initialization by user-defined conversion
8306 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8307 // from the return type of F1 to the destination type (i.e.,
8308 // the type of the entity being initialized) is a better
8309 // conversion sequence than the standard conversion sequence
8310 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008311 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008312 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008313 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008314 // First check whether we prefer one of the conversion functions over the
8315 // other. This only distinguishes the results in non-standard, extension
8316 // cases such as the conversion from a lambda closure type to a function
8317 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008318 ImplicitConversionSequence::CompareKind Result =
8319 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8320 if (Result == ImplicitConversionSequence::Indistinguishable)
8321 Result = CompareStandardConversionSequences(S,
8322 Cand1.FinalConversion,
8323 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008324
Richard Smithec2748a2014-05-17 04:36:39 +00008325 if (Result != ImplicitConversionSequence::Indistinguishable)
8326 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008327
8328 // FIXME: Compare kind of reference binding if conversion functions
8329 // convert to a reference type used in direct reference binding, per
8330 // C++14 [over.match.best]p1 section 2 bullet 3.
8331 }
8332
8333 // -- F1 is a non-template function and F2 is a function template
8334 // specialization, or, if not that,
8335 bool Cand1IsSpecialization = Cand1.Function &&
8336 Cand1.Function->getPrimaryTemplate();
8337 bool Cand2IsSpecialization = Cand2.Function &&
8338 Cand2.Function->getPrimaryTemplate();
8339 if (Cand1IsSpecialization != Cand2IsSpecialization)
8340 return Cand2IsSpecialization;
8341
8342 // -- F1 and F2 are function template specializations, and the function
8343 // template for F1 is more specialized than the template for F2
8344 // according to the partial ordering rules described in 14.5.5.2, or,
8345 // if not that,
8346 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8347 if (FunctionTemplateDecl *BetterTemplate
8348 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8349 Cand2.Function->getPrimaryTemplate(),
8350 Loc,
8351 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8352 : TPOC_Call,
8353 Cand1.ExplicitCallArguments,
8354 Cand2.ExplicitCallArguments))
8355 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008356 }
8357
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008358 // Check for enable_if value-based overload resolution.
8359 if (Cand1.Function && Cand2.Function &&
8360 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8361 Cand2.Function->hasAttr<EnableIfAttr>())) {
8362 // FIXME: The next several lines are just
8363 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8364 // instead of reverse order which is how they're stored in the AST.
8365 AttrVec Cand1Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008366 if (Cand1.Function->hasAttrs()) {
8367 Cand1Attrs = Cand1.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008368 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8369 IsNotEnableIfAttr),
8370 Cand1Attrs.end());
8371 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008372 }
8373
8374 AttrVec Cand2Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008375 if (Cand2.Function->hasAttrs()) {
8376 Cand2Attrs = Cand2.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008377 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8378 IsNotEnableIfAttr),
8379 Cand2Attrs.end());
8380 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008381 }
Richard Smith9516eee2014-05-17 02:21:47 +00008382
8383 // Candidate 1 is better if it has strictly more attributes and
8384 // the common sequence is identical.
8385 if (Cand1Attrs.size() <= Cand2Attrs.size())
8386 return false;
8387
8388 auto Cand1I = Cand1Attrs.begin();
8389 for (auto &Cand2A : Cand2Attrs) {
8390 auto &Cand1A = *Cand1I++;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008391 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
Richard Smith9516eee2014-05-17 02:21:47 +00008392 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8393 S.getASTContext(), true);
8394 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8395 S.getASTContext(), true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00008396 if (Cand1ID != Cand2ID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008397 return false;
8398 }
Richard Smith9516eee2014-05-17 02:21:47 +00008399
8400 return true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008401 }
8402
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008403 return false;
8404}
8405
Mike Stump11289f42009-09-09 15:08:12 +00008406/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008407/// within an overload candidate set.
8408///
James Dennettffad8b72012-06-22 08:10:18 +00008409/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008410/// which overload resolution occurs.
8411///
James Dennettffad8b72012-06-22 08:10:18 +00008412/// \param Best If overload resolution was successful or found a deleted
8413/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008414///
8415/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008416OverloadingResult
8417OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008418 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008419 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008420 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008421 Best = end();
8422 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8423 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008424 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008425 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008426 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008427 }
8428
8429 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008430 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008431 return OR_No_Viable_Function;
8432
8433 // Make sure that this function is better than every other viable
8434 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008435 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008436 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008437 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008438 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008439 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00008440 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008441 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008442 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008443 }
Mike Stump11289f42009-09-09 15:08:12 +00008444
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008445 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008446 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008447 (Best->Function->isDeleted() ||
8448 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008449 return OR_Deleted;
8450
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008451 return OR_Success;
8452}
8453
John McCall53262c92010-01-12 02:15:36 +00008454namespace {
8455
8456enum OverloadCandidateKind {
8457 oc_function,
8458 oc_method,
8459 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008460 oc_function_template,
8461 oc_method_template,
8462 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008463 oc_implicit_default_constructor,
8464 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008465 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008466 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008467 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008468 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008469};
8470
John McCalle1ac8d12010-01-13 00:25:19 +00008471OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8472 FunctionDecl *Fn,
8473 std::string &Description) {
8474 bool isTemplate = false;
8475
8476 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8477 isTemplate = true;
8478 Description = S.getTemplateArgumentBindingsText(
8479 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8480 }
John McCallfd0b2f82010-01-06 09:43:14 +00008481
8482 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008483 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008484 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008485
Sebastian Redl08905022011-02-05 19:23:19 +00008486 if (Ctor->getInheritedConstructor())
8487 return oc_implicit_inherited_constructor;
8488
Alexis Hunt119c10e2011-05-25 23:16:36 +00008489 if (Ctor->isDefaultConstructor())
8490 return oc_implicit_default_constructor;
8491
8492 if (Ctor->isMoveConstructor())
8493 return oc_implicit_move_constructor;
8494
8495 assert(Ctor->isCopyConstructor() &&
8496 "unexpected sort of implicit constructor");
8497 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008498 }
8499
8500 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8501 // This actually gets spelled 'candidate function' for now, but
8502 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008503 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008504 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008505
Alexis Hunt119c10e2011-05-25 23:16:36 +00008506 if (Meth->isMoveAssignmentOperator())
8507 return oc_implicit_move_assignment;
8508
Douglas Gregor12695102012-02-10 08:36:38 +00008509 if (Meth->isCopyAssignmentOperator())
8510 return oc_implicit_copy_assignment;
8511
8512 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8513 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008514 }
8515
John McCalle1ac8d12010-01-13 00:25:19 +00008516 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008517}
8518
Larisse Voufo98b20f12013-07-19 23:00:19 +00008519void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008520 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8521 if (!Ctor) return;
8522
8523 Ctor = Ctor->getInheritedConstructor();
8524 if (!Ctor) return;
8525
8526 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8527}
8528
John McCall53262c92010-01-12 02:15:36 +00008529} // end anonymous namespace
8530
8531// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00008532void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00008533 std::string FnDesc;
8534 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008535 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8536 << (unsigned) K << FnDesc;
8537 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8538 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008539 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008540}
8541
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008542// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008543// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00008544void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008545 assert(OverloadedExpr->getType() == Context.OverloadTy);
8546
8547 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8548 OverloadExpr *OvlExpr = Ovl.Expression;
8549
8550 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8551 IEnd = OvlExpr->decls_end();
8552 I != IEnd; ++I) {
8553 if (FunctionTemplateDecl *FunTmpl =
8554 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008555 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008556 } else if (FunctionDecl *Fun
8557 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008558 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008559 }
8560 }
8561}
8562
John McCall0d1da222010-01-12 00:44:57 +00008563/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8564/// "lead" diagnostic; it will be given two arguments, the source and
8565/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008566void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8567 Sema &S,
8568 SourceLocation CaretLoc,
8569 const PartialDiagnostic &PDiag) const {
8570 S.Diag(CaretLoc, PDiag)
8571 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008572 // FIXME: The note limiting machinery is borrowed from
8573 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8574 // refactoring here.
8575 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8576 unsigned CandsShown = 0;
8577 AmbiguousConversionSequence::const_iterator I, E;
8578 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8579 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8580 break;
8581 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008582 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008583 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008584 if (I != E)
8585 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008586}
8587
Richard Smith17c00b42014-11-12 01:24:00 +00008588static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8589 unsigned I) {
John McCall6a61b522010-01-13 09:16:55 +00008590 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8591 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008592 assert(Cand->Function && "for now, candidate must be a function");
8593 FunctionDecl *Fn = Cand->Function;
8594
8595 // There's a conversion slot for the object argument if this is a
8596 // non-constructor method. Note that 'I' corresponds the
8597 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008598 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008599 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008600 if (I == 0)
8601 isObjectArgument = true;
8602 else
8603 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008604 }
8605
John McCalle1ac8d12010-01-13 00:25:19 +00008606 std::string FnDesc;
8607 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8608
John McCall6a61b522010-01-13 09:16:55 +00008609 Expr *FromExpr = Conv.Bad.FromExpr;
8610 QualType FromTy = Conv.Bad.getFromType();
8611 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008612
John McCallfb7ad0f2010-02-02 02:42:52 +00008613 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008614 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008615 Expr *E = FromExpr->IgnoreParens();
8616 if (isa<UnaryOperator>(E))
8617 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008618 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008619
8620 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8621 << (unsigned) FnKind << FnDesc
8622 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8623 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008624 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008625 return;
8626 }
8627
John McCall6d174642010-01-23 08:10:49 +00008628 // Do some hand-waving analysis to see if the non-viability is due
8629 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008630 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8631 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8632 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8633 CToTy = RT->getPointeeType();
8634 else {
8635 // TODO: detect and diagnose the full richness of const mismatches.
8636 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8637 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8638 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8639 }
8640
8641 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8642 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008643 Qualifiers FromQs = CFromTy.getQualifiers();
8644 Qualifiers ToQs = CToTy.getQualifiers();
8645
8646 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8647 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8648 << (unsigned) FnKind << FnDesc
8649 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8650 << FromTy
8651 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8652 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008653 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008654 return;
8655 }
8656
John McCall31168b02011-06-15 23:02:42 +00008657 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008658 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008659 << (unsigned) FnKind << FnDesc
8660 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8661 << FromTy
8662 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8663 << (unsigned) isObjectArgument << I+1;
8664 MaybeEmitInheritedConstructorNote(S, Fn);
8665 return;
8666 }
8667
Douglas Gregoraec25842011-04-26 23:16:46 +00008668 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8669 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8670 << (unsigned) FnKind << FnDesc
8671 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8672 << FromTy
8673 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8674 << (unsigned) isObjectArgument << I+1;
8675 MaybeEmitInheritedConstructorNote(S, Fn);
8676 return;
8677 }
8678
John McCall47000992010-01-14 03:28:57 +00008679 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8680 assert(CVR && "unexpected qualifiers mismatch");
8681
8682 if (isObjectArgument) {
8683 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8684 << (unsigned) FnKind << FnDesc
8685 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8686 << FromTy << (CVR - 1);
8687 } else {
8688 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8689 << (unsigned) FnKind << FnDesc
8690 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8691 << FromTy << (CVR - 1) << I+1;
8692 }
Sebastian Redl08905022011-02-05 19:23:19 +00008693 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008694 return;
8695 }
8696
Sebastian Redla72462c2011-09-24 17:48:32 +00008697 // Special diagnostic for failure to convert an initializer list, since
8698 // telling the user that it has type void is not useful.
8699 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8700 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8701 << (unsigned) FnKind << FnDesc
8702 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8703 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8704 MaybeEmitInheritedConstructorNote(S, Fn);
8705 return;
8706 }
8707
John McCall6d174642010-01-23 08:10:49 +00008708 // Diagnose references or pointers to incomplete types differently,
8709 // since it's far from impossible that the incompleteness triggered
8710 // the failure.
8711 QualType TempFromTy = FromTy.getNonReferenceType();
8712 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8713 TempFromTy = PTy->getPointeeType();
8714 if (TempFromTy->isIncompleteType()) {
8715 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8716 << (unsigned) FnKind << FnDesc
8717 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8718 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008719 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008720 return;
8721 }
8722
Douglas Gregor56f2e342010-06-30 23:01:39 +00008723 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008724 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008725 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8726 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8727 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8728 FromPtrTy->getPointeeType()) &&
8729 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8730 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008731 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008732 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008733 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008734 }
8735 } else if (const ObjCObjectPointerType *FromPtrTy
8736 = FromTy->getAs<ObjCObjectPointerType>()) {
8737 if (const ObjCObjectPointerType *ToPtrTy
8738 = ToTy->getAs<ObjCObjectPointerType>())
8739 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8740 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8741 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8742 FromPtrTy->getPointeeType()) &&
8743 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008744 BaseToDerivedConversion = 2;
8745 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008746 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8747 !FromTy->isIncompleteType() &&
8748 !ToRefTy->getPointeeType()->isIncompleteType() &&
8749 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8750 BaseToDerivedConversion = 3;
8751 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8752 ToTy.getNonReferenceType().getCanonicalType() ==
8753 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008754 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8755 << (unsigned) FnKind << FnDesc
8756 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8757 << (unsigned) isObjectArgument << I + 1;
8758 MaybeEmitInheritedConstructorNote(S, Fn);
8759 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008760 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008761 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008762
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008763 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008764 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008765 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008766 << (unsigned) FnKind << FnDesc
8767 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008768 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008769 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008770 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008771 return;
8772 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008773
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008774 if (isa<ObjCObjectPointerType>(CFromTy) &&
8775 isa<PointerType>(CToTy)) {
8776 Qualifiers FromQs = CFromTy.getQualifiers();
8777 Qualifiers ToQs = CToTy.getQualifiers();
8778 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8779 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8780 << (unsigned) FnKind << FnDesc
8781 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8782 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8783 MaybeEmitInheritedConstructorNote(S, Fn);
8784 return;
8785 }
8786 }
8787
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008788 // Emit the generic diagnostic and, optionally, add the hints to it.
8789 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8790 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008791 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008792 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8793 << (unsigned) (Cand->Fix.Kind);
8794
8795 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008796 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8797 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008798 FDiag << *HI;
8799 S.Diag(Fn->getLocation(), FDiag);
8800
Sebastian Redl08905022011-02-05 19:23:19 +00008801 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008802}
8803
Larisse Voufo98b20f12013-07-19 23:00:19 +00008804/// Additional arity mismatch diagnosis specific to a function overload
8805/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8806/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008807static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8808 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00008809 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00008810 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008811
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008812 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00008813 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008814 // right number of arguments, because only overloaded operators have
8815 // the weird behavior of overloading member and non-member functions.
8816 // Just don't report anything.
8817 if (Fn->isInvalidDecl() &&
8818 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008819 return true;
8820
8821 if (NumArgs < MinParams) {
8822 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8823 (Cand->FailureKind == ovl_fail_bad_deduction &&
8824 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8825 } else {
8826 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8827 (Cand->FailureKind == ovl_fail_bad_deduction &&
8828 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8829 }
8830
8831 return false;
8832}
8833
8834/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008835static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008836 assert(isa<FunctionDecl>(D) &&
8837 "The templated declaration should at least be a function"
8838 " when diagnosing bad template argument deduction due to too many"
8839 " or too few arguments");
8840
8841 FunctionDecl *Fn = cast<FunctionDecl>(D);
8842
8843 // TODO: treat calls to a missing default constructor as a special case
8844 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8845 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008846
John McCall6a61b522010-01-13 09:16:55 +00008847 // at least / at most / exactly
8848 unsigned mode, modeCount;
8849 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00008850 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8851 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008852 mode = 0; // "at least"
8853 else
8854 mode = 2; // "exactly"
8855 modeCount = MinParams;
8856 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00008857 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00008858 mode = 1; // "at most"
8859 else
8860 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00008861 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00008862 }
8863
8864 std::string Description;
8865 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8866
Richard Smith10ff50d2012-05-11 05:16:41 +00008867 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8868 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00008869 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8870 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00008871 else
8872 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00008873 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8874 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008875 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008876}
8877
Larisse Voufo98b20f12013-07-19 23:00:19 +00008878/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00008879static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8880 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008881 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8882 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8883}
Larisse Voufo47c08452013-07-19 22:53:23 +00008884
Richard Smith17c00b42014-11-12 01:24:00 +00008885static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008886 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8887 return FD->getDescribedFunctionTemplate();
8888 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8889 return RD->getDescribedClassTemplate();
8890
8891 llvm_unreachable("Unsupported: Getting the described template declaration"
8892 " for bad deduction diagnosis");
8893}
8894
8895/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00008896static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8897 DeductionFailureInfo &DeductionFailure,
8898 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008899 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008900 NamedDecl *ParamD;
8901 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8902 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8903 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00008904 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00008905 case Sema::TDK_Success:
8906 llvm_unreachable("TDK_success while diagnosing bad deduction");
8907
8908 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008909 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00008910 S.Diag(Templated->getLocation(),
8911 diag::note_ovl_candidate_incomplete_deduction)
8912 << ParamD->getDeclName();
8913 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008914 return;
8915 }
8916
John McCall42d7d192010-08-05 09:05:08 +00008917 case Sema::TDK_Underqualified: {
8918 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8919 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8920
Larisse Voufo98b20f12013-07-19 23:00:19 +00008921 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008922
8923 // Param will have been canonicalized, but it should just be a
8924 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008925 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008926 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008927 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008928 assert(S.Context.hasSameType(Param, NonCanonParam));
8929
8930 // Arg has also been canonicalized, but there's nothing we can do
8931 // about that. It also doesn't matter as much, because it won't
8932 // have any template parameters in it (because deduction isn't
8933 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00008934 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008935
Larisse Voufo98b20f12013-07-19 23:00:19 +00008936 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8937 << ParamD->getDeclName() << Arg << NonCanonParam;
8938 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00008939 return;
8940 }
8941
8942 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008943 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008944 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008945 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008946 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008947 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008948 which = 1;
8949 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008950 which = 2;
8951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008952
Larisse Voufo98b20f12013-07-19 23:00:19 +00008953 S.Diag(Templated->getLocation(),
8954 diag::note_ovl_candidate_inconsistent_deduction)
8955 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8956 << *DeductionFailure.getSecondArg();
8957 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008958 return;
8959 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008960
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008961 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008962 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008963 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00008964 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008965 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008966 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008967 else {
8968 int index = 0;
8969 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8970 index = TTP->getIndex();
8971 else if (NonTypeTemplateParmDecl *NTTP
8972 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8973 index = NTTP->getIndex();
8974 else
8975 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008976 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008977 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008978 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008979 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00008980 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008981 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008982
Douglas Gregor02eb4832010-05-08 18:13:28 +00008983 case Sema::TDK_TooManyArguments:
8984 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008985 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00008986 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008987
8988 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008989 S.Diag(Templated->getLocation(),
8990 diag::note_ovl_candidate_instantiation_depth);
8991 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00008992 return;
8993
8994 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00008995 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008996 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00008997 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00008998 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00008999 TemplateArgString = " ";
9000 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009001 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009002 }
9003
Richard Smith6f8d2c62012-05-09 05:17:00 +00009004 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009005 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009006 if (PDiag && PDiag->second.getDiagID() ==
9007 diag::err_typename_nested_not_found_enable_if) {
9008 // FIXME: Use the source range of the condition, and the fully-qualified
9009 // name of the enable_if template. These are both present in PDiag.
9010 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9011 << "'enable_if'" << TemplateArgString;
9012 return;
9013 }
9014
Richard Smith9ca64612012-05-07 09:03:25 +00009015 // Format the SFINAE diagnostic into the argument string.
9016 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9017 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009018 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009019 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009020 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009021 SFINAEArgString = ": ";
9022 R = SourceRange(PDiag->first, PDiag->first);
9023 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9024 }
9025
Larisse Voufo98b20f12013-07-19 23:00:19 +00009026 S.Diag(Templated->getLocation(),
9027 diag::note_ovl_candidate_substitution_failure)
9028 << TemplateArgString << SFINAEArgString << R;
9029 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009030 return;
9031 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009032
Richard Smith8c6eeb92013-01-31 04:03:12 +00009033 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009034 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9035 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009036 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009037 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009038 return;
9039 }
9040
Richard Trieue3732352013-04-08 21:11:40 +00009041 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009042 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009043 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9044 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009045 if (FirstTA.getKind() == TemplateArgument::Template &&
9046 SecondTA.getKind() == TemplateArgument::Template) {
9047 TemplateName FirstTN = FirstTA.getAsTemplate();
9048 TemplateName SecondTN = SecondTA.getAsTemplate();
9049 if (FirstTN.getKind() == TemplateName::Template &&
9050 SecondTN.getKind() == TemplateName::Template) {
9051 if (FirstTN.getAsTemplateDecl()->getName() ==
9052 SecondTN.getAsTemplateDecl()->getName()) {
9053 // FIXME: This fixes a bad diagnostic where both templates are named
9054 // the same. This particular case is a bit difficult since:
9055 // 1) It is passed as a string to the diagnostic printer.
9056 // 2) The diagnostic printer only attempts to find a better
9057 // name for types, not decls.
9058 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009059 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009060 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9061 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9062 return;
9063 }
9064 }
9065 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00009066 // FIXME: For generic lambda parameters, check if the function is a lambda
9067 // call operator, and if so, emit a prettier and more informative
9068 // diagnostic that mentions 'auto' and lambda in addition to
9069 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009070 S.Diag(Templated->getLocation(),
9071 diag::note_ovl_candidate_non_deduced_mismatch)
9072 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009073 return;
Richard Trieue3732352013-04-08 21:11:40 +00009074 }
John McCall8b9ed552010-02-01 18:53:26 +00009075 // TODO: diagnose these individually, then kill off
9076 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009077 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009078 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9079 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009080 return;
9081 }
9082}
9083
Larisse Voufo98b20f12013-07-19 23:00:19 +00009084/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009085static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9086 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009087 unsigned TDK = Cand->DeductionFailure.Result;
9088 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9089 if (CheckArityMismatch(S, Cand, NumArgs))
9090 return;
9091 }
9092 DiagnoseBadDeduction(S, Cand->Function, // pattern
9093 Cand->DeductionFailure, NumArgs);
9094}
9095
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009096/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009097static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009098 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9099 FunctionDecl *Callee = Cand->Function;
9100
9101 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9102 CalleeTarget = S.IdentifyCUDATarget(Callee);
9103
9104 std::string FnDesc;
9105 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9106
9107 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009108 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9109
9110 // This could be an implicit constructor for which we could not infer the
9111 // target due to a collsion. Diagnose that case.
9112 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9113 if (Meth != nullptr && Meth->isImplicit()) {
9114 CXXRecordDecl *ParentClass = Meth->getParent();
9115 Sema::CXXSpecialMember CSM;
9116
9117 switch (FnKind) {
9118 default:
9119 return;
9120 case oc_implicit_default_constructor:
9121 CSM = Sema::CXXDefaultConstructor;
9122 break;
9123 case oc_implicit_copy_constructor:
9124 CSM = Sema::CXXCopyConstructor;
9125 break;
9126 case oc_implicit_move_constructor:
9127 CSM = Sema::CXXMoveConstructor;
9128 break;
9129 case oc_implicit_copy_assignment:
9130 CSM = Sema::CXXCopyAssignment;
9131 break;
9132 case oc_implicit_move_assignment:
9133 CSM = Sema::CXXMoveAssignment;
9134 break;
9135 };
9136
9137 bool ConstRHS = false;
9138 if (Meth->getNumParams()) {
9139 if (const ReferenceType *RT =
9140 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9141 ConstRHS = RT->getPointeeType().isConstQualified();
9142 }
9143 }
9144
9145 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9146 /* ConstRHS */ ConstRHS,
9147 /* Diagnose */ true);
9148 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009149}
9150
Richard Smith17c00b42014-11-12 01:24:00 +00009151static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009152 FunctionDecl *Callee = Cand->Function;
9153 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9154
9155 S.Diag(Callee->getLocation(),
9156 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9157 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9158}
9159
John McCall8b9ed552010-02-01 18:53:26 +00009160/// Generates a 'note' diagnostic for an overload candidate. We've
9161/// already generated a primary error at the call site.
9162///
9163/// It really does need to be a single diagnostic with its caret
9164/// pointed at the candidate declaration. Yes, this creates some
9165/// major challenges of technical writing. Yes, this makes pointing
9166/// out problems with specific arguments quite awkward. It's still
9167/// better than generating twenty screens of text for every failed
9168/// overload.
9169///
9170/// It would be great to be able to express per-candidate problems
9171/// more richly for those diagnostic clients that cared, but we'd
9172/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009173static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9174 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00009175 FunctionDecl *Fn = Cand->Function;
9176
John McCall12f97bc2010-01-08 04:41:39 +00009177 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009178 if (Cand->Viable && (Fn->isDeleted() ||
9179 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009180 std::string FnDesc;
9181 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009182
9183 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009184 << FnKind << FnDesc
9185 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009186 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009187 return;
John McCall12f97bc2010-01-08 04:41:39 +00009188 }
9189
John McCalle1ac8d12010-01-13 00:25:19 +00009190 // We don't really have anything else to say about viable candidates.
9191 if (Cand->Viable) {
9192 S.NoteOverloadCandidate(Fn);
9193 return;
9194 }
John McCall0d1da222010-01-12 00:44:57 +00009195
John McCall6a61b522010-01-13 09:16:55 +00009196 switch (Cand->FailureKind) {
9197 case ovl_fail_too_many_arguments:
9198 case ovl_fail_too_few_arguments:
9199 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009200
John McCall6a61b522010-01-13 09:16:55 +00009201 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009202 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009203
John McCallfe796dd2010-01-23 05:17:32 +00009204 case ovl_fail_trivial_conversion:
9205 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009206 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009207 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009208
John McCall65eb8792010-02-25 01:37:24 +00009209 case ovl_fail_bad_conversion: {
9210 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009211 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009212 if (Cand->Conversions[I].isBad())
9213 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009214
John McCall6a61b522010-01-13 09:16:55 +00009215 // FIXME: this currently happens when we're called from SemaInit
9216 // when user-conversion overload fails. Figure out how to handle
9217 // those conditions and diagnose them well.
9218 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009219 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009220
9221 case ovl_fail_bad_target:
9222 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009223
9224 case ovl_fail_enable_if:
9225 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009226 }
John McCalld3224162010-01-08 00:58:21 +00009227}
9228
Richard Smith17c00b42014-11-12 01:24:00 +00009229static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009230 // Desugar the type of the surrogate down to a function type,
9231 // retaining as many typedefs as possible while still showing
9232 // the function type (and, therefore, its parameter types).
9233 QualType FnType = Cand->Surrogate->getConversionType();
9234 bool isLValueReference = false;
9235 bool isRValueReference = false;
9236 bool isPointer = false;
9237 if (const LValueReferenceType *FnTypeRef =
9238 FnType->getAs<LValueReferenceType>()) {
9239 FnType = FnTypeRef->getPointeeType();
9240 isLValueReference = true;
9241 } else if (const RValueReferenceType *FnTypeRef =
9242 FnType->getAs<RValueReferenceType>()) {
9243 FnType = FnTypeRef->getPointeeType();
9244 isRValueReference = true;
9245 }
9246 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9247 FnType = FnTypePtr->getPointeeType();
9248 isPointer = true;
9249 }
9250 // Desugar down to a function type.
9251 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9252 // Reconstruct the pointer/reference as appropriate.
9253 if (isPointer) FnType = S.Context.getPointerType(FnType);
9254 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9255 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9256
9257 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9258 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009259 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009260}
9261
Richard Smith17c00b42014-11-12 01:24:00 +00009262static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9263 SourceLocation OpLoc,
9264 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009265 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009266 std::string TypeStr("operator");
9267 TypeStr += Opc;
9268 TypeStr += "(";
9269 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009270 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009271 TypeStr += ")";
9272 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9273 } else {
9274 TypeStr += ", ";
9275 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9276 TypeStr += ")";
9277 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9278 }
9279}
9280
Richard Smith17c00b42014-11-12 01:24:00 +00009281static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9282 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009283 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009284 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9285 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009286 if (ICS.isBad()) break; // all meaningless after first invalid
9287 if (!ICS.isAmbiguous()) continue;
9288
John McCall5c32be02010-08-24 20:38:10 +00009289 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009290 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009291 }
9292}
9293
Larisse Voufo98b20f12013-07-19 23:00:19 +00009294static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009295 if (Cand->Function)
9296 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009297 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009298 return Cand->Surrogate->getLocation();
9299 return SourceLocation();
9300}
9301
Larisse Voufo98b20f12013-07-19 23:00:19 +00009302static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009303 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009304 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009305 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009306
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009307 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009308 case Sema::TDK_Incomplete:
9309 return 1;
9310
9311 case Sema::TDK_Underqualified:
9312 case Sema::TDK_Inconsistent:
9313 return 2;
9314
9315 case Sema::TDK_SubstitutionFailure:
9316 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009317 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009318 return 3;
9319
9320 case Sema::TDK_InstantiationDepth:
9321 case Sema::TDK_FailedOverloadResolution:
9322 return 4;
9323
9324 case Sema::TDK_InvalidExplicitArguments:
9325 return 5;
9326
9327 case Sema::TDK_TooManyArguments:
9328 case Sema::TDK_TooFewArguments:
9329 return 6;
9330 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009331 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009332}
9333
Richard Smith17c00b42014-11-12 01:24:00 +00009334namespace {
John McCallad2587a2010-01-12 00:48:53 +00009335struct CompareOverloadCandidatesForDisplay {
9336 Sema &S;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009337 size_t NumArgs;
9338
9339 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9340 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009341
9342 bool operator()(const OverloadCandidate *L,
9343 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009344 // Fast-path this check.
9345 if (L == R) return false;
9346
John McCall12f97bc2010-01-08 04:41:39 +00009347 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009348 if (L->Viable) {
9349 if (!R->Viable) return true;
9350
9351 // TODO: introduce a tri-valued comparison for overload
9352 // candidates. Would be more worthwhile if we had a sort
9353 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009354 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9355 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009356 } else if (R->Viable)
9357 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009358
John McCall3712d9e2010-01-15 23:32:50 +00009359 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009360
John McCall3712d9e2010-01-15 23:32:50 +00009361 // Criteria by which we can sort non-viable candidates:
9362 if (!L->Viable) {
9363 // 1. Arity mismatches come after other candidates.
9364 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009365 L->FailureKind == ovl_fail_too_few_arguments) {
9366 if (R->FailureKind == ovl_fail_too_many_arguments ||
9367 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009368 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9369 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9370 if (LDist == RDist) {
9371 if (L->FailureKind == R->FailureKind)
9372 // Sort non-surrogates before surrogates.
9373 return !L->IsSurrogate && R->IsSurrogate;
9374 // Sort candidates requiring fewer parameters than there were
9375 // arguments given after candidates requiring more parameters
9376 // than there were arguments given.
9377 return L->FailureKind == ovl_fail_too_many_arguments;
9378 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009379 return LDist < RDist;
9380 }
John McCall3712d9e2010-01-15 23:32:50 +00009381 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009382 }
John McCall3712d9e2010-01-15 23:32:50 +00009383 if (R->FailureKind == ovl_fail_too_many_arguments ||
9384 R->FailureKind == ovl_fail_too_few_arguments)
9385 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009386
John McCallfe796dd2010-01-23 05:17:32 +00009387 // 2. Bad conversions come first and are ordered by the number
9388 // of bad conversions and quality of good conversions.
9389 if (L->FailureKind == ovl_fail_bad_conversion) {
9390 if (R->FailureKind != ovl_fail_bad_conversion)
9391 return true;
9392
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009393 // The conversion that can be fixed with a smaller number of changes,
9394 // comes first.
9395 unsigned numLFixes = L->Fix.NumConversionsFixed;
9396 unsigned numRFixes = R->Fix.NumConversionsFixed;
9397 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9398 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009399 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009400 if (numLFixes < numRFixes)
9401 return true;
9402 else
9403 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009404 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009405
John McCallfe796dd2010-01-23 05:17:32 +00009406 // If there's any ordering between the defined conversions...
9407 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009408 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009409
9410 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009411 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009412 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009413 switch (CompareImplicitConversionSequences(S,
9414 L->Conversions[I],
9415 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009416 case ImplicitConversionSequence::Better:
9417 leftBetter++;
9418 break;
9419
9420 case ImplicitConversionSequence::Worse:
9421 leftBetter--;
9422 break;
9423
9424 case ImplicitConversionSequence::Indistinguishable:
9425 break;
9426 }
9427 }
9428 if (leftBetter > 0) return true;
9429 if (leftBetter < 0) return false;
9430
9431 } else if (R->FailureKind == ovl_fail_bad_conversion)
9432 return false;
9433
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009434 if (L->FailureKind == ovl_fail_bad_deduction) {
9435 if (R->FailureKind != ovl_fail_bad_deduction)
9436 return true;
9437
9438 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9439 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009440 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009441 } else if (R->FailureKind == ovl_fail_bad_deduction)
9442 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009443
John McCall3712d9e2010-01-15 23:32:50 +00009444 // TODO: others?
9445 }
9446
9447 // Sort everything else by location.
9448 SourceLocation LLoc = GetLocationForCandidate(L);
9449 SourceLocation RLoc = GetLocationForCandidate(R);
9450
9451 // Put candidates without locations (e.g. builtins) at the end.
9452 if (LLoc.isInvalid()) return false;
9453 if (RLoc.isInvalid()) return true;
9454
9455 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009456 }
9457};
Richard Smith17c00b42014-11-12 01:24:00 +00009458}
John McCall12f97bc2010-01-08 04:41:39 +00009459
John McCallfe796dd2010-01-23 05:17:32 +00009460/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009461/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009462static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9463 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009464 assert(!Cand->Viable);
9465
9466 // Don't do anything on failures other than bad conversion.
9467 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9468
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009469 // We only want the FixIts if all the arguments can be corrected.
9470 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009471 // Use a implicit copy initialization to check conversion fixes.
9472 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009473
John McCallfe796dd2010-01-23 05:17:32 +00009474 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009475 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009476 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009477 while (true) {
9478 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9479 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009480 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009481 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009482 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009483 }
John McCallfe796dd2010-01-23 05:17:32 +00009484 }
9485
9486 if (ConvIdx == ConvCount)
9487 return;
9488
John McCall65eb8792010-02-25 01:37:24 +00009489 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9490 "remaining conversion is initialized?");
9491
Douglas Gregoradc7a702010-04-16 17:45:54 +00009492 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009493 // operation somehow.
9494 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009495
9496 const FunctionProtoType* Proto;
9497 unsigned ArgIdx = ConvIdx;
9498
9499 if (Cand->IsSurrogate) {
9500 QualType ConvType
9501 = Cand->Surrogate->getConversionType().getNonReferenceType();
9502 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9503 ConvType = ConvPtrType->getPointeeType();
9504 Proto = ConvType->getAs<FunctionProtoType>();
9505 ArgIdx--;
9506 } else if (Cand->Function) {
9507 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9508 if (isa<CXXMethodDecl>(Cand->Function) &&
9509 !isa<CXXConstructorDecl>(Cand->Function))
9510 ArgIdx--;
9511 } else {
9512 // Builtin binary operator with a bad first conversion.
9513 assert(ConvCount <= 3);
9514 for (; ConvIdx != ConvCount; ++ConvIdx)
9515 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009516 = TryCopyInitialization(S, Args[ConvIdx],
9517 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009518 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009519 /*InOverloadResolution*/ true,
9520 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009521 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009522 return;
9523 }
9524
9525 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009526 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009527 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009528 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009529 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9530 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9531 /*InOverloadResolution=*/true,
9532 /*AllowObjCWritebackConversion=*/
9533 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009534 // Store the FixIt in the candidate if it exists.
9535 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009536 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009537 }
John McCallfe796dd2010-01-23 05:17:32 +00009538 else
9539 Cand->Conversions[ConvIdx].setEllipsis();
9540 }
9541}
9542
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009543/// PrintOverloadCandidates - When overload resolution fails, prints
9544/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009545/// set.
John McCall5c32be02010-08-24 20:38:10 +00009546void OverloadCandidateSet::NoteCandidates(Sema &S,
9547 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009548 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009549 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009550 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009551 // Sort the candidates by viability and position. Sorting directly would
9552 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009553 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009554 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9555 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009556 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009557 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009558 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009559 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009560 if (Cand->Function || Cand->IsSurrogate)
9561 Cands.push_back(Cand);
9562 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9563 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009564 }
9565 }
9566
John McCallad2587a2010-01-12 00:48:53 +00009567 std::sort(Cands.begin(), Cands.end(),
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009568 CompareOverloadCandidatesForDisplay(S, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009569
John McCall0d1da222010-01-12 00:44:57 +00009570 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009571
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009572 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009573 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009574 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009575 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9576 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009577
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009578 // Set an arbitrary limit on the number of candidate functions we'll spam
9579 // the user with. FIXME: This limit should depend on details of the
9580 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009581 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009582 break;
9583 }
9584 ++CandsShown;
9585
John McCalld3224162010-01-08 00:58:21 +00009586 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009587 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009588 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009589 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009590 else {
9591 assert(Cand->Viable &&
9592 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009593 // Generally we only see ambiguities including viable builtin
9594 // operators if overload resolution got screwed up by an
9595 // ambiguous user-defined conversion.
9596 //
9597 // FIXME: It's quite possible for different conversions to see
9598 // different ambiguities, though.
9599 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009600 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009601 ReportedAmbiguousConversions = true;
9602 }
John McCalld3224162010-01-08 00:58:21 +00009603
John McCall0d1da222010-01-12 00:44:57 +00009604 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009605 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009606 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009607 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009608
9609 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009610 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009611}
9612
Larisse Voufo98b20f12013-07-19 23:00:19 +00009613static SourceLocation
9614GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9615 return Cand->Specialization ? Cand->Specialization->getLocation()
9616 : SourceLocation();
9617}
9618
Richard Smith17c00b42014-11-12 01:24:00 +00009619namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009620struct CompareTemplateSpecCandidatesForDisplay {
9621 Sema &S;
9622 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9623
9624 bool operator()(const TemplateSpecCandidate *L,
9625 const TemplateSpecCandidate *R) {
9626 // Fast-path this check.
9627 if (L == R)
9628 return false;
9629
9630 // Assuming that both candidates are not matches...
9631
9632 // Sort by the ranking of deduction failures.
9633 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9634 return RankDeductionFailure(L->DeductionFailure) <
9635 RankDeductionFailure(R->DeductionFailure);
9636
9637 // Sort everything else by location.
9638 SourceLocation LLoc = GetLocationForCandidate(L);
9639 SourceLocation RLoc = GetLocationForCandidate(R);
9640
9641 // Put candidates without locations (e.g. builtins) at the end.
9642 if (LLoc.isInvalid())
9643 return false;
9644 if (RLoc.isInvalid())
9645 return true;
9646
9647 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9648 }
9649};
Richard Smith17c00b42014-11-12 01:24:00 +00009650}
Larisse Voufo98b20f12013-07-19 23:00:19 +00009651
9652/// Diagnose a template argument deduction failure.
9653/// We are treating these failures as overload failures due to bad
9654/// deductions.
9655void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9656 DiagnoseBadDeduction(S, Specialization, // pattern
9657 DeductionFailure, /*NumArgs=*/0);
9658}
9659
9660void TemplateSpecCandidateSet::destroyCandidates() {
9661 for (iterator i = begin(), e = end(); i != e; ++i) {
9662 i->DeductionFailure.Destroy();
9663 }
9664}
9665
9666void TemplateSpecCandidateSet::clear() {
9667 destroyCandidates();
9668 Candidates.clear();
9669}
9670
9671/// NoteCandidates - When no template specialization match is found, prints
9672/// diagnostic messages containing the non-matching specializations that form
9673/// the candidate set.
9674/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9675/// OCD == OCD_AllCandidates and Cand->Viable == false.
9676void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9677 // Sort the candidates by position (assuming no candidate is a match).
9678 // Sorting directly would be prohibitive, so we make a set of pointers
9679 // and sort those.
9680 SmallVector<TemplateSpecCandidate *, 32> Cands;
9681 Cands.reserve(size());
9682 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9683 if (Cand->Specialization)
9684 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009685 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009686 // in general, want to list every possible builtin candidate.
9687 }
9688
9689 std::sort(Cands.begin(), Cands.end(),
9690 CompareTemplateSpecCandidatesForDisplay(S));
9691
9692 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9693 // for generalization purposes (?).
9694 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9695
9696 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9697 unsigned CandsShown = 0;
9698 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9699 TemplateSpecCandidate *Cand = *I;
9700
9701 // Set an arbitrary limit on the number of candidates we'll spam
9702 // the user with. FIXME: This limit should depend on details of the
9703 // candidate list.
9704 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9705 break;
9706 ++CandsShown;
9707
9708 assert(Cand->Specialization &&
9709 "Non-matching built-in candidates are not added to Cands.");
9710 Cand->NoteDeductionFailure(S);
9711 }
9712
9713 if (I != E)
9714 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9715}
9716
Douglas Gregorb491ed32011-02-19 21:32:49 +00009717// [PossiblyAFunctionType] --> [Return]
9718// NonFunctionType --> NonFunctionType
9719// R (A) --> R(A)
9720// R (*)(A) --> R (A)
9721// R (&)(A) --> R (A)
9722// R (S::*)(A) --> R (A)
9723QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9724 QualType Ret = PossiblyAFunctionType;
9725 if (const PointerType *ToTypePtr =
9726 PossiblyAFunctionType->getAs<PointerType>())
9727 Ret = ToTypePtr->getPointeeType();
9728 else if (const ReferenceType *ToTypeRef =
9729 PossiblyAFunctionType->getAs<ReferenceType>())
9730 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009731 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009732 PossiblyAFunctionType->getAs<MemberPointerType>())
9733 Ret = MemTypePtr->getPointeeType();
9734 Ret =
9735 Context.getCanonicalType(Ret).getUnqualifiedType();
9736 return Ret;
9737}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009738
Richard Smith17c00b42014-11-12 01:24:00 +00009739namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009740// A helper class to help with address of function resolution
9741// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +00009742class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009743 Sema& S;
9744 Expr* SourceExpr;
9745 const QualType& TargetType;
9746 QualType TargetFunctionType; // Extracted function type from target type
9747
9748 bool Complain;
9749 //DeclAccessPair& ResultFunctionAccessPair;
9750 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009751
Douglas Gregorb491ed32011-02-19 21:32:49 +00009752 bool TargetTypeIsNonStaticMemberFunction;
9753 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009754 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009755
Douglas Gregorb491ed32011-02-19 21:32:49 +00009756 OverloadExpr::FindResult OvlExprInfo;
9757 OverloadExpr *OvlExpr;
9758 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009759 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009760 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009761
Douglas Gregorb491ed32011-02-19 21:32:49 +00009762public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009763 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9764 const QualType &TargetType, bool Complain)
9765 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9766 Complain(Complain), Context(S.getASTContext()),
9767 TargetTypeIsNonStaticMemberFunction(
9768 !!TargetType->getAs<MemberPointerType>()),
9769 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009770 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009771 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9772 OvlExpr(OvlExprInfo.Expression),
9773 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009774 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009775
David Majnemera4f7c7a2013-08-01 06:13:59 +00009776 if (TargetFunctionType->isFunctionType()) {
9777 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9778 if (!UME->isImplicitAccess() &&
9779 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9780 StaticMemberFunctionFromBoundPointer = true;
9781 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9782 DeclAccessPair dap;
9783 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9784 OvlExpr, false, &dap)) {
9785 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9786 if (!Method->isStatic()) {
9787 // If the target type is a non-function type and the function found
9788 // is a non-static member function, pretend as if that was the
9789 // target, it's the only possible type to end up with.
9790 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +00009791
David Majnemera4f7c7a2013-08-01 06:13:59 +00009792 // And skip adding the function if its not in the proper form.
9793 // We'll diagnose this due to an empty set of functions.
9794 if (!OvlExprInfo.HasFormOfMemberPointer)
9795 return;
Chandler Carruthffce2452011-03-29 08:08:18 +00009796 }
9797
David Majnemera4f7c7a2013-08-01 06:13:59 +00009798 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +00009799 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009800 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00009801 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009802
9803 if (OvlExpr->hasExplicitTemplateArgs())
9804 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00009805
Douglas Gregorb491ed32011-02-19 21:32:49 +00009806 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9807 // C++ [over.over]p4:
9808 // If more than one function is selected, [...]
9809 if (Matches.size() > 1) {
9810 if (FoundNonTemplateFunction)
9811 EliminateAllTemplateMatches();
9812 else
9813 EliminateAllExceptMostSpecializedTemplate();
9814 }
9815 }
9816 }
9817
9818private:
9819 bool isTargetTypeAFunction() const {
9820 return TargetFunctionType->isFunctionType();
9821 }
9822
9823 // [ToType] [Return]
9824
9825 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9826 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9827 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9828 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9829 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9830 }
9831
9832 // return true if any matching specializations were found
9833 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9834 const DeclAccessPair& CurAccessFunPair) {
9835 if (CXXMethodDecl *Method
9836 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9837 // Skip non-static function templates when converting to pointer, and
9838 // static when converting to member pointer.
9839 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9840 return false;
9841 }
9842 else if (TargetTypeIsNonStaticMemberFunction)
9843 return false;
9844
9845 // C++ [over.over]p2:
9846 // If the name is a function template, template argument deduction is
9847 // done (14.8.2.2), and if the argument deduction succeeds, the
9848 // resulting template argument list is used to generate a single
9849 // function template specialization, which is added to the set of
9850 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +00009851 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009852 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009853 if (Sema::TemplateDeductionResult Result
9854 = S.DeduceTemplateArguments(FunctionTemplate,
9855 &OvlExplicitTemplateArgs,
9856 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009857 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009858 // Make a note of the failed deduction for diagnostics.
9859 FailedCandidates.addCandidate()
9860 .set(FunctionTemplate->getTemplatedDecl(),
9861 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009862 return false;
9863 }
9864
Douglas Gregor19a41f12013-04-17 08:45:07 +00009865 // Template argument deduction ensures that we have an exact match or
9866 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009867 // This function template specicalization works.
9868 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +00009869 assert(S.isSameOrCompatibleFunctionType(
9870 Context.getCanonicalType(Specialization->getType()),
9871 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009872 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9873 return true;
9874 }
9875
9876 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9877 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009878 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009879 // Skip non-static functions when converting to pointer, and static
9880 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009881 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9882 return false;
9883 }
9884 else if (TargetTypeIsNonStaticMemberFunction)
9885 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009886
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009887 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009888 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009889 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009890 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009891 return false;
9892
Richard Smith2a7d4812013-05-04 07:00:32 +00009893 // If any candidate has a placeholder return type, trigger its deduction
9894 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00009895 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +00009896 FunDecl->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00009897 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9898 return false;
9899
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009900 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009901 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9902 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009903 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9904 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009905 Matches.push_back(std::make_pair(CurAccessFunPair,
9906 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009907 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009908 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009909 }
Mike Stump11289f42009-09-09 15:08:12 +00009910 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009911
9912 return false;
9913 }
9914
9915 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9916 bool Ret = false;
9917
9918 // If the overload expression doesn't have the form of a pointer to
9919 // member, don't try to convert it to a pointer-to-member type.
9920 if (IsInvalidFormOfPointerToMemberFunction())
9921 return false;
9922
9923 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9924 E = OvlExpr->decls_end();
9925 I != E; ++I) {
9926 // Look through any using declarations to find the underlying function.
9927 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9928
9929 // C++ [over.over]p3:
9930 // Non-member functions and static member functions match
9931 // targets of type "pointer-to-function" or "reference-to-function."
9932 // Nonstatic member functions match targets of
9933 // type "pointer-to-member-function."
9934 // Note that according to DR 247, the containing class does not matter.
9935 if (FunctionTemplateDecl *FunctionTemplate
9936 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9937 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9938 Ret = true;
9939 }
9940 // If we have explicit template arguments supplied, skip non-templates.
9941 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9942 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9943 Ret = true;
9944 }
9945 assert(Ret || Matches.empty());
9946 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009947 }
9948
Douglas Gregorb491ed32011-02-19 21:32:49 +00009949 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00009950 // [...] and any given function template specialization F1 is
9951 // eliminated if the set contains a second function template
9952 // specialization whose function template is more specialized
9953 // than the function template of F1 according to the partial
9954 // ordering rules of 14.5.5.2.
9955
9956 // The algorithm specified above is quadratic. We instead use a
9957 // two-pass algorithm (similar to the one used to identify the
9958 // best viable function in an overload set) that identifies the
9959 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00009960
9961 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9962 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9963 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009964
Larisse Voufo98b20f12013-07-19 23:00:19 +00009965 // TODO: It looks like FailedCandidates does not serve much purpose
9966 // here, since the no_viable diagnostic has index 0.
9967 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00009968 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009969 SourceExpr->getLocStart(), S.PDiag(),
9970 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9971 .second->getDeclName(),
9972 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9973 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009974
Douglas Gregorb491ed32011-02-19 21:32:49 +00009975 if (Result != MatchesCopy.end()) {
9976 // Make it the first and only element
9977 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9978 Matches[0].second = cast<FunctionDecl>(*Result);
9979 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00009980 }
9981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009982
Douglas Gregorb491ed32011-02-19 21:32:49 +00009983 void EliminateAllTemplateMatches() {
9984 // [...] any function template specializations in the set are
9985 // eliminated if the set also contains a non-template function, [...]
9986 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009987 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +00009988 ++I;
9989 else {
9990 Matches[I] = Matches[--N];
9991 Matches.set_size(N);
9992 }
9993 }
9994 }
9995
9996public:
9997 void ComplainNoMatchesFound() const {
9998 assert(Matches.empty());
9999 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10000 << OvlExpr->getName() << TargetFunctionType
10001 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010002 if (FailedCandidates.empty())
10003 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10004 else {
10005 // We have some deduction failure messages. Use them to diagnose
10006 // the function templates, and diagnose the non-template candidates
10007 // normally.
10008 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10009 IEnd = OvlExpr->decls_end();
10010 I != IEnd; ++I)
10011 if (FunctionDecl *Fun =
10012 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10013 S.NoteOverloadCandidate(Fun, TargetFunctionType);
10014 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10015 }
10016 }
10017
Douglas Gregorb491ed32011-02-19 21:32:49 +000010018 bool IsInvalidFormOfPointerToMemberFunction() const {
10019 return TargetTypeIsNonStaticMemberFunction &&
10020 !OvlExprInfo.HasFormOfMemberPointer;
10021 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010022
Douglas Gregorb491ed32011-02-19 21:32:49 +000010023 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10024 // TODO: Should we condition this on whether any functions might
10025 // have matched, or is it more appropriate to do that in callers?
10026 // TODO: a fixit wouldn't hurt.
10027 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10028 << TargetType << OvlExpr->getSourceRange();
10029 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010030
10031 bool IsStaticMemberFunctionFromBoundPointer() const {
10032 return StaticMemberFunctionFromBoundPointer;
10033 }
10034
10035 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10036 S.Diag(OvlExpr->getLocStart(),
10037 diag::err_invalid_form_pointer_member_function)
10038 << OvlExpr->getSourceRange();
10039 }
10040
Douglas Gregorb491ed32011-02-19 21:32:49 +000010041 void ComplainOfInvalidConversion() const {
10042 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10043 << OvlExpr->getName() << TargetType;
10044 }
10045
10046 void ComplainMultipleMatchesFound() const {
10047 assert(Matches.size() > 1);
10048 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10049 << OvlExpr->getName()
10050 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +000010051 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010052 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010053
10054 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10055
Douglas Gregorb491ed32011-02-19 21:32:49 +000010056 int getNumMatches() const { return Matches.size(); }
10057
10058 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010059 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010060 return Matches[0].second;
10061 }
10062
10063 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010064 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010065 return &Matches[0].first;
10066 }
10067};
Richard Smith17c00b42014-11-12 01:24:00 +000010068}
10069
Douglas Gregorb491ed32011-02-19 21:32:49 +000010070/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10071/// an overloaded function (C++ [over.over]), where @p From is an
10072/// expression with overloaded function type and @p ToType is the type
10073/// we're trying to resolve to. For example:
10074///
10075/// @code
10076/// int f(double);
10077/// int f(int);
10078///
10079/// int (*pfd)(double) = f; // selects f(double)
10080/// @endcode
10081///
10082/// This routine returns the resulting FunctionDecl if it could be
10083/// resolved, and NULL otherwise. When @p Complain is true, this
10084/// routine will emit diagnostics if there is an error.
10085FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010086Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10087 QualType TargetType,
10088 bool Complain,
10089 DeclAccessPair &FoundResult,
10090 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010091 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010092
10093 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10094 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010095 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010096 FunctionDecl *Fn = nullptr;
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010097 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010098 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10099 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10100 else
10101 Resolver.ComplainNoMatchesFound();
10102 }
10103 else if (NumMatches > 1 && Complain)
10104 Resolver.ComplainMultipleMatchesFound();
10105 else if (NumMatches == 1) {
10106 Fn = Resolver.getMatchingFunctionDecl();
10107 assert(Fn);
10108 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010109 if (Complain) {
10110 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10111 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10112 else
10113 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10114 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010115 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010116
10117 if (pHadMultipleCandidates)
10118 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010119 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010120}
10121
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010122/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010123/// resolve that overloaded function expression down to a single function.
10124///
10125/// This routine can only resolve template-ids that refer to a single function
10126/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010127/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010128/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010129///
10130/// If no template-ids are found, no diagnostics are emitted and NULL is
10131/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010132FunctionDecl *
10133Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10134 bool Complain,
10135 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010136 // C++ [over.over]p1:
10137 // [...] [Note: any redundant set of parentheses surrounding the
10138 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010139 // C++ [over.over]p1:
10140 // [...] The overloaded function name can be preceded by the &
10141 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010142
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010143 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010144 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010145 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010146
10147 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +000010148 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010149 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010150
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010151 // Look through all of the overloaded functions, searching for one
10152 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010153 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010154 for (UnresolvedSetIterator I = ovl->decls_begin(),
10155 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010156 // C++0x [temp.arg.explicit]p3:
10157 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010158 // where deduction is not done, if a template argument list is
10159 // specified and it, along with any default template arguments,
10160 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010161 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010162 FunctionTemplateDecl *FunctionTemplate
10163 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010164
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010165 // C++ [over.over]p2:
10166 // If the name is a function template, template argument deduction is
10167 // done (14.8.2.2), and if the argument deduction succeeds, the
10168 // resulting template argument list is used to generate a single
10169 // function template specialization, which is added to the set of
10170 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010171 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010172 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010173 if (TemplateDeductionResult Result
10174 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010175 Specialization, Info,
10176 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010177 // Make a note of the failed deduction for diagnostics.
10178 // TODO: Actually use the failed-deduction info?
10179 FailedCandidates.addCandidate()
10180 .set(FunctionTemplate->getTemplatedDecl(),
10181 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010182 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010183 }
10184
John McCall0009fcc2011-04-26 20:42:42 +000010185 assert(Specialization && "no specialization and no error?");
10186
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010187 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010188 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010189 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010190 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10191 << ovl->getName();
10192 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010193 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010194 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010195 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010196
John McCall0009fcc2011-04-26 20:42:42 +000010197 Matched = Specialization;
10198 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010199 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010200
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010201 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010202 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010203 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010204 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010205
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010206 return Matched;
10207}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010208
Douglas Gregor1beec452011-03-12 01:48:56 +000010209
10210
10211
John McCall50a2c2c2011-10-11 23:14:30 +000010212// Resolve and fix an overloaded expression that can be resolved
10213// because it identifies a single function template specialization.
10214//
Douglas Gregor1beec452011-03-12 01:48:56 +000010215// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010216//
10217// Return true if it was logically possible to so resolve the
10218// expression, regardless of whether or not it succeeded. Always
10219// returns true if 'complain' is set.
10220bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10221 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10222 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010223 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010224 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010225 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010226
John McCall50a2c2c2011-10-11 23:14:30 +000010227 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010228
John McCall0009fcc2011-04-26 20:42:42 +000010229 DeclAccessPair found;
10230 ExprResult SingleFunctionExpression;
10231 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10232 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010233 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010234 SrcExpr = ExprError();
10235 return true;
10236 }
John McCall0009fcc2011-04-26 20:42:42 +000010237
10238 // It is only correct to resolve to an instance method if we're
10239 // resolving a form that's permitted to be a pointer to member.
10240 // Otherwise we'll end up making a bound member expression, which
10241 // is illegal in all the contexts we resolve like this.
10242 if (!ovl.HasFormOfMemberPointer &&
10243 isa<CXXMethodDecl>(fn) &&
10244 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010245 if (!complain) return false;
10246
10247 Diag(ovl.Expression->getExprLoc(),
10248 diag::err_bound_member_function)
10249 << 0 << ovl.Expression->getSourceRange();
10250
10251 // TODO: I believe we only end up here if there's a mix of
10252 // static and non-static candidates (otherwise the expression
10253 // would have 'bound member' type, not 'overload' type).
10254 // Ideally we would note which candidate was chosen and why
10255 // the static candidates were rejected.
10256 SrcExpr = ExprError();
10257 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010258 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010259
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010260 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010261 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010262 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010263
10264 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010265 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010266 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010267 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010268 if (SingleFunctionExpression.isInvalid()) {
10269 SrcExpr = ExprError();
10270 return true;
10271 }
10272 }
John McCall0009fcc2011-04-26 20:42:42 +000010273 }
10274
10275 if (!SingleFunctionExpression.isUsable()) {
10276 if (complain) {
10277 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10278 << ovl.Expression->getName()
10279 << DestTypeForComplaining
10280 << OpRangeForComplaining
10281 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010282 NoteAllOverloadCandidates(SrcExpr.get());
10283
10284 SrcExpr = ExprError();
10285 return true;
10286 }
10287
10288 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010289 }
10290
John McCall50a2c2c2011-10-11 23:14:30 +000010291 SrcExpr = SingleFunctionExpression;
10292 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010293}
10294
Douglas Gregorcabea402009-09-22 15:41:20 +000010295/// \brief Add a single candidate to the overload set.
10296static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010297 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010298 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010299 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010300 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010301 bool PartialOverloading,
10302 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010303 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010304 if (isa<UsingShadowDecl>(Callee))
10305 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10306
Douglas Gregorcabea402009-09-22 15:41:20 +000010307 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010308 if (ExplicitTemplateArgs) {
10309 assert(!KnownValid && "Explicit template arguments?");
10310 return;
10311 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010312 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
10313 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010314 return;
John McCalld14a8642009-11-21 08:51:07 +000010315 }
10316
10317 if (FunctionTemplateDecl *FuncTemplate
10318 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010319 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010320 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +000010321 return;
10322 }
10323
Richard Smith95ce4f62011-06-26 22:19:54 +000010324 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010325}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010326
Douglas Gregorcabea402009-09-22 15:41:20 +000010327/// \brief Add the overload candidates named by callee and/or found by argument
10328/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010329void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010330 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010331 OverloadCandidateSet &CandidateSet,
10332 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010333
10334#ifndef NDEBUG
10335 // Verify that ArgumentDependentLookup is consistent with the rules
10336 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010337 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010338 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10339 // and let Y be the lookup set produced by argument dependent
10340 // lookup (defined as follows). If X contains
10341 //
10342 // -- a declaration of a class member, or
10343 //
10344 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010345 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010346 //
10347 // -- a declaration that is neither a function or a function
10348 // template
10349 //
10350 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010351
John McCall57500772009-12-16 12:17:52 +000010352 if (ULE->requiresADL()) {
10353 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10354 E = ULE->decls_end(); I != E; ++I) {
10355 assert(!(*I)->getDeclContext()->isRecord());
10356 assert(isa<UsingShadowDecl>(*I) ||
10357 !(*I)->getDeclContext()->isFunctionOrMethod());
10358 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010359 }
10360 }
10361#endif
10362
John McCall57500772009-12-16 12:17:52 +000010363 // It would be nice to avoid this copy.
10364 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010365 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010366 if (ULE->hasExplicitTemplateArgs()) {
10367 ULE->copyTemplateArgumentsInto(TABuffer);
10368 ExplicitTemplateArgs = &TABuffer;
10369 }
10370
10371 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10372 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010373 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10374 CandidateSet, PartialOverloading,
10375 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010376
John McCall57500772009-12-16 12:17:52 +000010377 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010378 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010379 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010380 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010381}
John McCalld681c392009-12-16 08:11:27 +000010382
Richard Smith0603bbb2013-06-12 22:56:54 +000010383/// Determine whether a declaration with the specified name could be moved into
10384/// a different namespace.
10385static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10386 switch (Name.getCXXOverloadedOperator()) {
10387 case OO_New: case OO_Array_New:
10388 case OO_Delete: case OO_Array_Delete:
10389 return false;
10390
10391 default:
10392 return true;
10393 }
10394}
10395
Richard Smith998a5912011-06-05 22:42:48 +000010396/// Attempt to recover from an ill-formed use of a non-dependent name in a
10397/// template, where the non-dependent name was declared after the template
10398/// was defined. This is common in code written for a compilers which do not
10399/// correctly implement two-stage name lookup.
10400///
10401/// Returns true if a viable candidate was found and a diagnostic was issued.
10402static bool
10403DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10404 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010405 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010406 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010407 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010408 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10409 return false;
10410
10411 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010412 if (DC->isTransparentContext())
10413 continue;
10414
Richard Smith998a5912011-06-05 22:42:48 +000010415 SemaRef.LookupQualifiedName(R, DC);
10416
10417 if (!R.empty()) {
10418 R.suppressDiagnostics();
10419
10420 if (isa<CXXRecordDecl>(DC)) {
10421 // Don't diagnose names we find in classes; we get much better
10422 // diagnostics for these from DiagnoseEmptyLookup.
10423 R.clear();
10424 return false;
10425 }
10426
Richard Smith100b24a2014-04-17 01:52:14 +000010427 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010428 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10429 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010430 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010431 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010432
10433 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010434 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010435 // No viable functions. Don't bother the user with notes for functions
10436 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010437 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010438 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010439 }
Richard Smith998a5912011-06-05 22:42:48 +000010440
10441 // Find the namespaces where ADL would have looked, and suggest
10442 // declaring the function there instead.
10443 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10444 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010445 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010446 AssociatedNamespaces,
10447 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010448 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010449 if (canBeDeclaredInNamespace(R.getLookupName())) {
10450 DeclContext *Std = SemaRef.getStdNamespace();
10451 for (Sema::AssociatedNamespaceSet::iterator
10452 it = AssociatedNamespaces.begin(),
10453 end = AssociatedNamespaces.end(); it != end; ++it) {
10454 // Never suggest declaring a function within namespace 'std'.
10455 if (Std && Std->Encloses(*it))
10456 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010457
Richard Smith0603bbb2013-06-12 22:56:54 +000010458 // Never suggest declaring a function within a namespace with a
10459 // reserved name, like __gnu_cxx.
10460 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10461 if (NS &&
10462 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10463 continue;
10464
10465 SuggestedNamespaces.insert(*it);
10466 }
Richard Smith998a5912011-06-05 22:42:48 +000010467 }
10468
10469 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10470 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010471 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010472 SemaRef.Diag(Best->Function->getLocation(),
10473 diag::note_not_found_by_two_phase_lookup)
10474 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010475 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010476 SemaRef.Diag(Best->Function->getLocation(),
10477 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010478 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010479 } else {
10480 // FIXME: It would be useful to list the associated namespaces here,
10481 // but the diagnostics infrastructure doesn't provide a way to produce
10482 // a localized representation of a list of items.
10483 SemaRef.Diag(Best->Function->getLocation(),
10484 diag::note_not_found_by_two_phase_lookup)
10485 << R.getLookupName() << 2;
10486 }
10487
10488 // Try to recover by calling this function.
10489 return true;
10490 }
10491
10492 R.clear();
10493 }
10494
10495 return false;
10496}
10497
10498/// Attempt to recover from ill-formed use of a non-dependent operator in a
10499/// template, where the non-dependent operator was declared after the template
10500/// was defined.
10501///
10502/// Returns true if a viable candidate was found and a diagnostic was issued.
10503static bool
10504DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10505 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010506 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010507 DeclarationName OpName =
10508 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10509 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10510 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000010511 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000010512 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010513}
10514
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010515namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010516class BuildRecoveryCallExprRAII {
10517 Sema &SemaRef;
10518public:
10519 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10520 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10521 SemaRef.IsBuildingRecoveryCallExpr = true;
10522 }
10523
10524 ~BuildRecoveryCallExprRAII() {
10525 SemaRef.IsBuildingRecoveryCallExpr = false;
10526 }
10527};
10528
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010529}
10530
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010531static std::unique_ptr<CorrectionCandidateCallback>
10532MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10533 bool HasTemplateArgs, bool AllowTypoCorrection) {
10534 if (!AllowTypoCorrection)
10535 return llvm::make_unique<NoTypoCorrectionCCC>();
10536 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10537 HasTemplateArgs, ME);
10538}
10539
John McCalld681c392009-12-16 08:11:27 +000010540/// Attempts to recover from a call where no functions were found.
10541///
10542/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010543static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010544BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010545 UnresolvedLookupExpr *ULE,
10546 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000010547 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010548 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010549 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010550 // Do not try to recover if it is already building a recovery call.
10551 // This stops infinite loops for template instantiations like
10552 //
10553 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10554 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10555 //
10556 if (SemaRef.IsBuildingRecoveryCallExpr)
10557 return ExprError();
10558 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010559
10560 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010561 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010562 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010563
John McCall57500772009-12-16 12:17:52 +000010564 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010565 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010566 if (ULE->hasExplicitTemplateArgs()) {
10567 ULE->copyTemplateArgumentsInto(TABuffer);
10568 ExplicitTemplateArgs = &TABuffer;
10569 }
10570
John McCalld681c392009-12-16 08:11:27 +000010571 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10572 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +000010573 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000010574 OverloadCandidateSet::CSK_Normal,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010575 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +000010576 (!EmptyLookup ||
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010577 SemaRef.DiagnoseEmptyLookup(
10578 S, SS, R,
10579 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10580 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10581 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010582 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010583
John McCall57500772009-12-16 12:17:52 +000010584 assert(!R.empty() && "lookup results empty despite recovery");
10585
10586 // Build an implicit member call if appropriate. Just drop the
10587 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010588 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010589 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010590 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10591 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010592 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010593 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010594 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010595 else
10596 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10597
10598 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010599 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010600
10601 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010602 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010603 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010604 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010605 MultiExprArg(Args.data(), Args.size()),
10606 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010607}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010608
Sam Panzer0f384432012-08-21 00:52:01 +000010609/// \brief Constructs and populates an OverloadedCandidateSet from
10610/// the given function.
10611/// \returns true when an the ExprResult output parameter has been set.
10612bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10613 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010614 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010615 SourceLocation RParenLoc,
10616 OverloadCandidateSet *CandidateSet,
10617 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010618#ifndef NDEBUG
10619 if (ULE->requiresADL()) {
10620 // To do ADL, we must have found an unqualified name.
10621 assert(!ULE->getQualifier() && "qualified name with ADL");
10622
10623 // We don't perform ADL for implicit declarations of builtins.
10624 // Verify that this was correctly set up.
10625 FunctionDecl *F;
10626 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10627 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10628 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010629 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010630
John McCall57500772009-12-16 12:17:52 +000010631 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010632 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010633 }
John McCall57500772009-12-16 12:17:52 +000010634#endif
10635
John McCall4124c492011-10-17 18:40:02 +000010636 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010637 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010638 *Result = ExprError();
10639 return true;
10640 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010641
John McCall57500772009-12-16 12:17:52 +000010642 // Add the functions denoted by the callee to the set of candidate
10643 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010644 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010645
10646 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +000010647 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10648 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +000010649 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010650 // In Microsoft mode, if we are inside a template class member function then
10651 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +000010652 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010653 // classes.
Alp Tokerbfa39342014-01-14 12:51:41 +000010654 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +000010655 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010656 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010657 Context.DependentTy, VK_RValue,
10658 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010659 CE->setTypeDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010660 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000010661 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010662 }
Sam Panzer0f384432012-08-21 00:52:01 +000010663 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +000010664 }
John McCalld681c392009-12-16 08:11:27 +000010665
John McCall4124c492011-10-17 18:40:02 +000010666 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010667 return false;
10668}
John McCall4124c492011-10-17 18:40:02 +000010669
Sam Panzer0f384432012-08-21 00:52:01 +000010670/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10671/// the completed call expression. If overload resolution fails, emits
10672/// diagnostics and returns ExprError()
10673static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10674 UnresolvedLookupExpr *ULE,
10675 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010676 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010677 SourceLocation RParenLoc,
10678 Expr *ExecConfig,
10679 OverloadCandidateSet *CandidateSet,
10680 OverloadCandidateSet::iterator *Best,
10681 OverloadingResult OverloadResult,
10682 bool AllowTypoCorrection) {
10683 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010684 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010685 RParenLoc, /*EmptyLookup=*/true,
10686 AllowTypoCorrection);
10687
10688 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010689 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010690 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010691 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010692 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10693 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010694 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010695 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10696 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010697 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010698
Richard Smith998a5912011-06-05 22:42:48 +000010699 case OR_No_Viable_Function: {
10700 // Try to recover by looking for viable functions which the user might
10701 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010702 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010703 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010704 /*EmptyLookup=*/false,
10705 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010706 if (!Recovery.isInvalid())
10707 return Recovery;
10708
Sam Panzer0f384432012-08-21 00:52:01 +000010709 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010710 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000010711 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010712 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010713 break;
Richard Smith998a5912011-06-05 22:42:48 +000010714 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010715
10716 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000010717 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000010718 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010719 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010720 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010721
Sam Panzer0f384432012-08-21 00:52:01 +000010722 case OR_Deleted: {
10723 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10724 << (*Best)->Function->isDeleted()
10725 << ULE->getName()
10726 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10727 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010728 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000010729
Sam Panzer0f384432012-08-21 00:52:01 +000010730 // We emitted an error for the unvailable/deleted function call but keep
10731 // the call in the AST.
10732 FunctionDecl *FDecl = (*Best)->Function;
10733 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010734 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10735 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000010736 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010737 }
10738
Douglas Gregorb412e172010-07-25 18:17:45 +000010739 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000010740 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010741}
10742
Sam Panzer0f384432012-08-21 00:52:01 +000010743/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10744/// (which eventually refers to the declaration Func) and the call
10745/// arguments Args/NumArgs, attempt to resolve the function call down
10746/// to a specific function. If overload resolution succeeds, returns
10747/// the call expression produced by overload resolution.
10748/// Otherwise, emits diagnostics and returns ExprError.
10749ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10750 UnresolvedLookupExpr *ULE,
10751 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010752 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010753 SourceLocation RParenLoc,
10754 Expr *ExecConfig,
10755 bool AllowTypoCorrection) {
Richard Smith100b24a2014-04-17 01:52:14 +000010756 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10757 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000010758 ExprResult result;
10759
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010760 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10761 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000010762 return result;
10763
10764 OverloadCandidateSet::iterator Best;
10765 OverloadingResult OverloadResult =
10766 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10767
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010768 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010769 RParenLoc, ExecConfig, &CandidateSet,
10770 &Best, OverloadResult,
10771 AllowTypoCorrection);
10772}
10773
John McCall4c4c1df2010-01-26 03:27:55 +000010774static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000010775 return Functions.size() > 1 ||
10776 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10777}
10778
Douglas Gregor084d8552009-03-13 23:49:33 +000010779/// \brief Create a unary operation that may resolve to an overloaded
10780/// operator.
10781///
10782/// \param OpLoc The location of the operator itself (e.g., '*').
10783///
10784/// \param OpcIn The UnaryOperator::Opcode that describes this
10785/// operator.
10786///
James Dennett18348b62012-06-22 08:52:37 +000010787/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000010788/// considered by overload resolution. The caller needs to build this
10789/// set based on the context using, e.g.,
10790/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10791/// set should not contain any member functions; those will be added
10792/// by CreateOverloadedUnaryOp().
10793///
James Dennett91738ff2012-06-22 10:32:46 +000010794/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000010795ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000010796Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10797 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000010798 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010799 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000010800
10801 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10802 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10803 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010804 // TODO: provide better source location info.
10805 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010806
John McCall4124c492011-10-17 18:40:02 +000010807 if (checkPlaceholderForOverload(*this, Input))
10808 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010809
Craig Topperc3ec1492014-05-26 06:22:03 +000010810 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000010811 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000010812
Douglas Gregor084d8552009-03-13 23:49:33 +000010813 // For post-increment and post-decrement, add the implicit '0' as
10814 // the second argument, so that we know this is a post-increment or
10815 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000010816 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010817 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010818 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10819 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000010820 NumArgs = 2;
10821 }
10822
Richard Smithe54c3072013-05-05 15:51:06 +000010823 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10824
Douglas Gregor084d8552009-03-13 23:49:33 +000010825 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000010826 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010827 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10828 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010829
Craig Topperc3ec1492014-05-26 06:22:03 +000010830 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010831 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010832 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010833 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010834 /*ADL*/ true, IsOverloaded(Fns),
10835 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010836 return new (Context)
10837 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10838 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010839 }
10840
10841 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000010842 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000010843
10844 // Add the candidates from the given function set.
Richard Smithe54c3072013-05-05 15:51:06 +000010845 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010846
10847 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010848 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010849
John McCall4c4c1df2010-01-26 03:27:55 +000010850 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000010851 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000010852 /*ExplicitTemplateArgs*/nullptr,
10853 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000010854
Douglas Gregor084d8552009-03-13 23:49:33 +000010855 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010856 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010857
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010858 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10859
Douglas Gregor084d8552009-03-13 23:49:33 +000010860 // Perform overload resolution.
10861 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010862 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010863 case OR_Success: {
10864 // We found a built-in operator or an overloaded operator.
10865 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010866
Douglas Gregor084d8552009-03-13 23:49:33 +000010867 if (FnDecl) {
10868 // We matched an overloaded operator. Build a call to that
10869 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010870
Douglas Gregor084d8552009-03-13 23:49:33 +000010871 // Convert the arguments.
10872 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010873 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010874
John Wiegley01296292011-04-08 18:41:53 +000010875 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000010876 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000010877 Best->FoundDecl, Method);
10878 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010879 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010880 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010881 } else {
10882 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010883 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010884 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010885 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010886 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010887 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010888 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010889 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010890 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010891 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010892 }
10893
Douglas Gregor084d8552009-03-13 23:49:33 +000010894 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000010895 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010896 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010897 if (FnExpr.isInvalid())
10898 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000010899
Richard Smithc1564702013-11-15 02:58:23 +000010900 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000010901 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000010902 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10903 ResultTy = ResultTy.getNonLValueExprType(Context);
10904
Eli Friedman030eee42009-11-18 03:58:17 +000010905 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000010906 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010907 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000010908 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000010909
Alp Toker314cc812014-01-25 16:55:45 +000010910 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000010911 return ExprError();
10912
John McCallb268a282010-08-23 23:25:46 +000010913 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000010914 } else {
10915 // We matched a built-in operator. Convert the arguments, then
10916 // break out so that we will build the appropriate built-in
10917 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010918 ExprResult InputRes =
10919 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10920 Best->Conversions[0], AA_Passing);
10921 if (InputRes.isInvalid())
10922 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010923 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010924 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000010925 }
John Wiegley01296292011-04-08 18:41:53 +000010926 }
10927
10928 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000010929 // This is an erroneous use of an operator which can be overloaded by
10930 // a non-member function. Check for non-member operators which were
10931 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010932 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000010933 // FIXME: Recover by calling the found function.
10934 return ExprError();
10935
John Wiegley01296292011-04-08 18:41:53 +000010936 // No viable function; fall through to handling this as a
10937 // built-in operator, which will produce an error message for us.
10938 break;
10939
10940 case OR_Ambiguous:
10941 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10942 << UnaryOperator::getOpcodeStr(Opc)
10943 << Input->getType()
10944 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010945 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000010946 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10947 return ExprError();
10948
10949 case OR_Deleted:
10950 Diag(OpLoc, diag::err_ovl_deleted_oper)
10951 << Best->Function->isDeleted()
10952 << UnaryOperator::getOpcodeStr(Opc)
10953 << getDeletedOrUnavailableSuffix(Best->Function)
10954 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010955 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010956 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010957 return ExprError();
10958 }
Douglas Gregor084d8552009-03-13 23:49:33 +000010959
10960 // Either we found no viable overloaded operator or we matched a
10961 // built-in operator. In either case, fall through to trying to
10962 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000010963 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000010964}
10965
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010966/// \brief Create a binary operation that may resolve to an overloaded
10967/// operator.
10968///
10969/// \param OpLoc The location of the operator itself (e.g., '+').
10970///
10971/// \param OpcIn The BinaryOperator::Opcode that describes this
10972/// operator.
10973///
James Dennett18348b62012-06-22 08:52:37 +000010974/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010975/// considered by overload resolution. The caller needs to build this
10976/// set based on the context using, e.g.,
10977/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10978/// set should not contain any member functions; those will be added
10979/// by CreateOverloadedBinOp().
10980///
10981/// \param LHS Left-hand argument.
10982/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000010983ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010984Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000010985 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000010986 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010987 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010988 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000010989 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010990
10991 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10992 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10993 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10994
10995 // If either side is type-dependent, create an appropriate dependent
10996 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000010997 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000010998 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010999 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011000 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011001 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011002 return new (Context) BinaryOperator(
11003 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11004 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011005
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011006 return new (Context) CompoundAssignOperator(
11007 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11008 Context.DependentTy, Context.DependentTy, OpLoc,
11009 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011010 }
John McCall4c4c1df2010-01-26 03:27:55 +000011011
11012 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011013 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011014 // TODO: provide better source location info in DNLoc component.
11015 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011016 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011017 = UnresolvedLookupExpr::Create(Context, NamingClass,
11018 NestedNameSpecifierLoc(), OpNameInfo,
11019 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011020 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011021 return new (Context)
11022 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11023 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011024 }
11025
John McCall4124c492011-10-17 18:40:02 +000011026 // Always do placeholder-like conversions on the RHS.
11027 if (checkPlaceholderForOverload(*this, Args[1]))
11028 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011029
John McCall526ab472011-10-25 17:37:35 +000011030 // Do placeholder-like conversion on the LHS; note that we should
11031 // not get here with a PseudoObject LHS.
11032 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011033 if (checkPlaceholderForOverload(*this, Args[0]))
11034 return ExprError();
11035
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011036 // If this is the assignment operator, we only perform overload resolution
11037 // if the left-hand side is a class or enumeration type. This is actually
11038 // a hack. The standard requires that we do overload resolution between the
11039 // various built-in candidates, but as DR507 points out, this can lead to
11040 // problems. So we do it this way, which pretty much follows what GCC does.
11041 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011042 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011043 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011044
John McCalle26a8722010-12-04 08:14:53 +000011045 // If this is the .* operator, which is not overloadable, just
11046 // create a built-in binary operator.
11047 if (Opc == BO_PtrMemD)
11048 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11049
Douglas Gregor084d8552009-03-13 23:49:33 +000011050 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011051 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011052
11053 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011054 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011055
11056 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011057 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011058
Richard Smith0daabd72014-09-23 20:31:39 +000011059 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11060 // performed for an assignment operator (nor for operator[] nor operator->,
11061 // which don't get here).
11062 if (Opc != BO_Assign)
11063 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11064 /*ExplicitTemplateArgs*/ nullptr,
11065 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011066
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011067 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011068 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011069
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011070 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11071
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011072 // Perform overload resolution.
11073 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011074 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011075 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011076 // We found a built-in operator or an overloaded operator.
11077 FunctionDecl *FnDecl = Best->Function;
11078
11079 if (FnDecl) {
11080 // We matched an overloaded operator. Build a call to that
11081 // operator.
11082
11083 // Convert the arguments.
11084 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011085 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011086 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011087
Chandler Carruth8e543b32010-12-12 08:17:55 +000011088 ExprResult Arg1 =
11089 PerformCopyInitialization(
11090 InitializedEntity::InitializeParameter(Context,
11091 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011092 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011093 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011094 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011095
John Wiegley01296292011-04-08 18:41:53 +000011096 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011097 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011098 Best->FoundDecl, Method);
11099 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011100 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011101 Args[0] = Arg0.getAs<Expr>();
11102 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011103 } else {
11104 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011105 ExprResult Arg0 = PerformCopyInitialization(
11106 InitializedEntity::InitializeParameter(Context,
11107 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011108 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011109 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011110 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011111
Chandler Carruth8e543b32010-12-12 08:17:55 +000011112 ExprResult Arg1 =
11113 PerformCopyInitialization(
11114 InitializedEntity::InitializeParameter(Context,
11115 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011116 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011117 if (Arg1.isInvalid())
11118 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011119 Args[0] = LHS = Arg0.getAs<Expr>();
11120 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011121 }
11122
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011123 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011124 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011125 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011126 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011127 if (FnExpr.isInvalid())
11128 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011129
Richard Smithc1564702013-11-15 02:58:23 +000011130 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011131 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011132 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11133 ResultTy = ResultTy.getNonLValueExprType(Context);
11134
John McCallb268a282010-08-23 23:25:46 +000011135 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011136 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011137 Args, ResultTy, VK, OpLoc,
11138 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011139
Alp Toker314cc812014-01-25 16:55:45 +000011140 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011141 FnDecl))
11142 return ExprError();
11143
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011144 ArrayRef<const Expr *> ArgsArray(Args, 2);
11145 // Cut off the implicit 'this'.
11146 if (isa<CXXMethodDecl>(FnDecl))
11147 ArgsArray = ArgsArray.slice(1);
11148 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
11149 TheCall->getSourceRange(), VariadicDoesNotApply);
11150
John McCallb268a282010-08-23 23:25:46 +000011151 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011152 } else {
11153 // We matched a built-in operator. Convert the arguments, then
11154 // break out so that we will build the appropriate built-in
11155 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011156 ExprResult ArgsRes0 =
11157 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11158 Best->Conversions[0], AA_Passing);
11159 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011160 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011161 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011162
John Wiegley01296292011-04-08 18:41:53 +000011163 ExprResult ArgsRes1 =
11164 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11165 Best->Conversions[1], AA_Passing);
11166 if (ArgsRes1.isInvalid())
11167 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011168 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011169 break;
11170 }
11171 }
11172
Douglas Gregor66950a32009-09-30 21:46:01 +000011173 case OR_No_Viable_Function: {
11174 // C++ [over.match.oper]p9:
11175 // If the operator is the operator , [...] and there are no
11176 // viable functions, then the operator is assumed to be the
11177 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011178 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011179 break;
11180
Chandler Carruth8e543b32010-12-12 08:17:55 +000011181 // For class as left operand for assignment or compound assigment
11182 // operator do not fall through to handling in built-in, but report that
11183 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011184 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011185 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011186 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011187 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11188 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011189 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011190 if (Args[0]->getType()->isIncompleteType()) {
11191 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11192 << Args[0]->getType()
11193 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11194 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011195 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011196 // This is an erroneous use of an operator which can be overloaded by
11197 // a non-member function. Check for non-member operators which were
11198 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011199 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011200 // FIXME: Recover by calling the found function.
11201 return ExprError();
11202
Douglas Gregor66950a32009-09-30 21:46:01 +000011203 // No viable function; try to create a built-in operation, which will
11204 // produce an error. Then, show the non-viable candidates.
11205 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011206 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011207 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011208 "C++ binary operator overloading is missing candidates!");
11209 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011210 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011211 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011212 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011213 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011214
11215 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011216 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011217 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011218 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011219 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011220 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011221 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011222 return ExprError();
11223
11224 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011225 if (isImplicitlyDeleted(Best->Function)) {
11226 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11227 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011228 << Context.getRecordType(Method->getParent())
11229 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011230
Richard Smithde1a4872012-12-28 12:23:24 +000011231 // The user probably meant to call this special member. Just
11232 // explain why it's deleted.
11233 NoteDeletedFunction(Method);
11234 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011235 } else {
11236 Diag(OpLoc, diag::err_ovl_deleted_oper)
11237 << Best->Function->isDeleted()
11238 << BinaryOperator::getOpcodeStr(Opc)
11239 << getDeletedOrUnavailableSuffix(Best->Function)
11240 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11241 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011242 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011243 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011244 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011245 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011246
Douglas Gregor66950a32009-09-30 21:46:01 +000011247 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011248 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011249}
11250
John McCalldadc5752010-08-24 06:29:42 +000011251ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011252Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11253 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011254 Expr *Base, Expr *Idx) {
11255 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011256 DeclarationName OpName =
11257 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11258
11259 // If either side is type-dependent, create an appropriate dependent
11260 // expression.
11261 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11262
Craig Topperc3ec1492014-05-26 06:22:03 +000011263 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011264 // CHECKME: no 'operator' keyword?
11265 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11266 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011267 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011268 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011269 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011270 /*ADL*/ true, /*Overloaded*/ false,
11271 UnresolvedSetIterator(),
11272 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011273 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011274
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011275 return new (Context)
11276 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11277 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011278 }
11279
John McCall4124c492011-10-17 18:40:02 +000011280 // Handle placeholders on both operands.
11281 if (checkPlaceholderForOverload(*this, Args[0]))
11282 return ExprError();
11283 if (checkPlaceholderForOverload(*this, Args[1]))
11284 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011285
Sebastian Redladba46e2009-10-29 20:17:01 +000011286 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011287 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011288
11289 // Subscript can only be overloaded as a member function.
11290
11291 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011292 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011293
11294 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011295 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011296
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011297 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11298
Sebastian Redladba46e2009-10-29 20:17:01 +000011299 // Perform overload resolution.
11300 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011301 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011302 case OR_Success: {
11303 // We found a built-in operator or an overloaded operator.
11304 FunctionDecl *FnDecl = Best->Function;
11305
11306 if (FnDecl) {
11307 // We matched an overloaded operator. Build a call to that
11308 // operator.
11309
John McCalla0296f72010-03-19 07:35:19 +000011310 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011311
Sebastian Redladba46e2009-10-29 20:17:01 +000011312 // Convert the arguments.
11313 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011314 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011315 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011316 Best->FoundDecl, Method);
11317 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011318 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011319 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011320
Anders Carlssona68e51e2010-01-29 18:37:50 +000011321 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011322 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011323 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011324 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011325 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011326 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011327 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011328 if (InputInit.isInvalid())
11329 return ExprError();
11330
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011331 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011332
Sebastian Redladba46e2009-10-29 20:17:01 +000011333 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011334 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11335 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011336 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011337 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011338 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011339 OpLocInfo.getLoc(),
11340 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011341 if (FnExpr.isInvalid())
11342 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011343
Richard Smithc1564702013-11-15 02:58:23 +000011344 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011345 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011346 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11347 ResultTy = ResultTy.getNonLValueExprType(Context);
11348
John McCallb268a282010-08-23 23:25:46 +000011349 CXXOperatorCallExpr *TheCall =
11350 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011351 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011352 ResultTy, VK, RLoc,
11353 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011354
Alp Toker314cc812014-01-25 16:55:45 +000011355 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011356 return ExprError();
11357
John McCallb268a282010-08-23 23:25:46 +000011358 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011359 } else {
11360 // We matched a built-in operator. Convert the arguments, then
11361 // break out so that we will build the appropriate built-in
11362 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011363 ExprResult ArgsRes0 =
11364 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11365 Best->Conversions[0], AA_Passing);
11366 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011367 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011368 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011369
11370 ExprResult ArgsRes1 =
11371 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11372 Best->Conversions[1], AA_Passing);
11373 if (ArgsRes1.isInvalid())
11374 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011375 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011376
11377 break;
11378 }
11379 }
11380
11381 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011382 if (CandidateSet.empty())
11383 Diag(LLoc, diag::err_ovl_no_oper)
11384 << Args[0]->getType() << /*subscript*/ 0
11385 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11386 else
11387 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11388 << Args[0]->getType()
11389 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011390 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011391 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011392 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011393 }
11394
11395 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011396 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011397 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011398 << Args[0]->getType() << Args[1]->getType()
11399 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011400 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011401 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011402 return ExprError();
11403
11404 case OR_Deleted:
11405 Diag(LLoc, diag::err_ovl_deleted_oper)
11406 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011407 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011408 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011409 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011410 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011411 return ExprError();
11412 }
11413
11414 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011415 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011416}
11417
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011418/// BuildCallToMemberFunction - Build a call to a member
11419/// function. MemExpr is the expression that refers to the member
11420/// function (and includes the object parameter), Args/NumArgs are the
11421/// arguments to the function call (not including the object
11422/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011423/// expression refers to a non-static member function or an overloaded
11424/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011425ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011426Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011427 SourceLocation LParenLoc,
11428 MultiExprArg Args,
11429 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011430 assert(MemExprE->getType() == Context.BoundMemberTy ||
11431 MemExprE->getType() == Context.OverloadTy);
11432
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011433 // Dig out the member expression. This holds both the object
11434 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011435 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011436
John McCall0009fcc2011-04-26 20:42:42 +000011437 // Determine whether this is a call to a pointer-to-member function.
11438 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11439 assert(op->getType() == Context.BoundMemberTy);
11440 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11441
11442 QualType fnType =
11443 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11444
11445 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11446 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011447 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011448
11449 // Check that the object type isn't more qualified than the
11450 // member function we're calling.
11451 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11452
11453 QualType objectType = op->getLHS()->getType();
11454 if (op->getOpcode() == BO_PtrMemI)
11455 objectType = objectType->castAs<PointerType>()->getPointeeType();
11456 Qualifiers objectQuals = objectType.getQualifiers();
11457
11458 Qualifiers difference = objectQuals - funcQuals;
11459 difference.removeObjCGCAttr();
11460 difference.removeAddressSpace();
11461 if (difference) {
11462 std::string qualsString = difference.getAsString();
11463 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11464 << fnType.getUnqualifiedType()
11465 << qualsString
11466 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11467 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011468
David Majnemerb3e56542014-08-07 22:56:13 +000011469 if (resultType->isMemberPointerType())
11470 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11471 RequireCompleteType(LParenLoc, resultType, 0);
11472
John McCall0009fcc2011-04-26 20:42:42 +000011473 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011474 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011475 resultType, valueKind, RParenLoc);
11476
Alp Toker314cc812014-01-25 16:55:45 +000011477 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011478 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000011479 return ExprError();
11480
Craig Topperc3ec1492014-05-26 06:22:03 +000011481 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011482 return ExprError();
11483
Richard Trieu9be9c682013-06-22 02:30:38 +000011484 if (CheckOtherCall(call, proto))
11485 return ExprError();
11486
John McCall0009fcc2011-04-26 20:42:42 +000011487 return MaybeBindToTemporary(call);
11488 }
11489
John McCall4124c492011-10-17 18:40:02 +000011490 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011491 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011492 return ExprError();
11493
John McCall10eae182009-11-30 22:42:35 +000011494 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000011495 CXXMethodDecl *Method = nullptr;
11496 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11497 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000011498 if (isa<MemberExpr>(NakedMemExpr)) {
11499 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011500 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011501 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011502 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011503 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011504 } else {
11505 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011506 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011507
John McCall6e9f8f62009-12-03 04:06:58 +000011508 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011509 Expr::Classification ObjectClassification
11510 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11511 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011512
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011513 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000011514 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11515 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000011516
John McCall2d74de92009-12-01 22:10:20 +000011517 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000011518 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000011519 if (UnresExpr->hasExplicitTemplateArgs()) {
11520 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11521 TemplateArgs = &TemplateArgsBuffer;
11522 }
11523
John McCall10eae182009-11-30 22:42:35 +000011524 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11525 E = UnresExpr->decls_end(); I != E; ++I) {
11526
John McCall6e9f8f62009-12-03 04:06:58 +000011527 NamedDecl *Func = *I;
11528 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11529 if (isa<UsingShadowDecl>(Func))
11530 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11531
Douglas Gregor02824322011-01-26 19:30:28 +000011532
Francois Pichet64225792011-01-18 05:04:39 +000011533 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011534 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011535 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011536 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011537 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011538 // If explicit template arguments were provided, we can't call a
11539 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011540 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011541 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011542
John McCalla0296f72010-03-19 07:35:19 +000011543 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011544 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011545 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011546 } else {
John McCall10eae182009-11-30 22:42:35 +000011547 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011548 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011549 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011550 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011551 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011552 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011553 }
Mike Stump11289f42009-09-09 15:08:12 +000011554
John McCall10eae182009-11-30 22:42:35 +000011555 DeclarationName DeclName = UnresExpr->getMemberName();
11556
John McCall4124c492011-10-17 18:40:02 +000011557 UnbridgedCasts.restore();
11558
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011559 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011560 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011561 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011562 case OR_Success:
11563 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011564 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011565 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011566 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11567 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011568 // If FoundDecl is different from Method (such as if one is a template
11569 // and the other a specialization), make sure DiagnoseUseOfDecl is
11570 // called on both.
11571 // FIXME: This would be more comprehensively addressed by modifying
11572 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11573 // being used.
11574 if (Method != FoundDecl.getDecl() &&
11575 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11576 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011577 break;
11578
11579 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011580 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011581 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011582 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011583 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011584 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011585 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011586
11587 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011588 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011589 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011590 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011591 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011592 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011593
11594 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011595 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011596 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011597 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011598 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011599 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011600 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011601 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011602 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011603 }
11604
John McCall16df1e52010-03-30 21:47:33 +000011605 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011606
John McCall2d74de92009-12-01 22:10:20 +000011607 // If overload resolution picked a static member, build a
11608 // non-member call based on that function.
11609 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011610 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11611 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011612 }
11613
John McCall10eae182009-11-30 22:42:35 +000011614 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011615 }
11616
Alp Toker314cc812014-01-25 16:55:45 +000011617 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011618 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11619 ResultType = ResultType.getNonLValueExprType(Context);
11620
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011621 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011622 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011623 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011624 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011625
Eli Bendersky291a57e2014-09-25 23:59:08 +000011626 // (CUDA B.1): Check for invalid calls between targets.
11627 if (getLangOpts().CUDA) {
11628 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11629 if (CheckCUDATarget(Caller, Method)) {
11630 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11631 << IdentifyCUDATarget(Method) << Method->getIdentifier()
11632 << IdentifyCUDATarget(Caller);
11633 return ExprError();
11634 }
11635 }
11636 }
11637
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011638 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000011639 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011640 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011641 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011642
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011643 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011644 // We only need to do this if there was actually an overload; otherwise
11645 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011646 if (!Method->isStatic()) {
11647 ExprResult ObjectArg =
11648 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11649 FoundDecl, Method);
11650 if (ObjectArg.isInvalid())
11651 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011652 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000011653 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011654
11655 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011656 const FunctionProtoType *Proto =
11657 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011658 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011659 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011660 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011661
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011662 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011663
Richard Smith55ce3522012-06-25 20:30:08 +000011664 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011665 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011666
Anders Carlsson47061ee2011-05-06 14:25:31 +000011667 if ((isa<CXXConstructorDecl>(CurContext) ||
11668 isa<CXXDestructorDecl>(CurContext)) &&
11669 TheCall->getMethodDecl()->isPure()) {
11670 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11671
Chandler Carruth59259262011-06-27 08:31:58 +000011672 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000011673 Diag(MemExpr->getLocStart(),
11674 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11675 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11676 << MD->getParent()->getDeclName();
11677
11678 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011679 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011680 }
John McCallb268a282010-08-23 23:25:46 +000011681 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011682}
11683
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011684/// BuildCallToObjectOfClassType - Build a call to an object of class
11685/// type (C++ [over.call.object]), which can end up invoking an
11686/// overloaded function call operator (@c operator()) or performing a
11687/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000011688ExprResult
John Wiegley01296292011-04-08 18:41:53 +000011689Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000011690 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011691 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011692 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000011693 if (checkPlaceholderForOverload(*this, Obj))
11694 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011695 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000011696
11697 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011698 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011699 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011700
John Wiegley01296292011-04-08 18:41:53 +000011701 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11702 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000011703
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011704 // C++ [over.call.object]p1:
11705 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000011706 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011707 // candidate functions includes at least the function call
11708 // operators of T. The function call operators of T are obtained by
11709 // ordinary lookup of the name operator() in the context of
11710 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000011711 OverloadCandidateSet CandidateSet(LParenLoc,
11712 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000011713 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011714
John Wiegley01296292011-04-08 18:41:53 +000011715 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011716 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011717 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011718
John McCall27b18f82009-11-17 02:14:36 +000011719 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11720 LookupQualifiedName(R, Record->getDecl());
11721 R.suppressDiagnostics();
11722
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011723 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000011724 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000011725 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011726 Object.get()->Classify(Context),
11727 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000011728 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000011729 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011730
Douglas Gregorab7897a2008-11-19 22:57:39 +000011731 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011732 // In addition, for each (non-explicit in C++0x) conversion function
11733 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000011734 //
11735 // operator conversion-type-id () cv-qualifier;
11736 //
11737 // where cv-qualifier is the same cv-qualification as, or a
11738 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000011739 // denotes the type "pointer to function of (P1,...,Pn) returning
11740 // R", or the type "reference to pointer to function of
11741 // (P1,...,Pn) returning R", or the type "reference to function
11742 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000011743 // is also considered as a candidate function. Similarly,
11744 // surrogate call functions are added to the set of candidate
11745 // functions for each conversion function declared in an
11746 // accessible base class provided the function is not hidden
11747 // within T by another intervening declaration.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011748 std::pair<CXXRecordDecl::conversion_iterator,
11749 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000011750 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011751 for (CXXRecordDecl::conversion_iterator
11752 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000011753 NamedDecl *D = *I;
11754 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11755 if (isa<UsingShadowDecl>(D))
11756 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011757
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011758 // Skip over templated conversion functions; they aren't
11759 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000011760 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011761 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000011762
John McCall6e9f8f62009-12-03 04:06:58 +000011763 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011764 if (!Conv->isExplicit()) {
11765 // Strip the reference type (if any) and then the pointer type (if
11766 // any) to get down to what might be a function type.
11767 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11768 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11769 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000011770
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011771 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11772 {
11773 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011774 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011775 }
11776 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000011777 }
Mike Stump11289f42009-09-09 15:08:12 +000011778
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011779 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11780
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011781 // Perform overload resolution.
11782 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000011783 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000011784 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011785 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000011786 // Overload resolution succeeded; we'll build the appropriate call
11787 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011788 break;
11789
11790 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000011791 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011792 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000011793 << Object.get()->getType() << /*call*/ 1
11794 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000011795 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011796 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000011797 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011798 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011799 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011800 break;
11801
11802 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011803 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011804 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011805 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011806 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011807 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011808
11809 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011810 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000011811 diag::err_ovl_deleted_object_call)
11812 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000011813 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011814 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000011815 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011816 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011817 break;
Mike Stump11289f42009-09-09 15:08:12 +000011818 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011819
Douglas Gregorb412e172010-07-25 18:17:45 +000011820 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011821 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011822
John McCall4124c492011-10-17 18:40:02 +000011823 UnbridgedCasts.restore();
11824
Craig Topperc3ec1492014-05-26 06:22:03 +000011825 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000011826 // Since there is no function declaration, this is one of the
11827 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000011828 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000011829 = cast<CXXConversionDecl>(
11830 Best->Conversions[0].UserDefined.ConversionFunction);
11831
Craig Topperc3ec1492014-05-26 06:22:03 +000011832 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11833 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011834 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11835 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011836 assert(Conv == Best->FoundDecl.getDecl() &&
11837 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000011838 // We selected one of the surrogate functions that converts the
11839 // object parameter to a function pointer. Perform the conversion
11840 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011841
Fariborz Jahanian774cf792009-09-28 18:35:46 +000011842 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000011843 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011844 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11845 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011846 if (Call.isInvalid())
11847 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011848 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011849 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11850 CK_UserDefinedConversion, Call.get(),
11851 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011852
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011853 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011854 }
11855
Craig Topperc3ec1492014-05-26 06:22:03 +000011856 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000011857
Douglas Gregorab7897a2008-11-19 22:57:39 +000011858 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11859 // that calls this method, using Object for the implicit object
11860 // parameter and passing along the remaining arguments.
11861 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011862
11863 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011864 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011865 return ExprError();
11866
Chandler Carruth8e543b32010-12-12 08:17:55 +000011867 const FunctionProtoType *Proto =
11868 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011869
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011870 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000011871
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011872 DeclarationNameInfo OpLocInfo(
11873 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11874 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000011875 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011876 HadMultipleCandidates,
11877 OpLocInfo.getLoc(),
11878 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011879 if (NewFn.isInvalid())
11880 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011881
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011882 // Build the full argument list for the method call (the implicit object
11883 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000011884 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011885 MethodArgs[0] = Object.get();
11886 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11887
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011888 // Once we've built TheCall, all of the expressions are properly
11889 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000011890 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011891 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11892 ResultTy = ResultTy.getNonLValueExprType(Context);
11893
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011894 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011895 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011896 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11897 ResultTy, VK, RParenLoc, false);
11898 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011899
Alp Toker314cc812014-01-25 16:55:45 +000011900 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000011901 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011902
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011903 // We may have default arguments. If so, we need to allocate more
11904 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011905 if (Args.size() < NumParams)
11906 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011907
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011908 bool IsError = false;
11909
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011910 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000011911 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011912 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011913 Best->FoundDecl, Method);
11914 if (ObjRes.isInvalid())
11915 IsError = true;
11916 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011917 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011918 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011919
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011920 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011921 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011922 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011923 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011924 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000011925
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011926 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011927
John McCalldadc5752010-08-24 06:29:42 +000011928 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011929 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011930 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011931 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000011932 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011933
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011934 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011935 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011936 } else {
John McCalldadc5752010-08-24 06:29:42 +000011937 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011938 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11939 if (DefArg.isInvalid()) {
11940 IsError = true;
11941 break;
11942 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011943
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011944 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011945 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011946
11947 TheCall->setArg(i + 1, Arg);
11948 }
11949
11950 // If this is a variadic call, handle args passed through "...".
11951 if (Proto->isVariadic()) {
11952 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011953 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011954 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
11955 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000011956 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011957 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011958 }
11959 }
11960
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011961 if (IsError) return true;
11962
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011963 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011964
Richard Smith55ce3522012-06-25 20:30:08 +000011965 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000011966 return true;
11967
John McCalle172be52010-08-24 06:09:16 +000011968 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011969}
11970
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011971/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000011972/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011973/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000011974ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000011975Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11976 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000011977 assert(Base->getType()->isRecordType() &&
11978 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000011979
John McCall4124c492011-10-17 18:40:02 +000011980 if (checkPlaceholderForOverload(*this, Base))
11981 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011982
John McCallbc077cf2010-02-08 23:07:23 +000011983 SourceLocation Loc = Base->getExprLoc();
11984
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011985 // C++ [over.ref]p1:
11986 //
11987 // [...] An expression x->m is interpreted as (x.operator->())->m
11988 // for a class object x of type T if T::operator->() exists and if
11989 // the operator is selected as the best match function by the
11990 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000011991 DeclarationName OpName =
11992 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000011993 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011994 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000011995
John McCallbc077cf2010-02-08 23:07:23 +000011996 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011997 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000011998 return ExprError();
11999
John McCall27b18f82009-11-17 02:14:36 +000012000 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12001 LookupQualifiedName(R, BaseRecord->getDecl());
12002 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012003
12004 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012005 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012006 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012007 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012008 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012009
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012010 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12011
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012012 // Perform overload resolution.
12013 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012014 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012015 case OR_Success:
12016 // Overload resolution succeeded; we'll build the call below.
12017 break;
12018
12019 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012020 if (CandidateSet.empty()) {
12021 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012022 if (NoArrowOperatorFound) {
12023 // Report this specific error to the caller instead of emitting a
12024 // diagnostic, as requested.
12025 *NoArrowOperatorFound = true;
12026 return ExprError();
12027 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012028 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12029 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012030 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012031 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012032 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012033 }
12034 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012035 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012036 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012037 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012038 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012039
12040 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012041 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12042 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012043 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012044 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012045
12046 case OR_Deleted:
12047 Diag(OpLoc, diag::err_ovl_deleted_oper)
12048 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012049 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012050 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012051 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012052 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012053 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012054 }
12055
Craig Topperc3ec1492014-05-26 06:22:03 +000012056 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012057
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012058 // Convert the object parameter.
12059 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012060 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012061 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012062 Best->FoundDecl, Method);
12063 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012064 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012065 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012066
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012067 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012068 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012069 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012070 if (FnExpr.isInvalid())
12071 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012072
Alp Toker314cc812014-01-25 16:55:45 +000012073 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012074 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12075 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012076 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012077 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012078 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012079
Alp Toker314cc812014-01-25 16:55:45 +000012080 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012081 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012082
12083 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012084}
12085
Richard Smithbcc22fc2012-03-09 08:00:36 +000012086/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12087/// a literal operator described by the provided lookup results.
12088ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12089 DeclarationNameInfo &SuffixInfo,
12090 ArrayRef<Expr*> Args,
12091 SourceLocation LitEndLoc,
12092 TemplateArgumentListInfo *TemplateArgs) {
12093 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012094
Richard Smith100b24a2014-04-17 01:52:14 +000012095 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12096 OverloadCandidateSet::CSK_Normal);
Richard Smithbcc22fc2012-03-09 08:00:36 +000012097 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
12098 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000012099
Richard Smithbcc22fc2012-03-09 08:00:36 +000012100 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12101
Richard Smithbcc22fc2012-03-09 08:00:36 +000012102 // Perform overload resolution. This will usually be trivial, but might need
12103 // to perform substitutions for a literal operator template.
12104 OverloadCandidateSet::iterator Best;
12105 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12106 case OR_Success:
12107 case OR_Deleted:
12108 break;
12109
12110 case OR_No_Viable_Function:
12111 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12112 << R.getLookupName();
12113 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12114 return ExprError();
12115
12116 case OR_Ambiguous:
12117 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12118 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12119 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012120 }
12121
Richard Smithbcc22fc2012-03-09 08:00:36 +000012122 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012123 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12124 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012125 SuffixInfo.getLoc(),
12126 SuffixInfo.getInfo());
12127 if (Fn.isInvalid())
12128 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012129
12130 // Check the argument types. This should almost always be a no-op, except
12131 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012132 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012133 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012134 ExprResult InputInit = PerformCopyInitialization(
12135 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12136 SourceLocation(), Args[ArgIdx]);
12137 if (InputInit.isInvalid())
12138 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012139 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012140 }
12141
Alp Toker314cc812014-01-25 16:55:45 +000012142 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012143 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12144 ResultTy = ResultTy.getNonLValueExprType(Context);
12145
Richard Smithc67fdd42012-03-07 08:35:16 +000012146 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012147 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012148 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012149 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12150
Alp Toker314cc812014-01-25 16:55:45 +000012151 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012152 return ExprError();
12153
Craig Topperc3ec1492014-05-26 06:22:03 +000012154 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012155 return ExprError();
12156
12157 return MaybeBindToTemporary(UDL);
12158}
12159
Sam Panzer0f384432012-08-21 00:52:01 +000012160/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12161/// given LookupResult is non-empty, it is assumed to describe a member which
12162/// will be invoked. Otherwise, the function will be found via argument
12163/// dependent lookup.
12164/// CallExpr is set to a valid expression and FRS_Success returned on success,
12165/// otherwise CallExpr is set to ExprError() and some non-success value
12166/// is returned.
12167Sema::ForRangeStatus
12168Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12169 SourceLocation RangeLoc, VarDecl *Decl,
12170 BeginEndFunction BEF,
12171 const DeclarationNameInfo &NameInfo,
12172 LookupResult &MemberLookup,
12173 OverloadCandidateSet *CandidateSet,
12174 Expr *Range, ExprResult *CallExpr) {
12175 CandidateSet->clear();
12176 if (!MemberLookup.empty()) {
12177 ExprResult MemberRef =
12178 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12179 /*IsPtr=*/false, CXXScopeSpec(),
12180 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012181 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012182 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +000012183 /*TemplateArgs=*/nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012184 if (MemberRef.isInvalid()) {
12185 *CallExpr = ExprError();
12186 Diag(Range->getLocStart(), diag::note_in_for_range)
12187 << RangeLoc << BEF << Range->getType();
12188 return FRS_DiagnosticIssued;
12189 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012190 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012191 if (CallExpr->isInvalid()) {
12192 *CallExpr = ExprError();
12193 Diag(Range->getLocStart(), diag::note_in_for_range)
12194 << RangeLoc << BEF << Range->getType();
12195 return FRS_DiagnosticIssued;
12196 }
12197 } else {
12198 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012199 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012200 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012201 NestedNameSpecifierLoc(), NameInfo,
12202 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012203 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012204
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012205 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012206 CandidateSet, CallExpr);
12207 if (CandidateSet->empty() || CandidateSetError) {
12208 *CallExpr = ExprError();
12209 return FRS_NoViableFunction;
12210 }
12211 OverloadCandidateSet::iterator Best;
12212 OverloadingResult OverloadResult =
12213 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12214
12215 if (OverloadResult == OR_No_Viable_Function) {
12216 *CallExpr = ExprError();
12217 return FRS_NoViableFunction;
12218 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012219 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012220 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012221 OverloadResult,
12222 /*AllowTypoCorrection=*/false);
12223 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12224 *CallExpr = ExprError();
12225 Diag(Range->getLocStart(), diag::note_in_for_range)
12226 << RangeLoc << BEF << Range->getType();
12227 return FRS_DiagnosticIssued;
12228 }
12229 }
12230 return FRS_Success;
12231}
12232
12233
Douglas Gregorcd695e52008-11-10 20:40:00 +000012234/// FixOverloadedFunctionReference - E is an expression that refers to
12235/// a C++ overloaded function (possibly with some parentheses and
12236/// perhaps a '&' around it). We have resolved the overloaded function
12237/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012238/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012239Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012240 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012241 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012242 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12243 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012244 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012245 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012246
Douglas Gregor51c538b2009-11-20 19:42:02 +000012247 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012248 }
12249
Douglas Gregor51c538b2009-11-20 19:42:02 +000012250 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012251 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12252 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012253 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012254 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012255 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012256 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012257 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012258 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012259
12260 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012261 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012262 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012263 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012264 }
12265
Douglas Gregor51c538b2009-11-20 19:42:02 +000012266 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012267 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012268 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012269 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12270 if (Method->isStatic()) {
12271 // Do nothing: static member functions aren't any different
12272 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012273 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012274 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012275 // UnresolvedLookupExpr holding an overloaded member function
12276 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012277 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12278 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012279 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012280 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012281
John McCalld14a8642009-11-21 08:51:07 +000012282 assert(isa<DeclRefExpr>(SubExpr)
12283 && "fixed to something other than a decl ref");
12284 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12285 && "fixed to a member ref with no nested name qualifier");
12286
12287 // We have taken the address of a pointer to member
12288 // function. Perform the computation here so that we get the
12289 // appropriate pointer to member type.
12290 QualType ClassType
12291 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12292 QualType MemPtrType
12293 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12294
John McCall7decc9e2010-11-18 06:31:45 +000012295 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12296 VK_RValue, OK_Ordinary,
12297 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012298 }
12299 }
John McCall16df1e52010-03-30 21:47:33 +000012300 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12301 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012302 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012303 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012304
John McCalle3027922010-08-25 11:45:40 +000012305 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012306 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012307 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012308 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012309 }
John McCalld14a8642009-11-21 08:51:07 +000012310
12311 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012312 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012313 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012314 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012315 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12316 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012317 }
12318
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012319 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12320 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012321 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012322 Fn,
John McCall113bee02012-03-10 09:33:50 +000012323 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012324 ULE->getNameLoc(),
12325 Fn->getType(),
12326 VK_LValue,
12327 Found.getDecl(),
12328 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012329 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012330 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12331 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012332 }
12333
John McCall10eae182009-11-30 22:42:35 +000012334 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012335 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012336 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012337 if (MemExpr->hasExplicitTemplateArgs()) {
12338 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12339 TemplateArgs = &TemplateArgsBuffer;
12340 }
John McCall6b51f282009-11-23 01:53:49 +000012341
John McCall2d74de92009-12-01 22:10:20 +000012342 Expr *Base;
12343
John McCall7decc9e2010-11-18 06:31:45 +000012344 // If we're filling in a static method where we used to have an
12345 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012346 if (MemExpr->isImplicitAccess()) {
12347 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012348 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12349 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012350 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012351 Fn,
John McCall113bee02012-03-10 09:33:50 +000012352 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012353 MemExpr->getMemberLoc(),
12354 Fn->getType(),
12355 VK_LValue,
12356 Found.getDecl(),
12357 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012358 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012359 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12360 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012361 } else {
12362 SourceLocation Loc = MemExpr->getMemberLoc();
12363 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012364 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012365 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012366 Base = new (Context) CXXThisExpr(Loc,
12367 MemExpr->getBaseType(),
12368 /*isImplicit=*/true);
12369 }
John McCall2d74de92009-12-01 22:10:20 +000012370 } else
John McCallc3007a22010-10-26 07:05:15 +000012371 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012372
John McCall4adb38c2011-04-27 00:36:17 +000012373 ExprValueKind valueKind;
12374 QualType type;
12375 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12376 valueKind = VK_LValue;
12377 type = Fn->getType();
12378 } else {
12379 valueKind = VK_RValue;
12380 type = Context.BoundMemberTy;
12381 }
12382
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012383 MemberExpr *ME = MemberExpr::Create(Context, Base,
12384 MemExpr->isArrow(),
12385 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012386 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012387 Fn,
12388 Found,
12389 MemExpr->getMemberNameInfo(),
12390 TemplateArgs,
12391 type, valueKind, OK_Ordinary);
12392 ME->setHadMultipleCandidates(true);
Richard Smith4f6a2c42012-11-14 07:06:31 +000012393 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012394 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012395 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012396
John McCallc3007a22010-10-26 07:05:15 +000012397 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012398}
12399
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012400ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012401 DeclAccessPair Found,
12402 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012403 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012404}